Vous êtes sur la page 1sur 6

CSCP2034-DATA STRUCTURED AND ALGORITHMS

FIRST ASSIGNMENT

ASSIGNMENT STARTS HERE


Q-1: Write a program to display sum of all natural numbers up to given
one using recursion. If user enters 5,the output will be

CODE:
#include<iostream>
using namespace std;
int sum(int );
int main()
{
int i;
cout<<"Enter any Number : ";
cin>>i;
cout<< Sum will be equal to "<<
for(int j=1;j<=i;j++)
{
Talha Sadiq

G1F14BSCS0083

Page 1 of 6

CSCP2034-DATA STRUCTURED AND ALGORITHMS


FIRST ASSIGNMENT

Cout<<j;
if(j != i){
cout << " + ";
}
}
cout<<" = ";
cout<<sum(i);
return 0;
}
int sum(int n)
{
if(n>0)
{
return n+sum(n-1);
}else{
return 0;
}
Talha Sadiq

G1F14BSCS0083

Page 2 of 6

CSCP2034-DATA STRUCTURED AND ALGORITHMS


FIRST ASSIGNMENT

}
OUTPUT:
Sum will be equal to 1 + 2 + 3 + 4 + 5 = 15

Q-2: Write a Program to convert either binary number to decimal OR


decimal to binary in classical way. Dont use C++ built-in functions.

CODE:
#include<iostream>
using namespace std;
int decimal_binary(int );
int binary_decimal(int );
int main()
{
int a;
char c;
cout<<"D or d to Convert Binary to
Decimal .... "<<endl;

Talha Sadiq

G1F14BSCS0083

Page 3 of 6

CSCP2034-DATA STRUCTURED AND ALGORITHMS


FIRST ASSIGNMENT

cout<<"B or b to Convert Decimal to


Binary.... "<<endl;
cin>>c;
if(c=='D' || c=='d')
{
cout<<"Enter Binary Number

";

cin>>a;
cout<<endl<<a<<" IN Binary Number. =
"<<binary_decimal(a)<<" in Decimal ";
}
else if(c=='B' || c=='b')
{
cout<<"Enter Decimal Number

";

cin>>a;
cout<<endl<<a<<" in Decimal Number.

"<<decimal_binary(a)<<" in Binary";
}

Talha Sadiq

G1F14BSCS0083

Page 4 of 6

CSCP2034-DATA STRUCTURED AND ALGORITHMS


FIRST ASSIGNMENT

return 0;
}
int binary_decimal(int x)
{

int rem,decimal=0,i=1;
while(x!=0)
{
rem = x % 10;
decimal = decimal + rem * i;
x = x / 10;
i = i * 2;
}
return decimal;

}
int decimal_binary(int x)
{

int rem,binary=0,i=1;
while(x!=0)
{

Talha Sadiq

G1F14BSCS0083

Page 5 of 6

CSCP2034-DATA STRUCTURED AND ALGORITHMS


FIRST ASSIGNMENT

rem=x%2;
x/=2;
binary+=rem*i;
i*=10;
}
return binary;
}
OUTPUT:
D or d to Convert Binary to Decimal ....
B or b to Convert Decimal to Binary....
D
Enter binary number : 110111
110111 in binary = 55 in decimal

ASSIGNMENT ENDS HERE

Talha Sadiq

G1F14BSCS0083

Page 6 of 6

Vous aimerez peut-être aussi