2 C++ Fundamentals
Hussam Ghunaim, Ph.D.
Learning Objectives
At the end of reading this chapter, you will be able to:
- Write your first program
- Understanding data types in C++
- Implement branching and loops in your code
- Describe best practices for writing code
Introduction
Writing code always goes hand in hand with data. We can not think of writing any useful code without being able to handle data. Handling data in real-life scenarios usually requires data structures that you will learn about in higher-level courses. However, as this is your first course in programming, we will start with the smallest memory units that can store data, called variables and constants.
Variables vs. Constants
type variable_name;
int sum;
To better understand how variables are created and used, Figure 1 depicts the computer’s main memory, RAM. When you declare a variable, a label will be created with the variable name that points to a specific location in the RAM. Remember

that RAM looks like a huge array of memory locations that can be used by all running programs, including the operating system itself. This depiction is not entirely accurate, but it is a good starting point. Later, when we discuss further the types, we can elaborate more on how data is stored in RAM.
var = 10;
const type constant_name;
const int MY_CONSTANT = 1100;
Expressions and Operators
Example 01
Study the provided code that shows how to write some basic expressions. Additionally, note how we can add comments in C++. There are two ways to do this. For single-line comments, we use //
. For multiple-line comments, we use /* */
. Comments are ignored by the compilers and hence they are not considered part of the code. However, they’re extremely important for making the code understandable to humans. This is especially true in large projects where multiple developers need to understand each other’s code.
NOTE: For division, we use the operator /
, which is called a forward slash. This is different from the other similar slash \
, which is called a backward slash.
Exercise 01
- Declare two integer variables, num1 and num2. Initialize num1 with 15 and num2 with 5. Then, calculate the sum of both numbers and store the result in the variable addition.
- Using the variables in exercise 1, calculate the difference, multiplication, and division. Store the results in variables named subtraction, multiplication, and division, respectively.
- Declare a constant integer named MAX_VALUE and initialize it with the value 1000.
- In all previous exercises, write appropriate comments to explain the code and the expected output.
Writing Your First Program
Example 02
Run the provided code and study how the code is written.
The first two lines will appear in almost all your programs in this book. The first line is used to include the <iostream>
library. Libraries contain prewritten and tested code by professionals. They contain a lot of useful code that is ready for us to use. For example, to print out a message to the console, we use the stream cout. We do not know how exactly this stream is implemented. However, all that we need to know is how to use it, relieving a huge amount of work off our shoulders! Therefore, you will learn how to include a couple of more libraries as you proceed in this book. The second line is used to specify what namespace we need to use. This is important to avoid any conflicts in naming. As libraries can be huge, two or more libraries may have different implementations but with the same name, which can cause conflict in your code. Later, you will learn how to create your own namespaces.
Line 4 defines the main function in the code. You can think of functions as containers that contain the code. This function is called main because it is the first function to execute whenever you run your code; that is, it must appear only once in every program. No more than one main function in the same application is acceptable. The body of the main function starts with open curly braces {
and ends with the close curly braces }
in line 8. All the main code must be inside those symbols.
Line 5 has the declaration and initialization of the variable num as explained earlier in this chapter. Line 6 prints out a message to the console. We do this by using the stream cout that prints everything sent to it on the console. cout works with the insertion operator <<
. The message we want to print on the console is surrounded by quotation marks " "
to differentiate it from the code. As you can note from line 6, cout stream can accept a sequence of pieces to print out on the console. In this example, after printing the message surrounded by the quotation, it prints the value stored in the variable num, followed by a blank line created by the object endl, which stands for ‘end of the line’. Notice that when variable names appear in the cout line of code, the value stored in that variable will print out to the console, not the variable name itself.
Every statement in C++ must end with a semicolon. Line 7 has the return statement. For now, it is sufficient to understand that some functions must return something when they finish running. In this example, the main function will return 0
when it finishes running.
In many cases, we want users to enter some data. This makes programs interact with the users. We use the cin stream that reads users’ input from the keyboard. cin works with the extraction operator >>
. Pay attention to not confusing extraction and insertion operators by noticing the direction in which the arrows point.
Example 03
Run the provided code and study how the code is written.
To simplify the code, cout and cin streams allow for a sequence of operations to be done in the same line of code. For example, in line 7 of the code, cin is used to read values for two variables rather than writing two separate lines. This becomes possible because the >>
operator reads input until a whitespace is encountered, effectively using spaces to separate different values. Similarly, line 9 shows how we can print out several pieces of data using the cout stream.
Exercise 02
Write a program that asks users to enter the distance in miles and time in hours, then it calculates the speed using this formula: Speed = Distance / Time. The program should print the result as follows: The speed of the vehicle is …. miles/hour!
Note: Because this program calculation might involve numbers with decimals, using int as a data type will be erroneous. Therefore, you must use double as the declared variables’ type.
Exercise 03
Write a program that asks users to enter the radius of a sphere and then calculates its volume using this formula: sphere volume = (4.0/3.0) * PI * radius3. The value of the mathematical constant PI must be declared as a global constant and initialized to 3.14. The final result should be printed out to the console as “The volume of the sphere is ……. cubic units”.
NOTE: In the sphere volume formula, we put the fraction as 4.0/3.0. This is important to enforce the result to be of type double, otherwise, if we put 4/3, the results will be 1 instead of 1.33!! This error is known as the integer division error. If we used integers to perform division, the answer would be an integer as well, causing the loss of the fraction part from the result. To enforce the result to be double, that is, it can have a fraction part, we must write either the denominator or the numerator (or both) as a double number. This topic will be explained further in this chapter when we discuss type casting.
Exercise 04
Write a program to calculate simple interest. The program should ask users for the principal amount, the rate of interest entered as a whole number, and the time in years. It then calculates the simple interest using the formula: Interest = (Principal * Rate * Time) / 100 and displays the result.
Escape Characters
Sometimes it is useful to add basic formatting to the printed text, like adding a new line , printing the quotation with the output text, or adding more horizontal space, and so on. To do that you can use escape characters where the compiler treats them differently. Any character sequence that starts with a backslash \ and is followed by another character (or digits) will make the compiler treat that combination as one special character, not as literal text. Table 01 shows how you can use some common sequence characters.
Escape Characters |
What It Does | Example Code | Example Output |
\\\\ | Inserts a single backslash | cout << “Path: C:\\\\Program Files\\\\MyApp\n”; | Path: C:\Program Files\MyApp |
\’ | Inserts a single quotation mark | cout << “It\\’s C++ fun\n”; | It’s C++ fun |
\” | Inserts double quotation marks | cout << “She said, \”Hello\”\n”; | She said, “Hello” |
\n | Starts a new line | cout << “Error:\nInvalid input\n”; | Error: Invalid input |
More about Types
Type Name | Memory Used | Size Range | Precision |
bool |
1 byte | True or False | N/A |
char |
1 byte | -128 to 127 or 0 to 255 | N/A |
short |
2 bytes | -32768 to 32767 | N/A |
int |
4 bytes | -2147483648 to 2147483647 | N/A |
long int |
4 bytes | -2147483648 to 2147483647 | N/A |
float |
4 bytes | 1.2E-38 to 3.4E+38 | 6 decimal places |
long float |
8 bytes | 2.3E-308 to 1.7E+308 | 15 decimal places |
double |
8 bytes | 2.3E-308 to 1.7E+308 | 15 decimal places |
long double |
8 bytes | 2.3E-308 to 1.7E+308 | 15 decimal places |
Example 04
To find out the exact sizes of types on your system, you can use the function sizeof. Functions will be studied later, but for now, let us think of this function as a utility that helps us to find out the types’ sizes. Run the provided code on your system and compare the results with those I obtained on my system.
Types Compatibility
You need to pay extra attention when deciding what type to choose. For example, in the following line of code, some compilers will issue a syntax error or at least a warning:
int variable = 3.93;
The problem here is a data type mismatch by trying to save a double number 3.93 into an integer variable. However, other compilers allow such an assignment, but with the consequence that the fraction part will be lost. That is, the stored number in the variable will be 3, not 3.93. This is very tricky because the compiler might run your code without issuing any syntax error, you will still get the wrong results, leaving you wondering what happened with your code! The opposite might not be that serious, though.
double varialble = 3;
Here, the number will be converted from 3 to 3.0, which works without issues, however, the rule of thumb is, don’t mix types when working with variables!
Another example of type compatibility is int and char. char type is used to store characters; however, remember that all characters are actually encoded into numbers. That is, computers do not understand characters; they only understand numbers. That is, every character you can see on your keyboard is associated with a number. Figure 02 shows some of the characters encoding known as the ASCII encoding. As you can see from the table, every character has a code, including invisible characters like space, NULL, and many others. Therefore, the following code can run, although it is strongly unrecommended because this will make your code hard to read and confusing.
int variable = 'H';
char variable = 72;

Another example of type compatibility is int and bool. The type of bool accepts only two values, true or false. Those two values are encoded as 1 for true and 0 for false. Thus, the following lines of code are legal, though they should be avoided.
int variable = true;
bool variable = 0;
Exercise 05
Run the given code and find out what value is stored in each variable. Explain the results.
Example 05
Run the given code and check the correctness of the results.
We use the formula \[ \text{Fahrenheit (°F)} = (\text{Celsius (°C) × } \frac{9}{5}) + 32 \] to convert temperature degrees from Celsius to Fahrenheit.
While we expect the 25 °C to be converted to 77°F, we get the result of 57°F. The problem here is known as integer division, as explained in exercise 03. The easiest method to fix the problem is by writing either the denominator or the numerator (or both) as a double number. Another more formal method is using the casting syntax static_cast<the_desired_type>(variable)
as follows:
double fahrenheit = celsius * (static_cast<double>(9)/5) + 32.0;
Change the code and check the correctness of the results again. You have to pay attention when using casting. The following statement still produces the wrong result. Why?
double fahrenheit = celsius * (static_cast<double>(9/5)) + 32.0;
The reason is that we put the fraction 9/5 inside the parentheses, the integer division is then performed before the casting takes place. Thus, the result will already be calculated as an integer division, and casting will not make any difference by then!
Casting can be done on various types, such as casting int
to char
, bool
to int
and vice versa.
The string Type
<string>
library.Example 06
Run the provided code and comment on the outputs.
When initializing strings, you must surround the string between double-quotations, as in lines 6 and 7. Line 8 shows how to combine several strings together. This operation is called concatenating strings and is performed using the + operator. Compilers are smart enough to tell what needs to be done with this statement. If you are using the + operator between two numerical values, it will be understood that the required operation is to add the two numerical values and return their sum. However, if the + operator happens to be placed between two strings, it will be understood that the required operation is to concatenate the two strings into one string. If you try to place the + operator between a string and a numerical value, you will get an error, as this operator is not defined. Later in this book, you will learn how you can define your own operators. Additionally, line 8 shows that you can create strings without storing them in variables, ” ”. Here, all we want to do is add a space between the first and the last names. And of course, space is a string.
In line 9, we used one of the member functions of the string class. For now, all you need to know is that a string is a complex data type that includes many components (that is, member functions) inside it. To use those member functions, you need to call them by their names using the dot notation to specify which string you want a particular function to be called upon, for example, fullName.length(). In this statement, you are calling the member function length() specifically on the string variable fullName to find out how many characters are in this string.
Example 07
Run the provided code and explain the outputs.
To reverse a string, we can use the reversed function that uses two member functions of the string class, rbegin and rend. These two member functions are used to specify the beginning and the end of the string to be reversed. find is another useful function that finds the location of a substring in a larger string. In this example, the position is 15. Note here that in most cases in coding, counting usually starts from 0, not 1! The replace member function is used to replace part of a string with a substring. Again, pay attention to how numbers are chosen. The first number 7 denotes the position where the replacement should start, hence, counting starts at 0. The second number 11 denotes the number of characters that are to be replaced with the new string.
Exercise 06
Write a program to concatenate two strings without using the + operator. You need to do some research to find out how to use the string member function append.
Branching and Loops
if..else
discussed in this chapter. Later in Chapter 3, we will discuss another branching technique called switch
. There are several loops you are going to learn. In this chapter, we will cover for
loops, while
loops, and do..while
loops. Later, in chapter 5, another variation of the for
loop called the for-each loop will be discussed.Example 08
In boolean expressions, we can use these operators for any two variables a and b:
a > b |
greater than |
a >= b |
greater than or equals |
a < b |
less than |
a <= b |
less than or equals |
a != b |
is not equal |
a == b |
equals (Note: this operator is different from the assignment = operator.) |
.
if..else
Statementsif..else
statements is by discussing examples.Example 09
Run the provided code and explain the output.
The evaluation of the Boolean expression num >= 0
depends on the value of the variable num
. That is, if the expression evaluates to true, then the statement that comes after if
will be executed, skipping the else
part. However, if the expression is evaluated as false, then the else
part will be executed skipping the if
part.
To make the example more interactive, ask users to enter any number they wish, then the program will decide whether the entered number is positive or negative. You can do that by adding these statements above the if..else
statement:
Example 10
Run the provided code and explain the outputs.
In this code, the user is required to enter two numbers and then choose what operation they would like to operate on them, either addition or subtraction. If the user chooses +
then this character will be saved in the variable answer
and used in the boolean expression in the if
statement where the expression answer == '+'
will return true and execute the if
part skipping the else
part. Note here, we used the curly braces { }
to group more than one statement in both the if
and the else
parts. This is important; otherwise, only the first statement after if
will be executed, ignoring the rest statements, which of course will result in wrong outputs. Compare this case with example 09, where we did not use the { }
because we had only one statement and did not need the grouping curly braces.
In the previous example, you might have noticed that if you enter any character other than +
the else
part will be executed. That is ok with us as long as we meet the program requirements. In Chapter 3, you will learn about nested if..else
statements where you can specify more than just one condition.
Exercise 07
Write a program that asks users to enter two numbers. By using the if..else
statement, the program should determine which number is greater than the other and print it out to the console. Numbers entered should be either integers or decimals.
Exercise 08
Write a program that applies a 5% discount on items’ prices for members only using this formula \[discountedPrice = itemPrice – (0.05\text{ × }itemPrice)\]The program should ask the user to enter the item price and then ask if the user is a member or not. If the user answers y for yes, then a new discounted price should be printed out to the console; otherwise, a message saying no discount is applied should be printed instead.
for
Loops
for(initialization ; boolean expression ; update){
loop body
}
initialization
is the operation where we give the loop control variable an initial value. This control variable can be either declared in the loop header or somewhere else before the loop. This difference can have a significant consequence. In many compilers, including Visual Studio, if the control variable is declared inside thefor
loop header, it will be considered as a local variable. This means it can be visible only inside the loop body and cannot be accessed outside it. You are strongly recommended to test the compiler that you are using, whether this fact holds or not.boolean expression
is any expression that results in either true or false values.update
is any operation that results in updating the loop control variable value.
Example 11
Run the given code and explain the results.
The statement int i = 1
declares and initializes the loop control variable i
. The loop continues as long as the expression i <= num
evaluates to true. When this expression evaluates to false, the loop terminates. The statement i++
increments i
value by one after each iteration (conversely, the --
operator decrements any variable value by one). At the start of the loop, i
equals 1. If the user enters 5, then num
equals 5, and the condition 1 <= 5
is true. After the first iteration, i
is incremented to 2, and the condition 2 <= 5
is still true. This pattern continues until i
equals 6, at which 6 <= 5
is false, and the loop terminates. During each iteration, the value i
is printed to the console, followed by a colon and the welcome message. Run the code with different user inputs to observe the pattern of loop iterations.
Note in example 11, we did not use { }
to surround the for
loop body because the loop body has only one statement. However, whenever you need to add more than one statement inside the loop body, you must use the { }
same approach as in example 12.
Example 12
Run the given code and explain the results.
The loop control variable counter
declared before the loop header. This is important because this variable is used to calculate the average after the loop is terminated in line 12. As an exercise, delete line 5 and declare the counter
variable inside the loop header. When you do so, you will get an error because the scope of the counter
variable becomes local to the loop body, thus, you cannot access its value. Another thing to note here is that the total
variable is initialized in line 4. Again, if you do not do that, you will get an error generated by executing line 10. In line 10, we read the contents of the variable total
and it to grade
. And then save the new value back in the
total
variable. At the first iteration, assuming you did not initialize the total
variable, the code in line 10 will try to read the uninitialized variable value, which causes the error. The last detail to pay attention to is that on line 12, we divided the total
over (counter - 1)
. This is because the loop condition counter <= 5
evaluates true
until the counter
value becomes 6, causing the loop to terminate. This, of course, will cause a logical error because the user entered only 5 grades, not 6. Therefore, we must subtract 1 from this variable to bring it back to the correct value of the number of entered quizzes’ grades, which is 5.
Exercise 09
Write a program that asks the user to enter an integer number, then the program should print out all even numbers starting from 2 up to the number entered by the user. The program must use the for
loop.
Exercise 10
Write a program that calculates the factorial of a non-negative integer number using this formula, \[ \text{n! = n × (n-1) × (n-2) × … × 3 × 2 × 1} \] That is, if n = 5, then \[\text{5! = 5 × 4 × 3 × 2 × 1 = 120}\] In math, the exclamation mark !
is used to denote the factorial function. The program must use for
loop. Test your code for several numbers to find out the largest number that your system can calculate its factorial. On my system, using long long int
data type n
turns out to equal 20
. You will get negative results, denoting an overflow occurred in your system, which means the calculations have exceeded your system’s capabilities!
while
Loopsfor
loops are generally easier to use whenever you know beforehand how many iterations you would need. However, in some cases, we do not know this information. In example 11, we asked the user to choose how many times they wanted to print out the welcome message to the console. Suppose now we want the user to be able to print as many as they want until to say stop without specifying the number of iterations. This can be achieved using a while
loop.Example 13
Run the given code and explain the results.
A while
loop operates by evaluating an expression, similar to for
loops. The loop continues to run as long as this condition evaluates to true
. Once the condition evaluates to false
, the loop terminates. It’s crucial to ensure that the loop condition will eventually evaluate to false
; otherwise, the loop will run indefinitely, resulting in an infinite loop. After the welcome message is printed for the first time, we ask the user if they want to print the message again. The user’s response is checked in the while
loop condition answer == 'y'
. As long as this condition returns true
, the loop will continue to repeat. When the user enters ‘n
’ (or any other character), the condition evaluates to false
, and the loop terminates.
Example 14
Run the given code and explain the results.
This is a simple guessing game where the user keeps guessing a number until they guess it correctly. The loop condition compares the userGuess
value to the preselected secretNumber
value. While this condition evaluates true
, the loop will keep running until the user guesses the correct number, causing the condition to evaluate false
. The code can be modified to let users guess characters or strings like places’ names or people’s names to make the game more fun.
Exercise 11
Modify the code in example 14 to guess words instead of numbers. Be creative with what can be guessed. At the end of this chapter, a sample solution is provided.
Exercise 12
Redo exercise 10 using while
loops.
do..while
Loops
false
at the very beginning of the loop? Naturally, this will terminate the loop immediately without any iterations. Generally, this can be acceptable and raises no issues, however, in the case that we want to guarantee that at least the loop will iterate once, then we must use the do..while
loop. In this loop, the body of the do
block will execute without any condition checking. The loop condition check comes after the do
body. The following examples explain this special case loop.Example 15
In example 13, I hope you noticed the annoying duplication of printing the welcome message, followed by reading users’ input. Here, we can take advantage of do..while
to improve our code readability and efficiency.
The code starts with a do
block, which runs without checking any condition. In this example, that’s exactly what we want. Right after the end of the do
block, the while
header appears, checking the loop condition. As usual, the loop will continue as long as the condition evaluates to true
, and terminates when the condition evaluates to false
. Note that we must add a semicolon ;
at the end of the while
header. However, we do not add a semicolon in the ordinary while
loop. If you do, it will separate the while
loop header from its body, resulting in an infinite loop!
Example16
do..while
loop is a popular choice when you design a menu of choices that users need to choose from. Run the provided code and notice that the code is incomplete. In order to respond to the user’s choice, we usually use multiple if .. else
statements or switch
statements that you will learn about in Chapter 3. For now, it is ok to just notice how this loop can be used in the future whenever the problem that you are solving includes a menu of options. In this example, we implemented user choice as int numbers, however, technically, you can use anything else like, characters or even words.
Formatting Outputs
At this point, you might have gotten a brief picture of how complex the code can be, and hence the output as well. Therefore, it’s important as a programmer to start thinking about formatting the code and the output. This is not solely for beautifying how they look, but to make reading and understanding the code and the output a lot easier. The benefits of this way of thinking will become evident as you progress through this book.
In the next section, you will learn about the best practices for writing clear and easy-to-read code. In this section, you will learn how to write clear and easy-to-read outputs.
Example 17
Run the given code and pay attention to the outputs. The first group of output lines are called “Messy Outputs”. As the name suggests, their format is messy and hard to read and understand. However, in the second group of output lines, the same information is printed out in a formatted way. While the information is exactly the same, the way it’s formatted makes it easier to read and understand. In this code, we used a predefined function setw, which stands for “set the width”. This function is sometimes called a manipulator because it manipulates the output cout stream. left and right manipulators can be used with setw to align outputs. setw takes one int argument and creates a table column with the specified number of characters as the column width. You must include the <iomanip>
library to be able to use the setw function. Try to experiment with the values used to get a better sense of how to use this formatting function.
Example 18
You can be as creative as you want to present the outputs in the best way you are able to. Modify the previous example code to add boundaries to the table created. Note here to avoid writing long lines of code, some IDEs provide an option to break a single line of code into several lines to enhance readability. For example, line 10 is broken into two lines. Therefore, you either enter it as one long line on your IDE or configure your IDE to allow automatically breaking long lines. The curved arrow that appears at the end of the line is just a reminder that this line of code continues to the next line. Similarly, lines 12 and 13 are broken into two lines.
NOTE: If you are using Visual Studio IDE, you can configure it to automatically break long lines by following these steps:
- Open Visual Studio.
- From the Tools menu, select Options.
- In the search bar, type “word wrap”.
- Click the checkbox next to the ‘Word Wrap’ option.
Exercise 13
Write a program that produces this output:
In addition to formatting texts, we often need to format numbers as they would become very messy.
Example 19
Run the provided code and notice the new manipulators used. In this example, we have used setprecision manipulator to choose how many decimal digits we desire. The fixed manipulator is necessary to manipulate the cout output stream to always print out numbers with decimal places. That is to avoid printing numbers in sceintific notation like 1.234e5, 9.998745e-13, and so on, where the letter e
stands for the exponent.
Exercise 14
Write a program that produces this output:
Best Practices for Writing Code
In chapter one, we mentioned some general rules to create variable names. For the importance of this topic, we re-emphasize these rules here. Until now, variable names have been created arbitrarily. Technically, you can name your variables in any way you prefer; however, you must follow the following rules:
- Names must always be one word. No spaces are allowed.
- You cannot use a keyword as a variable name, like int, double, cout, and so on.
- You cannot use any special characters in the name except the underscore.
- Names must not start with numbers. The first character must always be either a letter or an underscore, followed by any combination of letters and numbers.
- C++ is a case-sensitive language, meaning all of these names are considered different and unique names: myVariable, MyVariable, myvariable, … and so on.
- Create meaningful names that can tell their purpose, like sum, average, grossTotal, FtoC, or CtoF for converted degrees from Fahrenheit to Celsius and vice versa. Always think creatively and consistently.
As you have seen so far, some variable names can consist of multiple words, like grandTotal or discountedPrice. As using spaces is not allowed in naming, you can make names easier to read by either capitalizing each word or using underscores. The choice will be totally up to your preference.
Exercise 15
Determine which of the following names are correct following the common names writing rules and which are not. If a name is not correct, explain the reason why.
- int
- My Variable
- totalScore
- 123abc
- studentName
- numberOfItems
- my-variable
- isReady
- maxValue
- @username
Writing Styles
While compilers won’t complain if you write your entire code in a single line, doing so can make it challenging for developers to read and debug. Therefore, adopting a professional coding style is essential. It serves not only as a formatting and beautification requirement but also as a means to ensure code clarity and ease of understanding, especially when multiple developers collaborate on the same project.
While there is no widespread consensus on which coding style to follow, the golden rule remains: keep your code clean and tidy. Fortunately, Integrated Development Environments (IDEs) offer significant assistance in achieving this goal. If you’re using any of the widely available IDEs (some of which are free, like Visual Studio), they can greatly simplify your development process.
Example 01 explained that in real-life scenarios, comments can serve a very important role, which is communication between developers, especially in large projects. For this reason, to write useful and efficient comments, you can follow one of the many available comment structures.
Example 20
When writing code, it’s essential to include certain details at the top of every program. These practices not only enhance readability but also provide valuable context for anyone who reads your code. Consider adopting these habits from now on, and feel free to customize the content to suit your specific needs:
- Program Description: Start with a brief description of what the program does. This helps readers quickly understand its purpose.
- Author Information: Include your name or the name of the author(s) responsible for the code. It’s a professional courtesy and allows others to reach out if they have questions.
- Date Created/Modified: Specify when the program was initially written and any subsequent modification dates. This timestamp helps track changes and ensures that everyone is working with the most up-to-date version.
- Version Number: If applicable, indicate the version of the program. This is especially useful for software that undergoes frequent updates.
- Dependencies and Requirements: List any external libraries, modules, or tools required to run the program successfully. Be specific about versions if necessary.
- Usage Instructions: Provide clear instructions on how to use the program. Include command-line arguments, input formats, and expected output.
- License Information: State the license under which the code is released. Common licenses include MIT, GPL, and Apache. Choose one that aligns with your intentions for sharing the code.
- Acknowledgments: If you’ve borrowed ideas, algorithms, or code snippets from other sources, acknowledge them. It’s good practice and shows respect for the work of others.
Example 21
In this example, we are using the preconditions and postconditions comments that usually appear at the beginning of every function. In chapters 04 and 05, you will start writing your own functions, and you will need to write meaningful comments following this common style. Preconditions are used to explain clearly what should be true before calling a function. In code snippet 1, the function calculateRectangleArea
expects to receive two double
arguments. The precondition is explicitly saying that those two arguments must not be negative, as the results would be unreasonable. This comment is very helpful in informing whoever wants to use this function how to use it correctly. Similarly, the postcondition says what the function will return at the end of its execution. In this case, the function will return the calculated area as a double
value. Again, if someone wants to use this function to calculate the area and save the returned value into some variable, they need to be sure that the variable has the correct type to save the returned value. In this case, the returned value will be double
and hence the variable used to save this value must be double
, otherwise, either an error or unexpected results will occur. Read the remaining code snippets to understand their importance in clarifying how each function must be called and used.
Exercise 16
Write the preconditions and postconditions for the following functions:
double squareRoot(double x)
bool isValidEmail(string email)
double calculateCircleArea(double radius)
Answers Key




myInt2 = 0
myInt3 = 72 //the ASCII value of H is 72
myInt4 = 5 //the fraction part is lost!
myBool = 0 //false value is encoded as 0
myBool2 = 1; //any non-zero number is represented as true, true value is encoded as 1
myChar = H; //H is represented by ASCII value 72
myDouble = 5;









- (not correct) int (uses a reserved keyword)
- (not correct) My Variable (contains spaces)
- (correct) totalScore
- (not correct) 123abc (starts with a digit)
- (correct) studentName
- (correct) numberOfItems
- (not correct) my-variable (contains a hyphen)
- (correct) isReady
- (correct) maxValue
- (not correct) @username (contains special characters)
- Precondition: The input
x
must be non-negative.
Postcondition: The function returns the square root ofx
. - Precondition: The input
email
is a non-empty string.
Postcondition: The function returnstrue
if the email address is valid (following common email format rules), otherwisefalse
. - Precondition: The input
radius
is non-negative.
Postcondition: The function returns the area of a circle with the given radius.
End of Chapter Exercises
int variableName = 0;
A) Variable declaration
B) Variable initialization
C) Variable declaration and initialization
D) Syntax error!
b) Every statement in C++ must end with a semicolon.
c) The cout stream is used to read user input.
d) The cin stream works with the extraction operator >>.
e) When variable names appear in a cout line of code, the variable name itself will print out to the console.
f) The return 0; statement in the main function signifies that the program has encountered an error.
a
and b
, initializes them with values 5 and 10, respectively, and then swaps their values. The program should print the values of the variables before and after the swap.A) I love programming C++!
B) C++ I love programming!
C) I love C++ramming!
D) Syntax error
b) The + operator can be used to concatenate two strings in C++
c) The length() function is used to print a string backward
- Declares a string variable str.
- Initializes str variable to the value “I just started learning C++.”.
- Use the member function replace() to replace the word C++ with Java. Both sentences, before and after the replacement, should be printed out to the console.
- Use the append() function to add “It is so much fun!” to the same variable and print out the new sentence.
- Use the find() function to find the position of the word it in the new sentence. The position value should be printed to the console.

A) Hello World!
B) Hi World!
C) World!
D) Hello, Hi World!
23) True or False:
if
-statement, we must use an else
-statement with it as well.if
-statement must always be a boolean.24) True or False:
for
loop is used when the number of iterations is known beforehand.do-while
loop checks the condition before executing the loop body.do-while
loop is guaranteed to execute its body at least once.25) What will be the output of the following C++ code?
int i = 0;
while (i < 5) {
cout << i << " ";
i++;
}
26) What will be the output of the following code?
int i = 0;
do {
cout << i << " ";
i++;
} while (i < 5);
27) Write a program that prints the numbers from 1 to 10 using a for
loop.
28) Write a program that calculates the factorial of a number using a while
loop.
29) Write a program that prints the numbers from 10 to 1 in reverse order using a for
loop.
30) Write a program that calculates the sum of the numbers from 1 to 100 using a for
loop.
int add(int a, int b)
double divide(double a, double b)
bool isPrime(int n)
void swap(int a, int b)
32) Explain how to use setprecision, setw, and fixed manipulators. Provide brief examples.
Projects
Project 01: Grocery Store Billing System
Write a program that simulates a grocery store billing system. The program should prompt the user to enter the quantities of three types of fruits: apples, bananas, and oranges. Then, it should calculate the total cost of the items purchased based on their quantities and prices. Additionally, if the total cost exceeds $10, a 10% discount should be applied. Finally, the program should display the total cost to the user, with or without the discount applied.
Your program should do the following:
- Prompt the user to enter the number of apples, bananas, and oranges.
- Calculate the total cost of items purchased using the following prices declared as constants:
- Apples: $1.00 each
- Bananas: $0.50 each
- Oranges: $1.50 each
- Display the total cost of items to the user.
- If the total cost exceeds $10, apply a 10% discount and display the new total cost.
- Ask the user if they wish to repeat the calculations using the
do..while
loop. - Write appropriate comments to explain the code where necessary.
- Test your program with various input values to ensure its correctness and reliability.
Project 02: Weekly Budget Planner
Create a program for managing weekly expenses using the Weekly Budget Planner. The program should allow users to add expenses for food, transportation, and entertainment categories. Additionally, users should be able to print the budget to see the total expenses for each category and the grand total.
Your program should do the following:
- Display a menu with these options:
- Add food expenses
- Add transportation expenses
- Add entertainment expenses
- Print budget
- Prompt the user to enter their choice (1, 2, 3, or 4) for the category they want to add expenses to.
- Depending on the user’s choice, prompt them to enter the value for the corresponding category’s expenses.
- Repeat steps 2 and 3 until the user chooses to print the budget by entering ‘4’.
- After the user chooses to print the budget, display the total expenses for each category and the grand total.
- Thank the user for using the Weekly Budget Planner.
- Write appropriate comments to explain the code where necessary.
- Test your program with various input values to ensure its correctness and reliability.
Ensure that your program follows these specifications:
- Use appropriate variable names and data types to store expenses and user inputs.
- Utilize a
do..while
loop to repeatedly prompt the user for input until they choose to print the budget. - Provide clear instructions and prompts to guide the user through the program.
Project 03: Prime Number Checker
- Prompt the user to input an integer.
- Process the input and determine whether it is a prime number.
- Display the result to the user.
- Write appropriate comments to explain the code where necessary.
- Test your program with various input values to ensure its correctness and reliability.
- A prime number is a number greater than 1 that has no positive divisors other than 1 and itself.
- Consider how you can optimize the program to reduce the number of checks needed to determine if a number is prime.
- Think about how you can handle different types of inputs and potential errors.