Quick learning: C++ Programming in ONE Hour
(By Dr. Leo Hu)
You can create a C++ program in only one hour, even though you have no knowledge of programming.
Let's begin!
1.Define a C++ program
A C++ program consists of a function called main() that looks like
int main() {
return 0;
}
where
int indicates that function main() will return an integer to whatever calls it. When an operating system calls the C++ program, it returns an integer back to the operating system.
The term main is the function name.
The parentheses () enclose the function parameter list, which may pass data as parameters into the function, or out of the function. When there is no parameter, the parenthesis encloses nothing and is empty.
The data type int, the function name main, and the parentheses for a parameter list together form the function header.
The curly bracket { marks the beginning of the function body, and } marks the end of the function body.
Inside the function body, there may have one or more statements. A statement is a programming instruction like an English sentence, which tells the computer what to do. A statement ends with semicolon (;). The last statement of function main() is a return statement, which is, generally,
return 0;
and means that function main() has successfully completed. The word return is a reserved word (or called keyword) in programming language C++.
Attention: A reserved word, or a keyword, cannot be used to name any of the programmer's identifiers.
Note: The complete set of reserved keywords can be reviewed at https://en.cppreference.com/w/cpp/keyword
Attention: a statement in C++ shall end with a semicolon ';'.
The keyword return is followed with an integer that has been defined by the program caller. Here the program caller is the operating system. Microsoft Windows operating systems has defined
0 - success
1 - Informational
2 - Warning
3 - Error
Therefore, statement
return 0;
means the program has completed with success. Other operating systems have the same effect.
Tip: To increase program source code readability, we may add spaces between items and indentations before statements. We may use spacebar to add space, and tab key to add indentations in a C++ program source code. It doesn't matter how many spaces or how many indentations are added in a C++ program source code, but we should keep in mind that we apply spaces and indentations to beautify our code and improve readability of our programs. In this simple program, we have added a space between int and main(), and an indentation before return statement. Theoretically, you can write your code in one line, like
int main(){return 0;}
but this is not good programming practice. Dividing a program code in lines is also a way to improve readability.
2.Add comments
If you want to explain something to your program reader (or remind yourself), you may add comments in your source code.
Attention: A comment is not to be used by C++ language compiler but by your reader and yourself for understanding the code. The C++ language compiler, which translate a C++ program source code into machine code, simply omits comments in a program source code.
For example, we may add comments a in the above simple program, and it looks like
// Online C++ compiler to run C++ program online
int main() {
// Write C++ code here
return 0;
}
In this program, there are two comments that start with double slashes "//". However, a comment can be enclosed between (/*) and (*/), and when a comment is written on more than one line, we must use (/*) and (*/) to enclose it. For example, the above program can be written as below without any syntax change of C++ program:
/* Online C++ compiler
to run C++ program online
*/
int main() {
/* Write C++ code here*/
return 0;
}
3.Add a statement to do something
Let's add a statement to display "Hello World!" on the screen. The program may look like
// Online C++ compiler to run C++ program online
int main() {
// Write C++ code here
std::cout << "Hello world!";
return 0;
}
Here, statement
std::cout << "Hello world";
display text Hello world on the screen, where std::cout is an object of the std::ostream class in C++ that represents the standard output stream. It is used to output data to the console or other output devices. By default, it stands the console. Output stream operator (<<) is used to insert data into the output stream.
Note: terms of object and class will be explained in more depth soon.
Before we can use any code pre-defined in another file, such as std::cout pre-defined in <iostream>, we must add that file so that the pre-defined code can be used in our program. So, the program should be rewritten as
// Online C++ compiler to run C++ program online
#include <iostream>
int main()
{
// Write C++ code here
std::cout << "Hello world!";
return 0;
}
Here, #include <iostream>, is called a preprocessor directive in C++ that tells the compiler to include a file, called library, in the source code program.
Hands-on:
Click the link, https://www.programiz.com/cpp-programming/online-compiler/, to use the online C++ programming tool to watch the execution of the program we discussed above. This tool has an editor in the left pane that host the program source code, and the program execution result shall be displayed in the Output in the right pane as shown in Figure 1 below.
Figure 1. Online C++ compiler
Note: the source code editor displays line numbers in the left side for convenience to edit the code.
The source code of the discussed simple program has been loaded in the editor automatically, so you don't have to enter manually.
Click the Run button in the top-right corner of the editor, you should see the display of Output in the right pane as shown in Figure 2 below:
Figure 2. An execution example of a C++ program
If you are interested in verifying the use of comments, you may remove the comments lines and click the Run button again. You should see that the output is exactly the same as above.
4.Input /Output in a C++ program
A program is essentially a file that ask the computer to read input, to process the input data, and to produce output, which is described as the input-process-output (IPO) model.
In the above program, we have used a simple output statement
std::cout << "Hello world!";
Generally, we use pre-defined functions and utilities to create our input and output. As stated above, we need have the #include preprocessing directive such as
#include <iostream>
before any code in the program. In this directive file, <iostream>, is a header file in C++ that provides input and output functionality to the console. It defines the standard input/output stream objects std::cin and std::cout, which are used to read input from the user and write output to the console, respectively. The <iostream> header file is included in C++ programs using the preprocessor directive #include <iostream>.
Now, let's add an input statement. Suppose we ask the user of the program to enter his/her first name, so that we may greet him/her in the output. What should we do? We should do a few things in a sequence:
1) declare a variable of string type such as firstName to hold the first name to be input by the user
2) remind the user what to do by displaying an instruction
3) read input from the user
4) display the greeting that contains the first name
The program shall look like
/*A C++ program with input/output */
#include <iostream>
#include <string>
int main()
{
// declare variable firstName to hold the first name
std::string firstName;
// tell the user what to do
std::cout << "Enter your first name: ";
// read input from the user
std::cin >> firstName;
// display a greeting with the first name
std::cout << "Hello, " << firstName << "!\n";
return 0;
}
Hands-on:
Click the link the online C++ compiler at Online C++ Compiler (programiz.com), copy or type the above code into the source code editor, click the Run button, you should read the instruction in the Output space, type in your first name and press enter, you should see the greeting. The execution looks like below:
Figure 3. A C++ program with input/output
In this program, the string variable firstName is declared as a std::string object. Similar to std::cout, std::string is pre-defined in another header file, <string>, so that we must use preprocessor directive to include the header file such as
#include <string>
in the beginning of the program file. If multiple header files are included in a program file, it doesn't matter the sequence of the preprocessor directives.
The input statement uses predefined input stream object std::cin to input string to the string variable firstName. Similarly, the output statement uses predefined output stream object std::cout to output the string "Hello", then the value of the string variable firstName, that has obtained its value from the user input in std::cin earlier.
Note: std is short for standard, cin is for console of input, and cout is for console output.
In C++, the >> operator is called the stream input operator. It is used to read data from an input stream, such as std::cin, into a variable or object. The << operator is called the stream output operator. It is used to write data to an output stream, such as std::cout, from a variable or object.
Tip: since << and >> are stream operators, they are designed to operate on streams of data. Therefore, they can be used multiple times in one statement to handle more than one data item. For example, if you need input data for two variables, firstName and lastName, you may design an input statement like
std::cin >> firstName >> lastName;
If you need to output multiple data items, you may desgn an output statement like
std::cout << firstName << lastName;
Please enter the program below in Online C++ Compiler (programiz.com), click the Run button, follow the instruction to enter your first name and last name, press Enter key, observe the result.
#include <string>
#include <iostream>
int main() {
std::string firstName, lastName;
std::cout << "Enter your first name and last name: ";
std::cin >> firstName >> lastName;
std::cout << "Hello, " << firstName << " "<<lastName << "!\n";
return 0;
}
If everything goes well, the screen should look like
Figure 4. Execution of a C++ program with input stream /output stream
Attention: when you type in your fist name and last name, you should use a space to separate them.
Attention: since C++ is an expansion of C, C++ compilers can compile pure C code. However, compiling C code with a C++ compiler can cause issues because, for example, C++ is stricter about types than C, and C++ has new reserved keywords (such as class, namespace, etc.) to support object-oriented programming so that these new keywords cannot be used as users' identifiers.
5. Using namespace
You should have seen that prefix std:: is applied for predefined class and objects string, cin, and cout. Why? because these class and objects are defined in the namespace called std. If you do not apply the prefix std::, C++ compiler does not identify them. If you want to remove the prefix std:: from your code, you must add a using directive before any program code. Generally, we add it after the include preprocessor directives. For example, the program below is the same as the one above:
#include <string>
#include <iostream>
using namespace std;
int main() {
string firstName, lastName;
cout << "Enter your first name and last name: ";
cin >> firstName >> lastName;
cout << "Hello, " << firstName << " "<<lastName << "!\n";
return 0;
}
The using directive
using namespace std;
shall bring all the names in the std namespace into the current scope, so that you don't have to add the prefix std:: to those terms pre-defined in this namespace.
If you enter the program source code in the Online C++ Compiler (programiz.com), the result should look like
Figure 5. Using namespace std
You can also define your own namespace.
To define a user-defined namespace in C++, you can use the `namespace` keyword followed by the name of the namespace you want to create. Here is an example:
namespace myNamespace {
// code here
}
This creates a new namespace called `myNamespace`. You can then use this namespace to define your own functions, classes, and variables. For example:
namespace myNamespace {
int myFunction(int x) {
return x * 2;
}
}
This creates a new function called `myFunction` inside the namespace named `myNamespace`. To use this function, you would need to qualify it with the namespace name like this:
int result = myNamespace::myFunction(5);
This calls the `myFunction` function inside the `myNamespace` namespace with an argument of `5` and assigns the result to the `result` variable. This is similar to use cin, cout that are defined in the 'std' namespace. You must add the namespace prefix to the items defined in the namespace.
Congratulations! You have learned how to create a very basic (and simple) C++ program.
Now you can move on to learn more C++ programming language to hone your skills in C++ programming.
References:
https://en.wikipedia.org/wiki/Compatibility_of_C_and_C%2B%2B.
https://learn.microsoft.com/en-us/cpp/cpp/namespaces-cpp?view=msvc-170.
https://learn.microsoft.com/en-us/cpp/standard-library/iostream?view=msvc-170.
https://stackoverflow.com/questions/5228056/can-i-use-c-compiler-to-compile-c-source-code.
https://stackoverflow.com/questions/76816428/using-namespaces-and-separate-compilation-in-c.
https://www.codingninjas.com/studio/library/what-is-namespace.
https://www.learncpp.com/cpp-tutorial/user-defined-namespaces-and-the-scope-resolution-operator/.
https://www.programiz.com/cpp-programming/library-function/iostream.