Implementation of the division algorithm in C++

<<algorithm

 

alg div en

#include <iostream>
using namespace std;
int main(void){
  float x, y;
  cout<<"x = ";
  cin>>x;
  cout<<"y = ";
  cin>>y;
  if(y==0)
    cout<<"Can not divide by 0";
  else{
    float z;
    z=x/y;
    cout<<"z = "<<z;
  };
  cout<<endl;
  char c;
  cin>>c;
}


 

In the first line of the program, we include the iostream header file (Input/Output streams library). This is essential because later in the program we will want the ability to write to the screen (cout) and read input data from the keyboard (cin).

In the second line, we inform the compiler that we will be using names defined in the std namespace (specifically: cin, cout, and endl). If we didn't do this, it would be necessary to use the longer form of qualified names (std::cin, std::cout, std::endl).

In C++, a program begins with the execution of the main function. In our example, this is the program's only function. Line 3 contains the start of the main function definition, which is the beginning of our algorithm's execution (START block (1)).

In the next line, we declare two variables, x and y, which we will be using shortly. In C++, variables can be declared anywhere before their use, which is why we don't immediately declare the variable z, which might not be needed at all.

Lines 5 to 8 implement the Input/Output operation (2), where the input data—the dividend and the divisor—are retrieved.

The conditional statement on line 9 is the Decision block (3) from our algorithm. The statement checks whether y is equal to 0. If the condition is met, the instruction written on line 10 is executed (corresponding to the Input/Output block (4) in the algorithm). If the condition is not met, the instruction following the keyword else is executed; in our case, this is a compound statement enclosed in curly braces {} between lines 11 and 15. First, on line 12, we declare the variable z (now we know we'll need it), then on line 13, we calculate the quotient of x divided by y (Operation block (5)), and finally, on line 14, we output the received result (Input/Output block (6)).

The instructions on lines 16-18 have no relation to the execution of the division algorithm. They serve to pause the program until any character is entered and the Enter key is pressed, which prevents the program window from closing immediately.

The closing curly brace } on line 19 ends the main function and, consequently, the execution of the entire program (Stop block of the algorithm (7)).