Tuesday, 24 September 2013

C++ - Assignment No. 1

Question 1 :- 1.     Fibonacci Series where upper & lower bound will be user defined.

      #include<iostream>

using namespace std;

int Fibonacci (int);                                     //Function prototype declaration

int main(void)
{
int m,n,i;

cout<<"\nEnter the lower bound : ";
cin>>m;

cout<<"\nEnter the upper bound : ";
cin>>n;
       
        if(m>=n)  
cout<<"\nInvalid Range! Check your boundary values. ";  //Checking range validity

else
for(i=m; i<=n; i++)
cout<<Fibonacci(i)<<"  ";     //Calling the Fibonacci function
cout<<"\n";
return 0;
}

int Fibonacci (int number)
{
if (number==0)                                         //First number is 0
return 0;
if (number==1)                                        //Second number is 1
return 1;
else
return Fibonacci(number-1) + Fibonacci(number-2);  //Formula for number >=2
}

Question 2 :- Write a Program to find GCD, LCM of two numbers using recursion.

#include<iostream>
using namespace std;
int gcd(int, int);
int lcm(int, int);
int main()
{
int x, y;
cout<<"\n Enter the first number : ";
cin>>x;
cout<<"\n Enter the second number : ";
cin>>y;
cout<<"\n The GCD of "<<x<<" and "<<y<<" is : "<<gcd(x,y);
cout<<"\n The LCM of "<<x<<" and "<<y<<" is : "<<lcm(x,y);
cout<<"\n ";
return 0;
}
int gcd(int x, int y)
{
    while (x !=y)
    {
        if (x > y)
        {
            return gcd(x-y, y);
        }
        else
        {
            return gcd(x, y-x);
        }
    }
    return x;
}
int lcm (int x, int y)
{
int result;
result = (x*y)/gcd(x,y);           //Since x*y=lcm*gcd
return result;
}

Question 3 :- Find the smallest and largest no in an array.

#include<iostream>
using namespace std;
int main () 
{

    int values[ 20 ];
    int i,n,small,big; 

    cout<<"\nEnter the number of elements in the array: ";
cin>>n;
    for (i = 0; i < n; i++ ) 
    {
        cout << "\nEnter the value no." << i << ": ";
        cin >> values[i];
    }
     
big=small=values[0];
    for (i = 0; i < n; i++)
    {
        if(values[i]>big) 
        {
            big=values[i];
        }
    }

    for (i = 0; i < n; i++)
    {
        if(values[i]<small) 
        {
            small=values[i];
        }
    }

    cout << "\nThe biggest number is " << big; 
    cout << "\nThe smallest number is " << small ; 
    cout<<"\n";
    return 0;
}

#     
 

No comments:

Post a Comment

Thank you for commenting.