Elementary Programming

Improve this page on Github


2.1 Introduction and Objectives

You are about to begin an exciting journey of programming. At the outset, it is helpful to start with some basic concepts and fundamentals of programming. We will learn about simple inputs/outputs, identifiers, variables, and related expressions in this chapter. These are crucial tools that will help the information be circulated through the user and the code. Additionally, We will learn:

  • How to get the information from the user
  • How to save that information
  • How to do some calculation using that information and;
  • How to let the user know about the result of the calculation

2.2 Writing a Simple Program

Writing a program involves designing a strategy for solving a problem and then using programming language to implement that strategy. 1

Let us begin with a simple C++ program that display a message on the screen.

#include <iostream>

using namespace std;

int main() 
{
  cout << "Hello World!" << endl;
  return 0;
}
2.2.1 Algorithm

Fist step on programming is to design an algorithm to solve the problem by listing the actions that must be taken, and the order of their execution. In this case, there are 4 steps:

  1. Prompt user by a printed message to enter a number.

  2. Declare a variable in order to store the number that user will enter.

  3. Get the user’s number.

  4. Print out a nicely formatted message that shows the number which user gave us.

2.2.2 Main Functions

The execution of all C++ programs begins and end with the main function.

We will learn more about functions on Chapter 6 (Functions)

int main()
{
    // Your program starts from here!
}

Regardless of where the function is located. The open brace ({) indicates the beginning of main’s function definition, and the closing brace (}) indicates its end.

To learn more about main function, check this out.

2.2.3 What Is iostream?

To perform standard input and output operations, such as writing the output to the screen, we need to include a section of standard C++ code, known as header iostream.

The syntax is as follows:

#include <iostream>

Lines beginning with a hash sign (#) are directive read and interpreted by what is known as the preprocessor. They are special lines interpreted before the compilation of the program itself begins. The following shows the usage of #.

#include <iostream>
2.2.4 Display the Message!

Sometimes, like when we want to tell the user to enter a number or display the result of a process or calculation, we need to display the messages on the screen.


In C++, we use the syntax below to print them out:

std::cout << "Please enter a number: ";

This line(statement) contains some parts as follows:

  • std::cout
    Identifies the standard character output device (usually, this is the computer screen).
  • <<
    The insertion operator, which indicates what as follows, is inserted into std::cout.
  • "Please enter a number: "
    The sentence we want to display on the screen.
  • ;
    This character marks the end of the statement, just as the period ends a sentence.

    All C++ statements must end with a semicolon character (;).

    One of the most common syntax errors in C++ is forgetting to end a statement with a semicolon.

#include <iostream>

int main()
{
    std::cout << "Please enter a number: ";
}
2.2.5 Standard Library of C++

In the C++ programming language, the C++ Standard Library is a collection of classes and functions, which are written in the core language and part of the C++ ISO Standard itself. 2

If you have seen C++ code before, you might have seen cout being used without std::. Both, cout and std::cout, invoke the same function: One uses its unqualified name (cout), while another one qualifies it directly within the namespace std (std::cout).

cout is part of the standard library of C++, and all the elements in the standard C++ library are declared within what is called a namespace; in this case it is the namespace std.

In order to refer to the elements in the std namespace a program shall either qualify each and every use of elements of the library (as we have done by prefixing cout with std::), or introduce visibility of its components.

The most typical way to introduce visibility of these components is by means of using declarations:

using namespace std;

The above declaration allows all elements in the std namespace to be accessed in an unqualified manner (without the std:: prefix).

See namespace Through an Example
Imagine you and a group of others are talking about the university of Regina. In this group, if you mention s specific place like Data Science Lab, everyone knows that you mean the Data Science Lab of the University of Regina.
On the other hand, if your topic is not the University of Regina and you mention *Data Science Lab*, avoid mentioning the place which this lab is located in, the others cannot understand what place are you talking about.
This is what exactly happens here.

Our code should look like:

#include <iostream>

using namespace std;

int main()
{
    cout << "Please enter a number: ";
}

Add the line using namespace std; and remove std:: from the beginning of the cout.

2.2.6 What Is the Variables? How We Can Store a Value in a Variable?

Sometimes we need to store a value and use it in our calculation, etc. In this case, you want to get a number from a user. You need to store it in the computer memory, so we can use it during the program (Display on the screen).

To store a value in the computer memory, we can use variables. Each variable needs a Identifier (name), and a Data Type.

For example:

int number;
  • Here number is the Identifier (name) of this variable. In the rest of the program we can use it by call its name.

  • In C++ programs, you need to tell computer what type of value you want to store in this specific variable. We will go through the Data Types in this chapter, but for know keep it in your mind that int is a data type to store numbers!

Prompt the user to enter a number, we need to declare a variable, So we can store the number which entered by the user to the variable.

#include <iostream>

using namespace std;

int main()
{
    cout << "Please enter a number: ";
    int number;
}
2.2.7 Get the Entered Number of the User and Store It in Variable

In order to get the value from the user through the console, we use the statement below:

std::cin >> number;

As we talked about the standard library of C++, as long as you are using the std namespace, you are able to remove the std::. It can be:

cin >> number;
  • number is the name of the variable (Identifier) that we want to store the value in. it.

By getting the number from the user our code leads to:

#include <iostream>

using namespace std;

int main()
{
    cout << "Please enter a number: ";
    int number;
    cin >> number;
}
2.2.8 Get the Entered Number of the User and Store It in Variable

It is the time to display the user’s number on the screen.

#include <iostream>

using namespace std;

int main()
{
    cout << "Please enter a number: ";
    int number;
    cin >> number;
    cout << "You entered: " << number << endl;
}
  • As you can see, we are able to print several variables and sentences in one line, by put << between them.

  • The std::endl or endl is a function, that insert a new-line character. Whenever we want to go to the next line, we can use it.

    To learn more about the endl click here.

2.2.9 How Does a Computer Know a Program Has Been Finished Successfully?

When a program begins running, the system calls the function main, which marks the entry point of the program.

The main function is both entry point and exit point of a program. when a program ends, it will return a number. The number returning by the main function has a meaning for the operating system (OS). Mostly, OS, monitor the code, and when the program ends by returning 0, it can be understood that the program is run successfully.

It’s not particularly use in C++ programs.

C++ program return 0 by default when the program is run successfully, and -1 or whatever when an error occurs during the runtime.

So, it is highly recommended using return 0; at the end of your program.

See the code after adding the return 0;:

#include <iostream>

using namespace std;

int main()
{
    cout << "Please enter a number: ";
    int number;
    cin >> number;
    cout << "You entered: " << number << endl;
    return 0;
}
2.2.10 Comments in C++ Programs

Sometimes we need to put a comment (note) in the code. For Instance, imagine that you have a complex part in your program that people usually can’t understand it. To ease it for others to understand the code, even for your future, put a comment there and explain what you did there.

For example, if we add some comments and explain our algorithm completely, our code looks like:

#include <iostream>

using namespace std;

int main()
{
    // Prompt user to enter a number
    cout << "Please enter a number: ";

    // Declare an integer variable named `number`
    int number;
    
    cin >> number;  // Get `number` from the user

    // Display nicely formatted number in console
    cout << "You entered: " << number << endl;

    /*
        return 0 as exit success; 
        means program finished successfully
    */
    return 0;
}
  • By convention, every C++ program is better to have this kind of comment block at the program.

    It does not mean that it is better to put comment for everything!

    There are some suggestion regarding the comments. If you are interested click here.
    These are some suggestion about the comment from the book named Clean Code by Robert C. Martin

    1. Always try to explain yourself in code.
    2. Don't be redundant.
    3. Don't add obvious noise.
    4. Don't use closing brace comments.
    5. Don't comment out code. Just remove.
    6. Use as explanation of intent.
    7. Use as clarification of code.
    8. Use as warning of consequences.

    These rules are usually using in the large scale companies.
    You can find more rules of Clean Code here.


  • Comment on just one line, or part of a line, begins with //.

  • Usually, a comment that carries over several lines begins with /* and ends with */. Everything between these special characters are commented.

Single or multi-line comments?

It is up to you which you want to use. Normally, we use // for short comments, and /* */ for longer.

Try It Yourself:


NOTE:

Built-in header files, in the program, are enclosed inside the < and > marks, and created header files in "" quotation marks.

  • int main() { } is the executable part of our program. The function name is main, and it returns an integer type value which its function, as indicated by the empty parentheses, has no parameters.

  • The parentheses () mark the beginning and end of a group (scope) of C++ statements. In this case, they enclose our main function.

  • int number; sets number as a variable of input type integer.

  • cout is the command to print out text or data on the screen. Anything enclosed in quotation marks (string) is printed.

  • cin - command receives data from the user.

  • The <iostream> file exists in every C++ program, and it is the file which allows us to use cout and cin.

  • The second cout line prints out "You entered: [number]". So, if I entered 5, the output would be: You entered: 5

  • This kind of way to get data into the program is called a user interactive input, and it makes the program interactive.

  • endl is a manipulator to indicate the end of the line. It tells the cursor to stop printing on the current line, and begin on the next line.

  • return 0; - is there, since the return value in our main program was designated as an integer. It prevents the compiler from reporting a syntax error. 0 also means the program has been finished successfully.

  • // end of the program - a single line comment.

2.3 Reading Input from the Keyboard

Reading input from the keyboard promotes the interaction between the user and the program. In other words, it helps the program to gain the necessary information by enabling it to accept input from the user.

Imagine writing a program to calculate the area of a rectangle with a length of x and a width of y. The very first step to calculate this area is to get the length and the width from the input.

Working knowledge of C++ Basic I/O is an important first stage in learning C++. Here is the table of C++ basic Input/Output (I/O) symbols we saw in the preceding program:

Symbol Name Description
cout A special variable Used along with the insertion operator << to write out the values of variables and expressions to the standard output device such as a screen.
<< Insertion operator Takes two operands. Its left-hand operand is a stream expression, and its right-hand operand is an expression that could be as simple as a literal string. It can be used several times in a single output statement.
cin A special variable Used along with the extraction operator >> to input values from the standard input device, such as a keyboard, to a variable.
>> Extraction operator Takes two operands. Its left-hand operand is a stream expression. Its right-hand operand is a variable into which we store the input data. It can be used several times in a single input statement.
Note:

That cin (pronounced see-in) stands for console input, and cout (pronounced see-out) stands for console output.

For instance, getting x (length) and y (width) from input, we could say:

cin >> x;
cin >> y;

Also, we could get x and y in one line:

cin >> x >> y;

2.4 Identifiers

In a program, identifiers are the names given to elements such as variables and functions. There are two main parts in a C++ program:

  • Instructions to the C++ preprocessor and compiler.

  • Instructions that describe the processing to be done.

We must have a way of naming things preceding the instruction description to tell the compiler about them and describe what we want to do with them. We call things (data types, data objects, and actions) by giving them an identifier.

Identifiers Naming Rules

  • An identifier is made up of letters, numbers, and underscore ( _ ).

  • An identifier must start with a letter or an underscore; it cannot start with a digit.

  • An identifier should not be a reserved word.

  • An identifier can be of any length, however, your C++ compiler may impose restriction.

For instance, length and _width1 are legal identifiers, while 1length and width-4 are not legal.

NOTE:

Reserved words are certain words which have predefined meanings within the C++ language.

int, namespace, using, include, cin, cout, and, return, etc. are reserved words, for example. You cannot use them as your user defined identifier such as variable names

Check out here for more reserved words in C++

NOTE:

C++ is case sensitive. It means length, Length, and LEngTh are all different.

camelCase:

Camel Case is the practice of writing phrases without spaces or punctuation, indicating the separation of words with a single capitalized letter, and the first word starting with either case. It is often used as a naming convention in which the first letter of each word is uppercase except for the first word. The rest of the letters are lower case.

For example, payRate, camelCase, and numberOfYears are camelCase.

camelCase

CamelCase Is Named After the "Hump" of Its Protruding Capital Letter, Similar to the Hump ommon Camels.

There are also other ways to write phrases such as PascalCase, snake_case, kebab-case.

Find out more here.

2.5 Variables

Variables are represented as memory locations that have a type, such as an integer or character, and consequently, a size, which is inherited from their type. Since variables are types, they have a set of operations that can be used to change or manipulate them.

Each variable in your program must be declared and initialized. There are two ways in which it can be done:

  • 1. Declare the Variables First

      char letter;
      int x;
      long student_id;
      float payRate;
      double pi;
      bool valid;
    

    Then initialize them as a separate statement, later in the program.

      letter = 'A';
      x = 7;
      student_id = 200201202;
      payRate = 12.85;
      pi = 3.1415926536;
      valid = true;
    
  • 2. Initialize the Variables While They Are Being Declared, in One Statement, Simultaneously.

      char letter = 'A';
      int x = 7;
      long student_id = 200201202;
      double pi = 3.1415926536;
      float payRate = 12.85;
      bool valid = true;
    

    A variable can be used only after its value is set.

2.6 Assignment Statements and Assignment Expressions

An assignment are used to designate a value for a variable, and it can also be used as an expression in C++. When we declare a variable, we can assign a value to it by using an assignment statement. At the outset, You need to know the definition of an arithmetic expression and the precedence of the operators.1

Arithmetic Expressions are defined as Variables and constants of integral and floating-point types can be combined into expressions using arithmetic operators.3

2.7 Named Constants

The initialized variable can be declared as a constant by adding the type qualifier const before the definition.4

The general format for a const declaration is shown as below:

const type variableName = [any value you like]

Inside a program, you will see constants written like this:

const float payRate = 12.85;
const double pi = 3.1415926536;
const char dollarSign = '$';
const string markdown = "MarkdownV2";

2.8 Numeric Data Types and Operations

A data type is a set of values and a set of operations on these values In the preceding program, we used the data type int, an identifier for the integer data type.

We used data type int in four ways in the preceding program. int precedes main, the name of the main function in the program to indicate that the function returns the value of type int. In the end, an int, literal (zero) is returned as the result of the main function main. Also, in the middle of the program, a variable number is declared to have the data type int. In addition, an integer number was read from the keyboard and stored in the storage of variable number.

The following are some fundamental/simple data types:

Integral Types

short int long char
unsigned short unsigned int unsigned long unsigned char

Floating Types

float double long double

The Arithmetic Operators

Operator Description
+ Unary plus needs one operand.
- Unary minus needs one operand.
+ Addition needs two operands.
- Subtraction needs two operands.
\ Multiplication needs two operands.
/ Division needs two operands.
Floating point operands &rightarrow; floating point result
Integer operands &rightarrow; integer quotient
Mixed operands &rightarrow; floating point result
% Modulus
Remainder from integer division
Operands must be integral
++ Increment by one
Can be prefix or postfix
As postfix has highest precedence
-- Decrement by one
Can be prefix or postfix
As postfix has highest precedence

2.9 Evaluating Expressions and Operator Precedence

The precedence rules of arithmetic apply to arithmetic expressions in a program. That is, the order of execution of an expression that contains more than one operation is determined by these rules of arithmetic. These rules state that parentheses have the highest precedence, multiplication, division, and modulus have the next highest precedence, and addition and subtraction have the lowest. Besides,the Postfix increment and decrement operators have the highest precedence over any of the arithmetic operators.

Look at the following example, and decide what is written by each of the output statements.

The program demonstrates the precedence of the operators.

#include <iostream>

using namespace std;

int main()
{
    cout << 4 + 3 * 5 << endl;
    cout << (4 + 3) * 5 << endl;
    cout << 4 * 5 % 3 + 2 << endl;
    cout << (4 * (5 % 3) + 2) << endl;
    return 0;
}
Output:
19
35
4
10
Try It Yourself:


Precedence Operator Description Associativity
1 :: Scope resolution Left-to-right
2 a++, a-- Suffix/postfix increment and decrement  
3 ++a, --a Prefix increment and decrement Right-to-left
  +a, -a Unary plus and minus  
  *a Indirection (dereference)  
  &a Address-of  
4 .*, ->* Pointer-to-member Left-to-right
5 a*b, a/b, a%b Multiplication, division, and remainder  
6 a+b, a-b Addition and subtraction  
7 <<, >> Bitwise left shift and right shift  
8 <=> Three-way comparison operator (since C++20)  
9 <, <= For relational operators < and ≤ respectively  
  >, >= For relational operators > and ≥ respectively  
10 ==, != For relational operators = and ≠ respectively  
11 & Bitwise AND  
12 ^ Bitwise XOR (exclusive or)  
13 \ Bitwise OR (inclusive or)  
14 && Logical AND  
15 ^ Logical OR  
16 a?b:c Ternary conditional Right-to-left
  = Direct assignment (provided by default for C++ classes)  
  +=, -= Compound assignment by sum and difference  
  *=, /=, %= Compound assignment by product, quotient, and remainder  
17 , Comma Left-to-right

2.10 Augmented Assignment Operators

Assignment operators is the name given to certain assignment operators in certain programming languages (especially those derived from C). It modifies the value of the object. (Wikipedia)

Operator name Syntax Overloadable
simple assignment a = b Yes
addition assignment a += b Yes
subtraction assignment a -= b Yes
multiplication assignment a *= b Yes
division assignment a /= b Yes
modulo assignment a %= b Yes
bitwise AND assignment a &= b Yes
bitwise OR assignment a \= b Yes
bitwise XOR assignment a ^= b Yes
bitwise left shift assignment a <<= b Yes
bitwise right shift assignment a >>= b Yes

Examples are Inside class definition and Outside class definition, respectively.

Explanation

copy assignment operator replaces the contents of the object a with a copy of the contents of b (b is not modified). For class types, this is a special member function, described in copy assignment operator.

move assignment operator replaces the contents of the object a with the contents of b, avoiding copying if possible (b may be modified). For class types, this is a special member function, described in move assignment operator. (since C++11)

For non-class types, copy and move assignment are indistinguishable and are referred to as direct assignment.

compound assignment operators replace the contents of the object a with the result of a binary operation between the previous value of a and the value of b.

2.11 Increment and Decrement Operators

Increment/decrement operators increment or decrement the value of the object.

Operator name Syntax Overloadable
pre-increment ++a Yes
pre-decrement --a Yes
post-increment a++ Yes
post-decrement a-- Yes

Explanation

Pre-increment and pre-decrement operators increase or decrease the value of the object and returns a reference to the result.

Post-increment and post-decrement creates a copy of the object, increments or decrements the value of the object and returns the copy from before the increment or decrement.

Built-in Prefix Operators

The prefix/suffix increment and decrement expressions have the form:

  • ++expr: prefix increment (pre-increment)

  • expr++: suffix increment (post-increment)

  • --expr: prefix decrement (pre-decrement)

  • expr--: suffix decrement (post-decrement)

The operand expr of a built-in prefix increment or decrement operator must be a modifiable (non-const) value of non-boolean (since C++17) arithmetic type or pointer to completely-defined object type.

For non-boolean operands, the expression ++x and x++ are exactly equivalent to x += 1 or x = x+1, and the expression --x and x-- are exactly equivalent to x -= 1 or x = x-1, that is, the prefix increment or decrement is a value expression that identifies the modified operand.

What is the difference between ++x and x++ in C++?

++x means first increase the value of x by 1 and then use it. whereas x++ means first use the value of x and then increment it’s value by 1.

both printf statements are separate not one after other.

All arithmetic conversion rules and pointer arithmetic rules defined for arithmetic operators apply and determine the implicit conversion (if any) applied to the operand as well as the return type of the expression.

#include <iostream>

using namespace std;

int main()
{
    int n1 = 1;
    int n2 = ++n1;
    int n3 = ++ ++n1;
    int n4 = n1++;
    // int n5 = n1++ ++; // error
    // int n6 = n1 + ++n1; // undefined behavior
    cout << "n1 = " << n1 << '\n' << "n2 = " << n2 << '\n' << "n3 = " << n3 << '\n' << "n4 = " << n4 << '\n';
}
Output:
n1 = 5
n2 = 2
n3 = 4
n4 = 4
Try It Yourself:


2.12 Numeric Type Conversions

If an integral and a floating point variable or constant are mixed in an operation, the integral value is changed temporarily to its equivalent floating point representation before the operation is executed. This automatic conversion of an integral value to a floating point value is called type coercion. Type coercion also occurs when a floating point value is assigned to an integral variable. Coercion from an integer to a floating point is exact. Although the two values are represented differently in memory, both representations are exact. However, when a floating point value is coerced into an integral value, the fractional part is truncated.

Type changes can be made explicit by placing the value to be changed in parentheses and placing the name of the new type before it. This is called type casting or type conversion.

For example:

int value = 10.66;, int value = int(10.66); and int value = (int)10.66; produce the same result 10.


1.0 can be coerced into 1, but what about 1.5? Is it coerced into 1 or 2?

when a floating point value is coerced into an integral value, loss of information occurs unless the floating point value is a whole number.

For example, int value = 14.0; and int value = 14.37; produce the same result 14.

In summary, we have explicit and implicit data type conversion.

  • Type coercion is the implicit (automatic) conversion of a value from one data type to another.

  • Type casting is The explicit conversion of a value from one data type to another; also called type conversion.

Conversion function is declared like a non-static member function or member function template with no parameters, no explicit return type, and with the name of the form:

  • 1. Operator Conversion-type-id

    Declares a user-defined conversion function that participates in all implicit and explicit conversions.

    Conversion function is declared like a non-static member function or member function template with

    • no parameter,
    • no explicit return type, and
    • with the name of the form:

    Conversion function is declared like a non-static member function or member function template with no parameters, no explicit return type, and with the name of the form:

  • 2. Explicit Operator Conversion-type-id (since C++11)

    Declares a user-defined conversion function that participates in direct-initialization and explicit conversions only.

  • 3. Explicit (expression) Operator Conversion-type-id (since C++20)

    Declares a user-defined conversion function that is conditionally explicit.

2.13 Software Development Process

In software engineering, a software development process is the process of dividing software development work into distinct phases to improve design, product management, and project management. It is also known as a software development life cycle (SDLC). The methodology may include the pre-definition of specific deliverables and artifacts that are created and completed by a project team to develop or maintain an application.

Most modern development processes can be vaguely described as agile. Other methodologies include waterfall, prototyping, iterative and incremental development, spiral development, rapid application development, and extreme programming.

Some methodologies are sometimes known as software development life cycle (SDLC) methodologies, though this term could also be used more generally to refer to any methodology.

A life-cycle model is sometimes considered a more general term for a category of methodologies and a software development process a more specific term to refer to a specific process chosen by a specific organization.

[citation needed]

For example, there are many specific software development processes that fit the spiral life-cycle model. The field is often considered a subset of the system’s development life cycle.

2.14 Common Errors

  • TypeError: Type conversion

  • ValueError: Trying to change the value of a constant variable

  • LogicalError: Lack of using parentheses and getting the wrong Boolean expression

  • SyntaxError: Forgetting ; at the end of the lines that is needed

  • VariableError: Inappropriate variable initialization

2.15 Exercises

The sections named Exercises, are some optional questions that you can solve and write code for them. You can submit your code then it will be judged, then after a while you can see if it’s accepted or not.

Barnie Loves Promotion

McDook is a fast food Company, which is loved by all the people. Barnie is in love with McDook’s Slushy. She used to go to the east McDook every afternoon to buy slushy. Today there is 20% off on all the McDook’s frozen drinks. To get the offer, seller give you the height and width of the McDook building, and you have to calculate the area of McDook east branch. Barnie is not good at mathematics, so she asks you to write a program for her.

Your program should get the height and width of the McDook’s building in a line with a space between them. and print the area of the building in the next line.

  Click Here to see the answer code!

Barnie and 30% OFF

McDook seller is a kind boy. When he saw how much barnie loves promotions, he decided to give her 30% off instead of 20%. But he is give Barnie only and if only she solves a harder problem. This time, barnie should calculate the usable area of the McDook building. In McDook building there are a rectangle area that is used as McDook Kitchen, and it’s Staff only. Barnie don’t really know how to calculate the usable area, so she asks you to write a program that solve her problem.

Your program should get the height and width of the total and staff only area, respectively; and print out the usable area in the next line.

  Click Here to see the answer code!

2.16 Chapter Summary

All in all, now we know how a simple C++ program looks like. Also, we know how to declare variables, get them from user, and how to write expressions using them and operators.


References


  1. Liang, D. Y. (2013a). Introduction to Programming with C++ (MyProgrammingLab) (3rd ed.). Pearson.  2

  2. Wikipedia 

  3. CS110 C++ Arithmetic Expressions Lab. (2021). Uregina.Ca. 

  4. CS Dept C++ Variables. (2021). Uregina.