CP Lab 8 Ex 1 - 5 (Function Overloading & Recursion)
CP Lab 8 Ex 1 - 5 (Function Overloading & Recursion)
Lab
Semester BS (CS) – 01
Yahya Faisal
02-134211-006
Lab 8 (Function Overloading &
Recursion)
Exercise 1
1. Write a C++ program for calculating grades of students by using int main() and one
user defined function Calgrades().
#include<iostream>
using namespace std;
char calgrades(int, int);
char calgrades(int, int, int);
int main()
{
int n;
cout << "Enter number of subjects: ";
cin >> n;
if (n == 3) {
int a, b, c;
cout << "Enter marks respectively: ";
cin >> a >> b >> c;
char r = calgrades(a, b, c);
cout << "GRADE: " << r;
}
if (n == 2)
{
int a, b;
cout << "Enter marks respectively: ";
cin >> a >> b;
char r = calgrades(a, b);
cout << "GRADE: " << r;
}
cout << endl;
system("pause");
}
char calgrades(int x, int y)
{
int temp = x + y;
int sum = temp / 2;
if (sum >= 50 && sum <= 64)
return 'D';
if (sum >= 65 && sum <= 74)
return 'C';
if (sum >= 75 && sum <= 86)
return 'B';
if (sum >= 87 && sum <= 100)
return 'A';
else
return 'F';
}
char calgrades(int x, int y, int z)
{
3. Write a C++ recursive function that prints the numbers between 1 to n in a reverse
order.
#include <iostream>
using namespace std;
int recur(int x)
{
cout << x << " ";
if (x <= 1)
return 1;
else
return recur(x - 1);
}
int main()
{
int n;
cout << "Enter number to generate series in reverse order: ";
cin >> n;
recur(n);
cout << endl;
system("pause");
return 0;
}
#include<iostream>
using namespace std;
int fib(int x)
{
if (x == 1 || x == 0)
{
return x;
}
else
return fib(x - 1) + fib(x - 2);
}
int main()
{
int n;
cout << "Enter a Positive Number : ";
cin >> n;
cout << "Fibonacci series is :";
for (int i = 0; i <= n; i++){
cout << " " << fib(i);
}
cout << endl;
system("pause");
}