Laboratory Training 1

Design of Algorithms

1 Training Tasks

1.1 Implementation of a Branching Algorithm

Implement an algorithm for solving quadratic equation. The algorithm should consider all possible data. In particular, the discriminant should be checked, and it should be checked whether the equation is quadratic. If the equation degenerates into a linear one, it is necessary to provide for finding the root of this linear equation, or to establish the presence of infinite count of solutions (absence of solutions). Use the UML Activity diagram for algorithm presentation.

1.2 Implementation of a Looping Algorithm

Implement an algorithm for calculating the following expression:

y = 1/(x + 2) + 2/(x + 4) + ... + (k - 1)/(x + 2(k - 1)) + (k + 1)/(x + 2(k + 1)) + ... + n/(x + 2n)

 

Use the UML Activity diagram for algorithm presentation. Provide a check of possible errors.

1.3 Individual Assignment

You should develop an algorithm of a program that calculates values of a function in a given range. Your program should read interval boundaries, step of argument increasing, and n value.

Your algorithm should be represented using the UML Activity diagram. It should contain such parts:

  • data reading
  • main loop, in which you set a new value of an argument and show both this value and calculated value of a function; then need to increase the argument value.

The particular function is given in the individual task according to your own index in the group students list (index of variant).

2 Instructions

2.1 Basic Concepts of Computer Science

2.1.1 Numeral Systems

A numeral system is a set of rules and symbols that allows encoding any number. The most common are positional numeral systems (positional notations), in which the value of a digit depends on position in the number representation.

The positional numeral system is concerned with the concept of base (radix) of notation. Any number can be represented as a sum of sequential powers of a radix multiplied by values of the relevant digits. The base or radix is also the number of unique digits that a positional numeral system uses to represent numbers. As radix we can use any number not less than two. The Name of notation corresponds to its base (decimal, binary, octal, hexadecimal, and so on). In everyday practice, we use the decimal notation.

The binary notation traditionally used in computing. All data is represented using sequences of zeros and ones. This notation has two main advantages:

  • to represent the numbers 1, a non-zero electronic signal is used; because the signal amplitude does not matter, it significantly improves the reliability and data storage;
  • rules of arithmetic are very simple and can be easily implemented by hardware.

The disadvantages of the binary notation include awkwardness and lack of visibility. In cases where binary representation is important, we can use other notations which bases are powers of two. In the previous decades octal notation was used. Now the most used is hexadecimal notation (with base 16). A hexadecimal digit is the one of the ten decimal digits or the one of the letters A (10), B (11), C (12), D (13), E (14), and F (15).

The table below shows a decimal, binary and hexadecimal representation of numbers from 1 to 32:

Decimal Binary Hexadecimal Decimal Binary Hexadecimal
1 00000001 1 17 00010001 11
2 00000010 2 18 00010010 12
3 00000011 3 19 00010011 13
4 00000100 4 20 00010100 14
5 00000101 5 21 00010101 15
6 00000110 6 22 00010110 16
7 00000111 7 23 00010111 17
8 00001000 8 24 00011000 18
9 00001001 9 25 00011001 19
10 00001010 a 26 00011010 1a
11 00001011 b 27 00011011 1b
12 00001100 c 28 00011100 1c
13 00001101 d 29 00011101 1d
14 00001110 e 30 00011110 1e
15 00001111 f 31 00011111 1f
16 00010000 10 32 00100000 20

Formally, the base is usually indicated as an index of the number. For example,

2710 = 110112 = 1B16

There are several ways to obtain numbers in various number systems. The most common way to convert from decimal notation to other number systems is a multiple division of the initial number and intermediate results onto the base of the number system and obtaining an integer part of division. The last result and the remainders received are copied in the reverse order. For example, in this way you can get a binary representation of 25:

Copying the last result and remainders from division, we get

2510 = 110012

The inverse transformation is carried out by finding the sum of the products of numbers and descending powers of the base:

110012 = 1 × 24 + 1 × 23 + 0 × 22 + 0 × 21 + 1 × 20 = 2510

To convert a number from binary notation to hexadecimal notation every four bits, from right, should be replaced with a single hexadecimal digit. The reverse conversion is similar: each hexadecimal digit should be replaced by four binary digits.

2.1.2 Software

The word program is used in two ways:

  • to describe individual instructions, or source code, created by the programmer;
  • to describe an entire piece of executable software.

Hardware is the physical, touchable, material parts of a computer or other system.

Software is a set of software programs and documents necessary for operating these programs. Software can be classified into such parts as:

  • System software - computer software designed to operate and control hardware components and application programs; it includes:
    • operating systems;
    • service utilities;
    • DBMS (database management systems)
    • device drivers;
  • Application software includes programs and packages designed to solve problems of users in specific domains; application software include word processors, graphic editors, polygraphic systems, programs for scientific and technical calculations, games and so on;
  • tools - software designed for creating other software; tools include compilers and other tools for linking and debug, integrated development environments (IDE), and CASE-system (Computer-Aided Software Engineering).

An application is a synonym for computer application program. This term can be also applied to any program that is not part of the operating system.

2.1.3 Operating Systems

An operating system is a set of software tools that manage all resources and processes of a computer system. Resources are processor, memory, display, and peripherals (external devices). Processes are separate programs, which obtained necessary resources and launched for execution.

Components of operating systems can be grouped as follows:

  • kernel (scheduler, device drivers, network support, file system);
  • system libraries;
  • utilities.

Examples of operating systems are MS-DOS, OS/2, Mac OS, MS Windows of various versions, UNIX, Linux, Solaris, Google Android, etc.

2.1.4 File system

A file system is a set of method and rules for the organization and storage of directories and files on the external device. Sometimes file system also means a set of files and directories on a specific device.

File systems are classified into hierarchical file systems (files and subdirectories can be arbitrary nesting) and flat file systems (set of files without subdirectories). Hierarchical file systems are currently most used. There are special types of file systems:

  • clustered file systems can distribute files across multiple physical devices of the single computer;
  • network file systems provide mechanisms for file access one computer from other computers on the network;
  • distributed file systems provide file storage by their distribution between multiple computers on the network.

The file system is usually considered as part of the operating system. Each operating system provides a set of file systems. For example, file systems FAT 16, FAT 32, NTFS associated with Windows, Ext2, Ext3, Ext4 used in Linux.

2.1.5 Text Files and Binary Files

Regardless of the file system, all files can be divided into text files and binary files.

A text file is a computer file in which all the information is represented in the form of characters (symbols) of a particular character set. The sequences of characters are split into lines. To separate lines from each other special separators are used (one or more special control characters). Examples of text files are simple documents created using notepad (*.txt), the source code of programs (*.pas, *.c, *.cpp, *.cs, *.java, etc.), hypertext markup files (*.htm, *.html), formatted documents (*.rtf), and so on. Preparation and editing text files, regardless of their format and special purpose can be done using universal text editors, such as Notepad.

A binary file is a computer file in which data are represented using binary numbers, according to an internal representation in memory (not by symbols as in text files). Every single binary file format requires special software. Examples of binary files are executables (programs) under all operating systems, raster images (*.tif, *.jpeg, *.png, *.gif, etc.), archives (*.zip, *.rar, etc.), audio files and video files of all formats, binary code files (*.obj, *.class, etc.), as well as many special formats of software packages.

2.2 Basic Concepts of Programming

2.2.1 Programming Languages

A programming language is a special notation designed to set instructions to a computer. Programming languages can be classified as low-level languages and high-level languages.

  • low-level languages designed for a specific computer and reflects its machine code; this group contains machine instructions and assembly language;
  • high-level languages are independent of the internal machine code of any particular computer. Programmers can work with abstract data.

High level languages are divided into the following groups:

  • procedural (FORTRAN, ALGOL-60, BASIC, ALGOL-68, PASCAL, C, Modula-2, etc.);
  • object-oriented (Simula-67, Smalltalk-80, C++, ADA, Object Pascal, OBERON, Java, C#, etc.).

There are also languages of functional, logical, declarative programming, etc.

2.2.2 Interpreters and Compilers. Stages of Program Development

The instructions of high-level programming language should be translated into machine code by a special program called translator. Translators can be of two types: interpreters and compilers.

  • An interpreter translates a program as it reads it, turning the program instructions, or code, directly into actions; examples of interpreters are BASIC, JavaScript, etc.; interpreters provide flexibility and create effect of instant performance, but the need for multiple translation of previously interpreted lines at runtime significantly reduces the effectiveness of the program;
  • A compiler translates the code into a set of commands that can execute processor or virtual machine; programs written in Pascal, C++, C# and many others, are always processed by compilers.

Typical stages of program development are the following:

  • a source code of the program being prepared by text editor;
  • the source code is translated into a set of binary instructions (binary code); it can be machine code, as in C++, or intermediate binary code, as in Java;
  • compiled code is linked from individual parts and executed.

Unfortunately, almost every program, no matter how trivial, can have errors, or bugs. Program execution in order to identify errors and verify compliance with algorithm is called debug.

2.2.3 Types of Applications

Applications that are created in modern programming environments in terms of user interaction can be divided into two main groups:

  • console applications;
  • graphical user interface applications (GUI applications).

Console applications run in a special console window or in full-screen mode. To enter data, keyboard (standard input device) is used. Data can be read either as command line arguments (after the name of the program in the command line) or at runtime.

The common logic of console applications is built on so-called data-driven paradigm. The overall structure of the program includes input of initial data, computing and display results. During the calculations, based on data and intermediate results, branching, looping, or subroutine call can be done.

GUI applications provide user interaction through graphical controls (buttons, menu items, list items, scroll bars, etc.) and various technical input and positioning devices (keyboard, mouse, joystick, etc.). The results can also be displayed in windows or dialog boxes in the form of text, graphics, etc.

The complex interaction logic prevents data-driven programming techniques. Instead of it, event-driven paradigm is used. The entire program consists of initialization (registration visual controls) and the main loop of receiving and processing events. Examples of events are moving or clicking mouse, keyboard input, and so on. Each registered visual control can receive events related to it and perform processing event handlers - functions that process these events.

Typically, you create one or more windows, and then you add visual controls to these windows. For these items you can create and register event handlers. The basic cycle of receiving and processing events is performed by standard means (through application framework). Developers of particular program only need to add the necessary elements and write functions for handling events.

2.3 Algorithms

An algorithm is a detailed description of the sequence of actions aimed at solving a particular problem. The goal of the algorithm is to be achieved by the finite number of steps. Algorithms are usually divided into linear algorithms, branching algorithms and cyclic algorithms.

We can represent algorithms in several ways:

  • verbal description
  • pseudocode (artificial algorithmic language)
  • graphical representation

The graphical representation is more descriptive. There are two standard forms of graphical algorithm representation: traditional flowchart (block diagram) and activity diagram.

The present-day representation of flowcharting is based on Unified Modeling Language. Unified Modeling Language (UML) allows graphical representation of models of complex software systems. UML gives a set of diagrams for visualization of systems' design. A diagram is a graphical presentation of a collection of model elements, most often rendered as a connected graph of relationships and other model elements.

An activity diagram is one of standard UML's diagrams. Activity diagrams are very similar to flowcharts because you can model a workflow from activity to activity. Activity diagrams can be used for representation of algorithm.

Typically, Activity diagram includes such elements:

  • Initial State
  • Activity
  • State Transition
  • Decision Symbol
  • Final State

It is always necessary to describe the initial state. The initial state is represented by a large black dot. The only initial state can present on a diagram.

Each activity represents a particular state within the execution of the encompassing method.

Activities are linked by automatic transitions, represented by arrows.

UML defines an optional stereotype for displaying decisions. A decision is represented by a rhombus with several transitions coming out of it.

A final state is represented by a big black dot surrounded by a circle. One diagram can contain several final states.

One and only one arrow issues from the initial state. An action element requires one arrow to enter and one to exit. There should be no operation without any arrow. Multiple arrows can only come from the decision symbol.

The following diagram shows an algorithm for finding of arithmetic mean (average value). This is a typical linear algorithm without branching and loops, because all actions are performed once, and under any conditions:

An algorithm that calculates reciprocal value requires checking whether the divider takes the value 0 or not:

Cyclic (looping) algorithm involves performing certain calculations several times. All these actions that are repeated cyclically are called the body of the loop. Before the start of the loop or after the action in the body we need to verify the necessity of re-entry into the body of the loop. The following algorithm describes the actions associated with the reading of an integer value (n) and finding powers of 2: from the first to the n-th:

When creating algorithms using activity diagrams, individual messages can be displayed in any human language, because the diagram is not associated with a specific programming language and its software implementation is performed manually. The main thing: the diagram should be understandable to the executor.

2.4 Main Features of C++ Programming Language

The C++ programming language was invented in 1983 by Danish researcher Bjarne Stroustrup.

The base for C++ was C language – a multi-purpose, concise and relatively low-level programming language. C is retained as a subset. The main features of C++ compared to C are as follows:

  • strict typing;
  • support for object-oriented programming;
  • support for templates and generic programming;
  • advanced procedural programming capabilities.

C++ combines the ability to represent complex data structures and the ability to write effective low-level programs. New object-oriented languages ​​were later created based on the C++ syntax. First of all, these are Java and C# languages.

In August 1998, the C++ language standard was ratified. The C++ Standard is a document that fully describes the syntax of a language and its possible use. In addition to the basic tools of the C++ programming language, the standard includes the so-called Standard C++ Library. All the latest versions of C++ programming compilers must support the language standard. Some companies offer special packages that test the "standard" implementation of C++. The C++ Standard was updated in 2003, 2011 and 2014.

2.5 Steps of Development of a C++ Program

There are several typical steps of program development

  • The source code can be prepared using any text editor.
  • Preprocessing of source code is carried out and the so-called translation unit is created. In most cases, preprocessing is combined with compiling.
  • The translation unit turns into an executable program using a compiler. If compilation is not possible due to compiler errors, a list of these errors is displayed. If there are no syntax errors, the source code is compiled an object module is produced. This is a machine code file that contains links to functions that are missing from this module. This file is often has the .obj extension.
  • unresolved references are processed using the so-called linker, a special subroutine that connects several object modules, as well as adds compiled functions from standard libraries (files with the .lib extension). In addition, functions that are not referenced are removed from the code. The result of the linker's work is an executable file (*.exe) or a library.

During operation, runtime errors may occur, which are reflected in separate dialog boxes, as well as logical errors (the program performs unexpected actions and you do not get the proper result). Whatever type of bug you find, you must fix it, and that involves editing your source code, recompiling and relinking, and then rerunning the program.

2.6 Microsoft Visual Studio Programming Environment

2.6.1 Installing the Program and Creating a New Project

Microsoft Visual Studio is a complete suite of development tools for building applications using Visual Basic .NET, C, C++, F++, C#, as well as support for Web-programming. This all languages use the same integrated development environment (IDE). The integrated development environment allows the programmer to create projects, access help files, edit, and compile the code in place, and to resolve compile and link errors.

You can download the IDE from https://visualstudio.microsoft.com/downloads. Select the Community option and click on the Free download button. The Visual Studio Installer is loaded. By clicking on the Continue you start the installation process. In the window Installer - Visual Studio Community among the various options, select Desktop development with C++ and click Install. On the next page, you can leave everything unchanged.

After you launched the IDE first, a Start Page appears, which in particular contains buttons Open project or solution and Create a new Project. Now you can create a new project.

Note: if a solution has already been created, a new project can be created using the main menu function File | New | Project... or by pressing Ctrl+Shif+N.

A project is the key concept of application development in Visual Studio. A project can be defined as a configuration and a group of files that produce an executable program or DLL (Dynamic link library). The project source files are usually stored in a separate folder. Within the project, you can create multiple configurations. A configuration is an agreed collection of settings related to a specific purpose. Each project contains at least two configurations - a debug configuration and a release configuration.

To create a new project in a wizard,

  • in the Installed pane, select a project type: Empty Project
  • type a project name in the Name box; a default location for the new project is supplied automatically, but you can change the drive and path
  • choose the name of the solution, which for simple projects coincides with the name of the project; for simple projects it is also advisable to select the option Place solution and project in the same directory;
  • Click OK and the empty project opens.

Note: you can also use the Console App template, but then you will need to manually delete unnecessary comments and statements such as output of "Hello World!" string.

To create a new source file,

  • In the Project menu, click Add New Item... (or Add | New Item... in context menu of solution explorer project's item).
  • Select a file type: C++ File. It is recommended to type a file name in the Name box. Otherwise the name will be set to Source.cpp.
  • Click OK, and the empty file opens in editor pane.

Now you can type and save the source text. You can execute new program by pressing Ctrl-F5 (Start Without Debugging).

2.6.2 Using the Debugger

Debugging tools are used to find and fix logical errors.

Programs allow not only automatic execution, but also step by step program execution. The text of the program should have at least one breakpoint. This can be done by pressing F9, when the cursor is in the correct line. When the program is running in debug mode, breakpoints cause the temporary stop of the program.

Now you can start program in debugging mode (Debug | Start Debugging or F5). Your application starts up and runs until it reaches a breakpoint. You can break execution at any time to examine values, and otherwise examine the state of your program. To continue normal (not stepwise) execution, use F5. If you want to continue stepwise execution, you can use several commands:

  • Debug | Step Into, function key F11: with entering into the body of the subprogram for debugging;
  • Debug | Step Over, function key F10: without entering into the body of the subprogram for debugging.

If you place the mouse pointer on a variable, its value can be seen in a small window. You can also watch and edit values of variables in special subwindows.

The Find Symbol Results window contains three tabs:

  • The Autos tab displays information about variables used in the current statement and the previous statement.
  • The Locals tab displays information about variables that are local to the current function.
  • The Watch 1 tab allows watch and editing of values stored in variables.

If the Locals window contains an array, object, or structure variable, a button appears next to the variable name. By clicking the button, you can expand or contract your view of the variable. The button displays a plus sign (+) when the variable is displayed in contracted form and a minus sign when it is displayed in expanded form.

You can terminate execution using DEBUG | Stop Debugging (Shift-F5). You can also stop the program and start it from the beginning (Debug | Restart or Ctrl-Shif-F5).

The programs given in Examples 3.6 and 3.7 can be reproduced in the Visual Studio environment. Line numbers in the following examples are not a part of code. These numbers can be removed together with comments, in which they are located. The syntactic structures, used in programs will be explained in detail later.

2.7 The First C++ Program

Studying programming languages traditionally begins with the creation of the "Hello, World!" program. To create such a program in C++, we need to prepare a new empty project in Visual Studio. Let this project be called Hello. Next, we add an empty Source.cpp file for the source code. In this file we will place our program in the simplest version:

#include <iostream>

void main()
{
    std::cout << "Hello, World!";
}

The first line of code is a preprocessor directive, which specifies the inclusion of standard iostream header file. This file contains declarations of the required objects, in particular the std::cout object, which is used to display the result in the console window. ext is the title of the main() function, which is a starting point of the program. Then in parentheses allocated the body of the main() function with one statement. The greeting string is output to the standard output stream.

In order to after the output of the text "Hello, World!" the cursor was moved to a new line, you should change the line in which the output is performed, as follows:

std::cout << "Hello, World!" << std::endl;

Adding a std::endl manipulator to a stream provides a newline. In order not to use the std prefix (namespace name) twice, you can add a namespace directive to the program (after the #include <iostream> preprocessor directive):

using namespace std;

Now the line in which the results are output will be as follows:

cout << "Hello, World!" << endl;

In order for the compiler not to generate a warning "return type of 'main' should be 'int' instead of 'void'" the result type of the main() function must be changed. If you'll use int instead of void, you'll be able to analyze the success of the program at the operating system level. Now our program will look like this:

#include <iostream>

using namespace std;

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

After starting program (Debug | Start Without Debugging) the greeting text will appear in a specially created console window.

3 Sample Algorithms and Programs

3.1 Linear Equation

An example of a branching algorithm (without looping) is an algorithm for solving a linear equation:

ax + b = 0

If a is not equals to zero,

x = –b / a

If both a and b are zeros, any value can be treated as the root of an equation. If b is non-zero value, but a is not, equation cannot be solved. This should be displayed on the diagram:

3.2 The Calculation of Sum

Cyclic algorithms are very often used to calculate sums of sequences. Suppose we need to read the value n and calculate such sum:

y = 12 + 22 + 32 + ... + n2

The algorithm for calculating the sum may look like this:

As can be seen from the algorithm, first we assign 0 to the result, and then at each step we add the next summand.

3.3 Calculating the Product

The calculation of products is typically implemented through assigning the result of the initial value of 1 and the sequential multiplication of the current result and the next multiplicand. Suppose it is necessary to calculate such a product:

p = x(x – 1)(x + 2)(x – 3) ... (x + (–1)n n)

Additional problem is concerned with alternating signs in multiplicands. There is common solution of this problem: we create a special additional coefficient (for example, k), which is sequentially equal to 1 or –1. Calculation of powers of –1 does not make sense in any case. The algorithm may be like that:

The diagram above contains so-called annotation, the arbitrary text with an explanation that can be linked to a certain element .

3.4 The Sum of Products

Sometimes, there is a need to realize the nested loops. For example, when we need to get the sum of all cells of a rectangular table or calculate the sum of products, the sum of sums, the product of products, etc.

It is necessary to enter the value of n and calculate y by the formula

We need to start with the analysis of the task. We can present a formula in a more convenient form:

у = (1 + 12)(1 + 22)...(1 + (n – 1)2) + (2 + 12)(2 + 22)...(2 + (n – 1)2) + ... + ((n – 1) + 12)((n – 1) + 22)...((n – 1) + (n – 1)2)

For example, if n is 4, we get:

у = (1 + 12)(1 + 22)(1 + 32) + (2 + 12)(2 + 22)(2 + 32) + (3 + 12)(3 + 22)(3 + 32) = 634

The algorithm can be as follows:

It is important to initialize the inner product with initial value (1) on each step of outer loop.

3.5 The Product of Sums

Another example of implementing an algorithm with nested looping is the calculation of the product of sums. It is necessary to enter the value of n, calculate y by the formula

and show the result.

As in the preceding example, we can represent the formula in a more convenient form:

Before calculations, it is necessary to check whether the value of n, which was entered by user, more than or equal to 2, otherwise the formula loses sense and an error message should be displayed. The algorithm can be as follows:

Similarly to the previous example, it is very important to initialize the internal sum every time at each step of the external cycle.

3.6 General Algorithm of the Individual Task

According to the individual task, it is necessary to create an algorithm of the program of calculating values of the function in a given range. The total algorithm frame may be like that:

You should describe the possible options for incorrect data in more detail, and you should ensure the condition of the individual task.

3.7 Average Speed

Assume that we need to write a program that reads value of distance between two cities and value of time trip and shows an average speed. The program will implement a linear algorithm similar to shown in Fig. 2.5. Our program will be as follows:

/* 01 */  // Average speed
/* 02 */  #include <iostream>
/* 03 */  using namespace std;

/* 04 */  int main(int argc, char* argv[])
/* 05 */  {
/* 06 */      float s, t;
/* 07 */      cout << "Enter distance and time:" << endl;
/* 08 */      cin >> s >> t;
/* 19 */      float v = s / t;
/* 10 */      cout << "Speed is " << v << endl;
/* 11 */      return 0;
/* 12 */  }

Line 01 contains a comment that is some explanatory text embedded in program intended to help human readers understand it. Comments are simply text that is ignored by the compiler.

Line 02 represents a preprocessor directive. Preprocessor is a subprogram that provides some actions according to its directives and creates so-called translation unit. According to include directive, preprocessor inserts the text of a given header file into translation unit. The standard header file iostream contains declarations of standard input stream cin (keyboard), standard output stream cout (console window), and manipulator endl (end of line).

Line 03 contains directive that implements connecting so called namespace. In our example, we connect namespace called std. This connection provides the ability to use names cin, cout and endl directly, instead of std::cin, std::cout, and std::endl.

Note: connecting all the names of a certain namespace can produce name conflicts and are therefore acceptable only in small training programs.

Line 04 constitutes a title of a main function. The execution of any program starts from a first statement of a function named main(). The brackets constitute the list of arguments. The integer argument argc represents count of command line parameters. The argument argv represents a pointer to an array of command line parameters. If you don't process command line arguments, you can define main() function without arguments:

int main()
{

}

The braces on lines 05 and 12 bound the programming block of a main function. Programming block contains statements to be executed.

Line 06 contains definition of two floating point (real) variables. This type is used to represent real numbers. The variable s will store the distance, and t will store time.

The statement on line 07 performs an output some message on the screen. When the statement is executed, the text string (without quotation marks) is displayed. Placing the endl manipulator in the output stream ensures that the cursor moves to a new line.

The user inputs two values (line 08). New variable v obtains a new calculated value (line 09). Line 10 contains a statement which performs an output of a string literal "Speed is " followed by previously calculated value.

The returning value of main() function set in line 11 can be used by operating system. The value 0 signals that program terminates normally.

Note. If you start the program without debugging (Ctrl-F5), you'll get an additional message after its finishing:"Press any key to continue . . .". You can finish the job by pressing any key. If the line does not appear, for example, through the launch with debugging (F5), the invocation of a special function is needed:

system("pause"); // "Press any key to continue . . ." 
return 0;

3.8 Integer Power

The following program calculates an integer power (looping algorithm, similar to one shown on fig. 2.8):

/* 01 */  // Integer power
/* 02 */  #include <iostream>
/* 03 */  using namespace std;

/* 04 */  int main()
/* 05 */  {   
/* 06 */      float x;
/* 07 */      int n;
/* 08 */      cout << "Enter base of power and exponent of power:" << endl;
/* 09 */      cin >> x >> n;
/* 10 */      float power = 1;
/* 11 */      for (int i = 1; i <= n; i++)
/* 12 */          power *= x;
/* 13 */      cout << "Power is " << power << endl;
/* 14 */      return 0;
/* 15 */  }

In contrast to base of power x, the exponent n is defined as an integer variable (line 07).

The value 1 assigned to a new variable named power is considered as the first approximation of a sought result (line 10).

Line 11 contains the header of a for statement. A for loop causes your program to repeat a sequence of statements. Before this, the cycle index i obtains a value 1. This value stepwise increases by one (i++) as long as the condition i <= n (less or equals) remains true. At each step of the cycle a statement within the looping body is executed. This statement is allocated immediately after the for (...) statement.

Line 12 constitutes a loop body. The value of power variable becomes equal to previous value multiplied by x n times.

4 Exercises

Exercises are performed by students who want to get an excellent grade. Programs can be created by reprocessing the above examples

Task 1

Develop an algorithm of the program that reads some distance in inches and shows it in millimeters (1 inch = 25.4 mm).

Task 2

Develop an algorithm of the program that reads eight values and returns an average.

Task 3

Develop an algorithm of the program that reads value of integer variable n and returns n!

5 Quiz

  1. What is a positional notation?
  2. What is a base of the numeral system?
  3. What are advantages and disadvantages of binary notation?
  4. What is the usage of the hexadecimal notation?
  5. Define the concept of software.
  6. How can classify software?
  7. What are tools?
  8. What is application?
  9. List the functions of the operating system.
  10. Give examples of operating systems.
  11. What is a file system?
  12. What is the difference between text files and binary files?
  13. Give examples of text and binary files.
  14. What determines the level of programming language?
  15. How to define the term "computer program"?
  16. What are the stages of program development?
  17. What is debugging?
  18. What is console application and how it differs from other types of applications?
  19. What are the advantages and disadvantages of interpreters and compilers?
  20. What is an algorithm?
  21. What are ways of algorithm representation?
  22. What are the different types of algorithms?
  23. What is UML?
  24. What is UML diagram?
  25. What is the difference between block diagram (flowchart) and activity diagram?
  26. What is the difference between representation of decision elements in block diagram (flowchart) and activity diagram?
  27. What is the difference between representation of output and calculation in Activity diagram notation?
  28. What are steps of development of a C++ program?
  29. What is the difference between compiler and linker?
  30. What is Integrated Development Environment?
  31. What programming languages are supported by Visual Studio?
  32. What is debugging?
  33. How to create a new project in Visual Studio?
  34. How to debug programs in Visual Studio?

 

up