1
|
Write a program using function which accept two integers as an argument and return its sum. Call this function from main( ) and print the results in main( ).
#include<iostream.h>
#include<conio.h>
int sum(int, int);
int main()
{
int x,y,s;
cout<<"Enter first number : ";
cin>>x;
cout<<"Enter second number : ";
cin>>y;
s=sum(x,y);
cout<<"The sum is : "<<s;
getch();
return 0;
}
int sum(int a, int b)
{
int total;
total=a+b;
return total;
}
|
2
|
Write a function to calculate the factorial value of any integer as an argument. Call this function from main( ) and print the results in main( ).
#include<iostream.h>
#include<conio.h>
int factorial(int);
int main()
{
int x,f;
cout<<"Enter number : ";
cin>>x;
f=factorial(x);
cout<<"The factorial is :"<<f;
getch();
return 0;
}
int factorial(int a)
{
int fact=1;
while(a>=1)
{
fact=fact*a;
a--;
}
return fact;
}
|
3
|
Write a function that receives two numbers as an argument and display all prime numbers between these two numbers. Call this function from main( ).
#include<iostream.h>
#include<conio.h>
void showprime(int, int);
int main()
{
int x,y;
cout<<"Enter first number : ";
cin>>x;
cout<<"Enter second number : ";
cin>>y;
showprime(x,y);
getch();
return 0;
}
void showprime(int a, int b)
{
int flag;
for(int i=a+1;i<=b;i++)
{
flag=0;
for(int j=2;j<i;j++)
{
if(i%j==0)
{
flag=1;
break;
}
}
if(flag==0 && i>1)
cout<<i<<endl;
}
}
|
4
|
Raising a number to a power p is the same as multiplying n by itself p times. Write a function called power that takes two arguments, a double value for n and an int value for p, and return the result as double value. Use default argument of 2 for p, so that if this argument is omitted the number will be squared. Write the main function that gets value from the user to test power function.
#include<iostream.h>
#include<conio.h>
double power(double,int=2);
int main()
{
int p;
double n,r;
cout<<"Enter number : ";
cin>>n;
cout<<"Enter exponent : ";
cin>>p;
r=power(n,p);
cout<<"Result is "<<r;
r=power(n);
cout<<"\nResult without passing exponent is "<<r;
getch();
return 0;
}
double power(double a, int b)
{
double x=1;
for(int i=1;i<=b;i++)
x=x*a;
return x;
}
|
5
|
Write a function called zero_small() that has two integer arguments being passed by reference and sets the smaller of the two numbers to 0. Write the main program to access the function.
#include<iostream.h>
#include<conio.h>
void zero_small(int &,int &);
int main()
{
int x,y;
cout<<"Enter first number : ";
cin>>x;
cout<<"Enter second number : ";
cin>>y;
zero_small(x,y);
cout<<"First number is : "<<x;
cout<<"\nSecond number is : "<<y;
getch();
return 0;
}
void zero_small(int &a, int &b)
{
if(a<b)
a=0;
else
b=0;
}
|
No comments:
Post a Comment