WRITE ONE C PROGRAM THAT SATISFIES THE FOLLOWING 1 An input

WRITE ONE C++ PROGRAM THAT SATISFIES THE FOLLOWING:


1. An input file A1.txt is given where each line consists of two integers: n and r.
2. Read each line of the input file using a loop and perform the following operations:

(a) If n is a positive integer and r is a nonnegative integer where r n, then find the number of r-permutations and r-combinations of a set with n elements when repetition is NOT allowed.

(b) The output file B1.txt will contain 4 integers in the following format: n r r-permutations r -combinations.

(c) Ifr>n,thenprint‘r>nerror’.

Note: You have to read the file using loops. The number of lines in A1.txt can be more than 10.

Sample input:

7 2

8 9

Sample Output:

7 2 42 21

8 9 r>n error

The contents of A1.text are:

Solution

/*

After running this program you will get \"Done !\" on console screen and file B1.txt will be generated

*/

#include<iostream>
#include<fstream>

using namespace std;

//calculation of factorial of number
long long int fact(int num)
{
long long int factorial = 1;
if(num < 0)
return num;

else
{
for(int i=1; i <= num; i++)
factorial *= i;
}
return factorial;
}
//calculation of permutation
long long int permute(int n, int r)
{
return fact(n)/fact(n-r);
}
//calculation of combination
long long int combination(int n, int r)
{
return fact(n)/(fact(n-r) * fact(r));
}
int main()
{
int n,r;

std::ifstream infile(\"A1.txt\"); //Input file
std::ofstream outfile(\"B1.txt\"); //Output file

if(!infile.is_open()) //If file is unable to open or file is not present
{
cout<<\"Unable to open file\"<<endl;
return 0;
}

while(infile >> n >> r) //reading file line by line
{
if((n > 0) && (r > 0) && (r <= n)) //checking condition given in problem
{
long long int per = permute(n, r);
long long int comb = combination(n, r);

outfile<<n<<\" \"<<r<<\" \"<<per<<\" \"<<comb<<endl; //writing data to file B1.txt
}
else if( r > n)
{
outfile<<n<<\" \"<<r<<\" \"<<\"r>n\"<<\" \"<<\"error\"<<endl;
}
}
cout<<\"Done !\"<<endl;
//closing both input and output file
infile.close();
outfile.close();
}

Here is out file B1.txt generated

7 2 42 21
8 9 r>n error
10 2 90 45
16 3 3360 560
5 3 60 10
7 5 2520 21
12 4 11880 495
9 7 181440 36
8 6 20160 28
13 9 259459200 715

WRITE ONE C++ PROGRAM THAT SATISFIES THE FOLLOWING: 1. An input file A1.txt is given where each line consists of two integers: n and r. 2. Read each line of the
WRITE ONE C++ PROGRAM THAT SATISFIES THE FOLLOWING: 1. An input file A1.txt is given where each line consists of two integers: n and r. 2. Read each line of the

Get Help Now

Submit a Take Down Notice

Tutor
Tutor: Dr Jack
Most rated tutor on our site