JUGInformation Engineering Laboratory - Semester 1

02 - Basics

02 - Basics

Helpful site

www.cplusplus.com is a great source of information about C++. You can use the search engine on the website to search for the commands you want to familiarise yourself with. Use it if you do not know how to utilise a particular function. Use it often to learn more!

using namespace std

Lets once again consider a simple C++ Hello World program from previous class:

#include <iostream>

using namespace std;

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

Now lets consider an equivalent code of:

#include <iostream>

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

As you can see the second code does not include line using namespace std;, however each command from C++ standard library are preceded by std::. C++ standard library command are all enclosed in something called namespace. You can call it globally by adding using namespace std; after include section or call it each time using std:: prefix. We recommend using the second std:: approach as it is compliant with official C++ coding standards.


🔨 🔥 Assignment 🔥 🔨

Create a new C++ project named basics , copy and paste the second std:: version of the Hello World. Build and run. In all later projects use the second template as a base of all your projects.


Variables

During programming course you will probably soon come across need to store some information. In C++ language information used in program can be stored as variables. Usually they are allocated in operational memory and can be accessed quickly comparing to for example reading from file.

Types

There are some basic types in C++. Most common and most useful are listed below:

Declaring variables

Prior to using variable you have to declare it. To do that you have to type the type of the variable followed by it’s name (name has to be unique) as in example below.

int a;                       // Signed integer with name "a"
float b;                     // Floating-point with name "b"

double floating_point_var;   // Floating-point with name "floating_point_var"

char id1, id2, id3;          // Three chars with names "id1", "id2", "id3"

Assigning values to variables

To assign value to a variable in some other place in a code, you have to use = operator. Value of a variable can be obtained by typing its’ name. Example below illustrates these operations.

int a;
int b;

a = 10;                       // Value of a = 10
a = 5 * a;                    // Value of a = 50
b = a + 2;                    // Value of b = 52

You can assign value to a variable during initialization.

float var1 = 12.5;           // Initial value 12.5
float fl2 = -4e3;            // Initial value -4e3 = -4000
int other_var = 4;           // Initial value 4

Printing variables

Ealier we have used std::cout to print a given text to a standard output. std::cout can also be used to print variable value, eg.:

#include <iostream>

int main() {
    int x = 10;
    int y = 3;

    std::cout << x << std::endl;
    std::cout << y << std::endl;

    return 0;
}

🔨 🔥 Assignment 🔥 🔨

  1. Declare an integer variable and assign some value to it. Print the value of that variable to the standard output using std::cout.
  2. Declare a new integer variable and assign a value of a previous variable multiplied by 4 to it. Print the value of that variable.
  3. Assign the value of 25 to the previous variable. Declare a new floating-point variable. Assign the value of the previous variable divided by 4 to it. What can you observe?

Converting types

If we divide an integer value the result will be always an integer. Executing code:

int a = 5;
float b = a / 2;

will cause the assigned value to be left as integer value, because expression on the right side of the = operator is treated as an integer expression (there are only integer values in it). To inform the compiler to treat integer value as a floating-point value we have to cast it.

To convert variable from one type to another you have to precede its name with static_cast<TYPE>() statement. Example below illustrates conversion from int to float:

int a = 5;

float b = static_cast<float>(a) / 2;        // Value of b = 2.5

🔨 🔥 Assignment 🔥 🔨

Fix your program, so dividing 25 / 4 gives a true, not integer, result.


Truncation

Integer variables have their range that depends on number of bits used to represent this variable. Writing value out of that range will result in truncation of this value. Example below illustrates this.

unsigned char a;

a = 255;         // a = 255
a = 256;         // a = 0
a = 310;         // a = 54

Naming your variables

Variable names should always be meaningful. The names a and b from the examples above are not very good at informing the person reading the code what they are supposed to store. Names like that will only work fine for very simple programs (like the one above). See an example below, is it not clearer?

int compund_1, compound_2, sum;

compund_1 = 5;
compund_2 = 10;
sum = compound_1 + compound_2;

More information on C++ variables

http://www.cplusplus.com/doc/tutorial/variables/

std::cout and std::cin

Displaying variables and text

Communication with external world is an important part of each program. Program needs to fetch input data, process it and return output data. You can achieve this using standard input and standard output, which often is a command line in which program was run. C++ way to write data to standard output is std::cout object. Example usage is visible below:

#include <iostream>

int main() {
   int x = 10;
   std::cout << "variable x = " << x << std::endl;

   return 0;
}

Firstly a text surrounded with " " is written to the output, than a value of x is joined, terminated with std::endl which displays a new line character. As you can see you can pass more than one argument to the stream and build a complicated display expressions and display more than one value at a time.


🔨 🔥 Assignment 🔥 🔨

Try the above code. Modify it to display more then one variable - create an int, float and bool type variables and display them all with additional text.


Formatting floating-point values

When displaying float values it is very important to format the floating-point value in order for it to be easily ridable for the user, see example below:

#include <iostream>
#include <iomanip>  // header needed for std::setprecision()

int main() {
    float nbr = 100.01;

    std::cout << "Default:         " << nbr << std::endl;
    std::cout << "Fixed:           " << std::fixed << nbr << std::endl;
    std::cout << "Hexfloat:        " << std::hexfloat << nbr << std::endl;
    std::cout << "Scientific:      " << std::scientific << nbr << std::endl;
    std::cout << "Back to default: " << std::defaultfloat << nbr << std::endl << std::endl;

    std::cout << "Default with precision: " << std::setprecision(3) << nbr << std::endl;
    std::cout << "Fixed with precision:   " << std::fixed << std::setprecision(3) << nbr << std::endl << std::endl;

    return 0;
}

🔨 🔥 Assignment 🔥 🔨

Try the above code. Change the precision of the displayed floating-point variable. Try changing the float value and see how the output changes.


Displaying values in different number systems

Sometimes it is necessary to display given variable in hex or octal format:

#include <iostream>

int main()
{
    int x = 45;
    std::cout << "x in octal: " << std::oct << x << std::endl
              << "x in hex:   " << std::hex << x << std::endl
              << "x decimal:  " << std::dec << x << std::endl;

    return 0;
}

Reading data from user

For reading data from a standard input std::cin object can be used:

#include <iostream>

int main() {
   int year;

   std::cout << "Enter current year: ";
   std::cin >> year;

   std::cout << "It is: " << year;
   std::cout << " , 23 years ago it was: " << year - 23 << std::endl;

   return 0;
}

Usage is similar to std::cout function. Notice that instead of writing to console (standard output) using << operator, we now read from console (standard input) using >> operator.

std::cin can be chained in order to read mote than one variable:

#include <iostream>

int main() {
    int a;
    float b;
    std::cin >> a >> b;

    return 0;
}

If you’ll feed 456 and 56.753 (separated by whitespace) to a standard input (console), variable a will be assigned value 456 and variable b value 56.753. You can notice that std::cin ends reading each value when it encounters a whitespace (eg. space or enter).


🔨 🔥 Assignment 🔥 🔨

  1. Write a program that will ask user to enter his age, height in meters and shoe size. Read provided information and print it back to the standard output. Use variables of proper types.
  2. Modify previous program so that the height is printed with decimal precision of 3.

Further reading on input streams and output streams:

Text input

In C and C++ programs text can be stored in char arrays. C++ introduces additional, friendly type: std::string.

We will work with C-style char arrays for now. Length of an array should be set to a maximal expected length of a text plus 1 (for a special, null value indicating the end of the string). Length of an array is denoted by a number in a [] brackets placed after its name. Example:

std::cout << "Please enter your name: ";

char name[20];
std::cin >> name;

std::cout << "Your name is: " << name << std::endl;

Random number generator

To generate random numbers special rand function can be used. It uses pseudo-random generator that generates numbers based on a seed value. For the same seed each sequence of generated number will be the same. Due to this fact generators are sometimes initialized with a current timestamp, which causes the rand to produce different number sequences with every run. In order to use this functions you have to include two additional headers <cstdlib> and <ctime>:

#include <cstdlib>              // Header with rand() and srand() functions
#include <ctime>                // Header with time() function

int main()
{
    srand(time(nullptr));          // Initialize pseudo-random generator with current time
    int a = rand() % 100 + 50;  // Generate random number in range 50..149

    return 0;
}

The rand() function returns an integer number in range 0 to RAND_MAX (which is defined in the library, you can print it to check its’ value). To obtain value in a specified range you can use % (modulo) operator combined with a + operator.

More information on rand(): http://www.cplusplus.com/reference/cstdlib/rand/?kw=rand

<cmath>

One of the useful libraries included in C++ is a math library that comes with a functions for computing for example sine and cosine values. To make all those functions available in your program you have to include it:

#include <cmath>

Now you can use functions that are listed here: http://www.cplusplus.com/reference/cmath/?kw=cmath

Example of computing sine value of 30 degrees angle:

const double pi = 3.14159265359;             // Constant value of Pi number

double degrees = 30;                         // Variable with angle value in degrees

double sine_value = sin(degrees * pi / 180); // Function accepts values in
                                             // radians, so we need to
                                             // do the conversion from degrees

Values that are constant during a program execution can be declared using const qualifiers. Such values can be used in expressions as regular variables, but they are usually optimized by the compiler so that no additional read from memory is needed.


🔨 🔥 Assignment 🔥 🔨

  1. Create a program that will generate a random integer angle value in a range -90...90 degrees, compute its cosine and print it to the standard output.
  2. Now additionally compute 5-th root of computed cosine value and print it. Tip: 1_equation.

Final assignments 🔥 🔨

Exercise 1

Hint 1: Use Heron’s formula (https://en.wikipedia.org/wiki/Heron%27s_formula) to calculate triangle area based on the lengths of the sides.

Hint 2: Use law of cosines (https://en.wikipedia.org/wiki/Law_of_cosines) to calculate the angles of triangle.

Hint 3: Inverse trigonometric functions arcsine, arccosine, and arctangent are part of cmath library (they are provided under following names: asin(), acos(), and atan2(). Pay attention to the returned values as they are provided in radians.

Exercise 2

Load two numbers given by the user and perform add, multiply, subtract and divide operations on them. Print numbers on the screen. Write two versions:

Exercise 3

Load one number given by the user and perform pre- (++i) and post- (i++) incrementation operations on it. Do the same with pre- (--i) and post- (i--) decrementation.

Hint:: To observe difference between pre- and post- operators put them directly in a print command (e.g. std::cout << ++a << std::endl;).

Exercise 4

Write program that will output the following text (all the information are provided by the user - preserve formatting):

First name: Jan
Second name: Kowalski
Father's first name: Antoni
Father’s age: 55
Mother’s first name: Jadwiga
Mother’s age: 50
Mother’s family name: Kazmierczak
Birth place: Poznan
Birth year: 1970
Birth month: 6
Birth day: 12

Citizen Jan Kowalski was born in Poznan 30 years ago. His mother, mrs Jadwiga (of a Kazmierczak), was 20 years old then and his father 25 years old.

Kowalski Jan till 12.10.2015 lived approximately 11155 days.
His father is 1.83 times older than him and mother 1.67 times.
It is an old family, because together they have 135 years.

Hint: To store string such as name you have to use char array. Declare it using the following syntax:

char name[20];

Number in [] brackets specify maximal length of a string plus 1 (for a special value indicating the end of the string).


Authors: Michał Fularz, Jan Wietrzykowski, Dominik Pieczyński, Tomasz Mańkowski