Professional Documents
Culture Documents
Graded Lab
Lab 10
Instructions:
Indent your code
Comment your code
Use meaningful variable and function names
Plan your code carefully on a piece of paper before you implement it.
Name of the program should be same as the task name. i.e. the first program should be
Task_4_01.cpp
Upload a zip file on Moodle, zip file should contain all the tasks you have implemented.
Name of zip file should be your UMT-ID e.g. 12003065123.zip
Sample Lab Tasks:
Sample Lab Task (Recursion) :
Sample Output:
Sum of 2 & 3 is 5
Sample Code:
#include <iostream>
using namespace std;
int add(int x,int y){
if(y>=0 && x>=0){
if(y==0)
return x;
else
return 1+add(x,y-1);
}
else
return -1;
}
int main()
{
int x,y;
cout<<"Enter first number ";
cin>>x;
cout<<"Enter second number ";
cin>>y;
int ans=add(x,y);
if(ans==-1)
cout<<"you have entered a negative number ";
else
cout<<"Sum of "<<x<<" and "<<y<<" is "<<ans<<endl;
return 0;
}
Sample Lab Task (Fille Handling ) :
Writing operations on text files are performed in the same way as we operated with cout:
int main () {
ofstream myfile ("example.txt");
if (myfile.is_open())
{
myfile << "This is a line.\n";
myfile << "This is another line.\n";
myfile.close();
}
else cout << "Unable to open file";
return 0;
}
Reading from a file can also be performed in the same way that we did with cin:
int main () {
string line;
ifstream myfile ("example.txt");
if (myfile.is_open())
{
while ( getline (myfile,line) )
{
cout << line << '\n';
}
myfile.close();
}
return 0;
}
Lab Tasks
Task 1:
Write a recursive function which computes sum of first ten numbers. (1 to 10)
i.e. 1+2+3+4+5+6+7+8+9+10=55
Task 2:
Write a recursive function which computes factorial of a number entered by the user.
Task 3:
Write a recursive function power (base, exponent) that when invoked returns base exponent. For example,
power (3, 4) = 3 * 3 * 3 * 3. Assume that exponent is an integer greater than or equal to 1.
base1 = base
Sample Output:
Task 4:
The greatest common divisor of integers x and y is the largest integer that evenly divides both x and y.
Write a recursive function GCD that returns the greatest common divisor of x and y. The GCD of x and y
is defined recursively as follows: If y is equal to 0, then GCD(x, y) is x; otherwise GCD(x, y) is GCD(y, x % y)
where % is the remainder operator.
Sample Output:
Task 5:
Write a program to declare an array of user defined size, initialize it with random numbers and write this
array to a file myArray.txt. Also write code to read that array data from file.
#include <iostream>
#include <fstream>
using namespace std;
int main () {
const int size = 7;
double x[] = {1,2,3,4,5,6,7};