Solution_Assignment4
Solution_Assignment4
Solution:
#include <iostream>
using namespace std;
float temperature(float c)
{
return (c*(9.0/5.0) + 32);
}
int main()
{
float c;
cout << "Enter the temperature in Celsius: ";
cin >> c;
cout << temperature(c) << endl;
return 0;
}
Solution:
#include <iostream>
using namespace std;
int factorial(int n)
{
if(n==1)
return 1;
else
return n*factorial(n-1);
}
int main()
{
int n = 6;
cout << factorial(n) << endl;
return 0;
}
Hint: Write a function int fib(int n) that returns Fn. For example, ifn = 0,
thenfib() should return 0. If n = 1, then it should return 1. For n > 1, it
should return Fn-1 + Fn-2.
Solution:
#include <iostream>
using namespace std;
int fib(int n)
{
if(n==0) return 0;
if(n==1) return 1;
else return fib(n-1)+fib(n-2);
}
int main()
{
int n = 6;
cout << fib(n) << endl;
return 0;
}
4. Use the concept of call by value and call by reference to swap the
values of two variables in a C++ program.
Solution:
//Call by value: does not change values in main
#include <iostream>
using namespace std;
int main()
{
int x = 5;
int y = 4;
swap(x, y);
//cout << x << endl; // does not change value in main
//cout << y << endl;
return 0;
}
//Call by reference
#include <iostream>
using namespace std;
int main()
{
int x = 5;
int y = 4;
swap(x, y);
cout << x << endl;
cout << y << endl;
return 0;
}
5. Write a C++ program using a function to reverse the number 12345 so
that the output prints as 54321.
Solution:
#include <iostream>
using namespace std;
void reverse(int n)
{
int remainder;
int reverse_n = 0; // important to initialize
while(n != 0)
{
remainder = n%10;
reverse_n = reverse_n * 10 + remainder;
n /= 10;
}
int main()
{
reverse (12345);
return 0;
}
Solution:
// rand()/RAND_MAX should return a number in [0, 1]
#include <iostream>
using namespace std;
int main()
{
for (int i=0;i<100;i++)
{
cout << (2.0*(rand()/(float)RAND_MAX - 0.5)) << endl; // needs typecasting
}
}
7. Please write a C++ program to define a function to find the solutions
to x2 – 8x + 15 = 0.
Solution:
#include <iostream>
using namespace std;
void find_roots(int x)
{
if(x*x - 8*x + 15 == 0)
cout << "x = " << x << endl;
}
int main()
{
int i;
for(i=0;i<10;i++)
find_roots(i);
return 0;
}