top of page
Writer's pictureD A Rosi Arsida Wardani

C++ Program and Algorithm | Counting Fractions


 

Algorithm series_counting

{calculate fraction series based on user input}

Declaration

n : integer

Description

read (n)

count (n, i, j)

if (i > n) then

return j

else

if (i%2 == 0) then

j -= 1/j

else

j += 1/j

end if

end if

return hitung (n, i+1, j)

write (count (n, 1, 0))


 

Flowchart



 

C++ Program


#include <iostream>

using namespace std; 

class count{
	friend ostream& operator<<(ostream&, count&);
	friend istream& operator>>(istream&, count&);

	public:
           void process(int n, int i, float j);
           input();
           print();
   	   int n;
    
};

count::input(){
    cout << "n : ";
    cin >> n;
}

void count::process (int n, int i, float j) {
   if (i>n) {
      cout << j << endl;   
   }
   else {
      if (i % 2==0) {
         j =j-(float)1/i;
      }
      else {
         j =j+(float)1/i;
      }
      process(n,i+1,j);
   }
}

count::print(){
	process(n,1,0);	
}

int main(){
	count x;
	
	x.input();
	x.print();

	return 0;
}

Output :



Recent Posts

See All

One-dimensional Arrays

One-dimensional arrays are data structures that contain data types of the same type. In the form of a group of related memories...

Loop

Introduction Examples of algorithms in everyday life : Example 1 : To finish eating a plate of rice (initial conditions) Mouthfuls of a...

Comments


Post: Blog2_Post
bottom of page