Introduction: How to Write a Simple C++ Program
In this tutorial, you will learn how to write a program in the C++ programming language. This will go over 10 steps that will explain a simple C++ program. The topics that each step cover in this tutorial are often used in more complex C++ programs. This is only a simple tutorial designed for new C++ programmers and consequently only covers some of the basic topics in C++. C++ programming is one of the most popular languages and consequently, one of the most useful to know.
The following code is the premise for which the tutorial is written on:
// This is a line comment
/*This is
a multiline
comment */
//This has libraries to use input and output
#include
//This has libraries for string operations
#include
//This has standard c libraries
#include
//This includes time libraries for c
#include
int main() {
std::cout << "Do you want to guess a number from 0-9?(yes or no)" << std::endl; // prints to the console
std::string response; // declares a string variable named response
getline(std::cin, response); //gets a line from std::cin and stores it in response
std::srand(std::time(0)); // needed once per program run
int random_number = std::rand() % 10; // gets a random number from 0-9
int guess = -1;
int number_of_guesses = 0;
std::cout << random_number << std::endl;
if (response.compare("yes") == 0) {
while (guess != random_number) {
std::cin >> guess;
number_of_guesses = number_of_guesses + 1;
}
}
else {
std::cout << "You're no fun!" << std::endl;
}
if (guess != -1) {
std::cout << "Number: " << random_number << std::endl;
std::cout << "Number of Guesses: " << number_of_guesses << std::endl;
std::cout << "Congratulations you guessed the number!" << std::endl;
}
system("pause");
return 0;
}
Step 1: Download and Install an IDE
The first step to developing your C++ program will be to download an IDE (Integrated Developing Environment). An IDE often includes a compiler, text editor, and often includes a debugger. Using IDEs makes programming simpler. Three IDEs that I have used and would recommend are the following;
Dev C++
Visual Studio
Eclipse
Here's a link to install DevC++ if you choose to use it:
http://www.youtube.com/watch?v=Y8So6Hh-ZSs
Step 2: Commenting
Though comments in programming don't change how the code works, it is important in communicating what a program does to future developers. Commenting is more important in larger programs, but is also good to use for smaller programs to develop good habits. There are two basic ways to comment. The first is the line comment. Any line that starts with \\ is a comment. Also any code between /* and */ are comments. This is shown in the picture corresponding to this step.
Step 3: #include Directives
After comments, #include statements are written. These lines allow us to specify libraries, or to use code we have written in other files. In the example program, we include a library to use C++ input and output streams, a library to be able to use strings, the c standard library, and a time library. These libraries will enable us to use more operations further on in the program.
Step 4: Main Function
The main function line will be in almost any program you will write. This is where the program will start to run. The main function often is written in the form int main((int argc, char **argv)). This would allow us to pass arguments to our main function, but can be ignored for this program.
Step 5: Variables and Variable Types
In C++, depending on what type of data is being dealt with, different data types might be necessary. The data type used in the picture on this page shows two variables, guess and number_of_guesses, both of type int. They can hold any integer value as their name indicates. There are different other types of variables. Other basic kind of variables include float, double and char. A char can hold a single character, while a float and double can hold decimal values. An example of a char would be the character 'c'. A value that a float or double could store could be the value 1.5. The example program for this tutorial, in addition to using int, uses the type Std::string. This type can hold a sequence of characters.
In the example the value -1 is stored in guess and 0 is stores in number_of_guesses.
Step 6: Printing to Console
In C++, text can be printed to the console by sending data to std::cout. This can include basic data types. The std::endl adds a new line to the output. This is the C++ way to do this. C++ supports most functionality from C. This includes the printf function. Instead of the following code, it could instead be written as the following:
printf("Number: %d \n",random_number);
printf("Number of Guesses: %d \n",number_of_guesses);
printf("Congratulations you guessed the number! \n");
In the printf function, the text entered between the quotes is the text displayed. After the quotes and the comma, the variables printed out are listed. They are printed out in order and must correspond to a %d, %c or other sequence starting with the percent sign. The \n character displays a new line.
Step 7: Reading From the Console
In C++, text can be read from the console by sending data from std::cin and storing in a variable. The console waits until user input when the std::cin function is called. After the user types something in, the program will attempt to store it in guess. In this example, no error checking is done, so if something other than an integer were typed in, the program would likely crash.
Step 8: Arithmetic Operations and Assignment Operator
The assignment operator (= sign) assigns the value from the right side of the equals to the variable on the left side of the equals. For this to work properly, the left side must be a variable.
Arithmetic operations allow mathematical operations to be performed on numbers. There are many operators that can be used to operate on numbers. They include addition (+ sign), subtraction ( - sign), multiplication (x sign) among others. In the line of code, the number_of_guesses gets assigned its previous value plus 1.
Step 9: Conditional (if) Statements
Conditional statements (if statements) change what code runs next depending on what is inside the parenthesis next to an if statement. First the inside of the parenthesis is evaluated. In this instance, if response.compare ( a function from the string library) return 0, the code following it is executed. The compare function returns 0 when the string calling it (response in this instance) is equivalent. Note that strings and basic types use different comparisons. If response is anything other than "yes", "You're no fun!" will be printed to the console. Case does matter.
Step 10: Loops
Loops are almost always used with if statements and run until a certain condition is met. Inside the parenthesis next to the while loop is essentially an if statement. If the statement is true, the program runs until the closing bracket of the while loop and the condition is evaluated again and if it is true, the program runs until the closing bracket of the while loop. This cycle continues until the condition (guess != random_number) isn't true anymore. This loop runs until guess doesn't equal the random_number variable.
Step 11: Final Thoughts
This tutorial left out a lot basics essential to programming in C++, but hopefully was useful in providing an example for some basic C++ programming. If you are more serious about programming, many other websites offer tutorials and can be found through a search through google or another search engine.
12 Comments
Question 2 years ago on Step 6
What does std::endl means?
Tip 3 years ago on Step 9
I made it
Question 3 years ago
Hey guys i need help solving this please
1. A program is required to compute the volume of a cube given by the formula; V = L*B*H*. Design this program using an algorithm of your choice; and convert the algorithm into a C++ Program
2. Ushirika Society pays 5% interest on shares exceeding Ksh 100,000 and 3% on shares that do not meet the target. However no interest is paid on deposits in the members bank account. Design a flowchart and a C++ source program that can prompt, calculate and display the shares, deposits, interests and total savings on the screen for a member
3. Kambo Company pays employee gratuity on retirement that can be computed using the formula: Gratuity = (Salary x Fixed Rate x Number of Years Worked) + One Month Salary. Formulate an Algorithm that can be used to calculate the gratuity and write a C++ program that can be used for the computation
Question 4 years ago on Step 3
In which condition #imclude is used?
Question 5 years ago on Step 4
what is the procedure to download an IDE?
Question 5 years ago on Step 11
What is mean by function should return a value
5 years ago
I need Help, please help...Write a program that will
upper limit in the form of integer numbers.
/ sum all those numbers between upper limit and lower limit (including
the lower and upper limits) which are NOT multiple of 4.
the remaining integer numbers up until the upper limit is reached.
aggregate sum of all numbers for the given range.
Make sure that lower limit
entered by the user should be greater than zero. Also the upper limit value
entered by the user should be greater than the lower limit value.
7 years ago
Great article here is another series for beginners C++http://psychocodes.in/blog_view.php?tutorial_id=23
8 years ago on Introduction
Write a c++ program for hostel
administrator. Assume that there r 50 rooms in a hostel ,room and student.
Student will store registration number , batch and name of a student. Room will
comprise of room no, status (free or reserved) and student. Hostel will use an
array size 50 of room objects. Include necessary constructors and member
functions to enter and display data in each class. Program will provide
following menu options to the user.
-Reserve a room
-Cancel room reservation.
-Display information of
reserved room.
-Display information of free
rooms.
-Search by reg no.
-Search by student name.
-Exit-
8 years ago
What IDE did you use? I use Code::Blocks, and I had to make some major modifications to your source code. They were relatively quick, though, so props to you.
8 years ago on Introduction
Write the C++ language program that should fulfill the following requirements:
Program should contain two classes as “Student” and “Instructor”. Within main() function, create the objects of these two classes. Display your student ID and name by passing as attributes(student ID, name) while instantiating the object of the “Student” class. Using the object of the Instructor Class, call its member function Input() to take input for the height of the 8 instructors then call its member function print() to display the average height of the instructors.
Declare data members by private and member functions by public access specifier for both classes.
9 years ago on Introduction
This is a good instructable, but I would suggest refactoring a lot of this into separate functions, to illustrate good separation of responsibility, and to demonstrate functions.
e.g. something like the following
int main() {
bool userWantsToPlay = GetUserWantsToPlay();
if (userWantsToPlay)
{
SeedRandomNumberGenerator();
int randomNumber = GetRandomNumber();
int numberOfGuesses = 0;
int userGuess = -1;
while (userGuess != randomNumber)
{
userGuess = GetUserGuess();
numberOfGuesses++;
}
DisplayResults(randomNumber, numberOfGuesses);
}
bool GetUserWantsToPlay()
{
std::cout << "Do you want to guess a number from 0-9?(yes or no)" << std::endl; // prints to the console
std::string response; // declares a string variable named response
getline(std::cin, response); //gets a line from std::cin and stores it in response
return (response.compare("yes") == 0)
}
etc