Assignment 1
Assignment 1
Output
3. WAP to implement three different ways to
swap two variables without using a third
variable.
Code
#include<iostream>
using namespace std;
void way1(int n,int m){
n=n*m;
m=n/m;
n=n/m;
cout<<"now the value of first number
is:"<<n<<"\n";
cout<<"now the value of second number
is:"<<m<<"\n";
}
void way2(int n,int m){
n=n+m;
m=n-m;
n=n-m;
cout<<"now the value of first number
is:"<<n<<"\n";
cout<<"now the value of second number
is:"<<m<<"\n";
}
void way3(int n,int m){
n=n^m;
m=n^m;
n=n^m;
cout<<"now the value of first number
is:"<<n<<"\n";
cout<<"now the value of second number
is:"<<m<<"\n";
}
int main(){
cout<<"enter the first number:";
int n,m;
cin>>n;
cout<<"enter the second number:";
cin>>m;
cout<<"--way1--\n\n";
way1(n,m);
cout<<"\n\n--way2--\n\n";
way2(n,m);
cout<<"\n\n--way3--\n\n";
way3(n,m);}
Output
4.WAP to implement the following programs using
recursion.
a. Factorial
code
#include<iostream>
using namespace std;
int fac(int n){
if(n==1||n==0)return 1;
return n*fac(n-1);}
int main(){
int n;
cout<<"enter the number:";
cin>>n;
cout<<"factorial of "<<n<<" is:"<<fac(n);}
Output
b.fibonacci
code
#include<iostream>
using namespace std;
int fib(int n){
if(n==1||n==2)return 1;
return fib(n-1)+fib(n-2);
}
int main(){
cout<<"enter no. of terms:";
int n;
cin>>n;
for(int i=1;i<=n;i++){
cout<<fib(i)<<" ";}}
Output
c. Greatest Common Divisor
code
#include<bits/stdc++.h>
using namespace std;
int gcd(int p,int q,int k){
if(p%k==0&&q%k==0)return k;
return gcd(p,q,k-1);
}
int main(){
int p,q;
cout<<"enter the numbers:";
cin>>p>>q;
int k=min(p,q);
cout<<"the gcd is: "<<gcd(p,q,k);
}
Output
d. linear search
code
#include<iostream>
using namespace std;
int ls(int a[],int i,int x){
if(i<0)return -1;
if(a[i]==x)return i;
return ls(a,i-1,x);
}
int main(){
cout<<"enter number of terms in array:";
int n;
cin>>n;
int a[n];
cout<<"enter elements of array:";
for(int i=0;i<n;i++){
cin>>a[i];
}
cout<<"enter number to be searched:";
int x;
cin>>x;
int ind=ls(a,n-1,x);
if(ind==-1)cout<<"not present\n";
else cout<<"the index of given number
is:"<<ind;
}
Output
e. binary search
code
#include <bits/stdc++.h>
using namespace std;
return -1;
}
int main() {
int n, x;
cout << "Enter the number of elements in the
array: ";
cin >> n;
int arr[n];
cout << "Enter the elements of the array in
sorted order: ";
for (int i = 0; i < n; i++) {
cin >> arr[i];
}
f. Tower of hanoi
code
#include <iostream>
using namespace std;
Output