Professional Documents
Culture Documents
lab report 7
lab report 7
Lab-07
Task-1:
Part(a): Write a C++ program to calculate the factorial of
a number using a for loop
Code:
#include<iostream>
using namespace std;
int main()
{
int num,result=1;
cout<<"This program will calculate the factorial"<<endl;
cout<<"Enter the number:";
cin>>num;
if (num==0)
{
result=1;
}
else if (num<0)
{
cout<<"Please Enter 0 or positive integer";
return 0;
}
else
{
for (int i=1;i<=num;i++)
{
result=i*result;
}
}
cout<<result;
return 0;
}
Output Window:
int main()
{
int num,i=1,result=1;
cout<<"Please enter any number"<<endl;
cin>>num;
if (num==0)
{
result=1;
}
else if (num<0)
{
cout<<"Please Enter 0 or positive integer";
return 0;
}
else
{
while(i<=num)
{
result=i*result;
i++;
}
}
cout<<result;
return 0;
}
Output window:
int main()
{
int result=0;
for(int i=1;i<=100;i++)
{
if (i%2==0)
{
result=result+i;
}
}
cout<<"sun of all even number between 1 and 100 is "<<result;
return 0;
}
Output window:
Task-3:
Part(a): Write a C++ program that prompts the user to
enter a number and displays its multiplication table up to
10 by using for loop.
Code:
#include<iostream>
using namespace std;
int main()
{
int num, result;
cout<<"Enter number for table:";
cin>>num;
for(int i=1;i<=10;i++ )
{
result=num*i;
cout<<num<<" * "<<i<<" = "<<result<<endl;
}
return 0;
}
Output Window:
int main()
{
int num,i=1,result;
cout<<"Enter number for table:";
cin>>num;
while(i<=10)
{
result=num*i;
cout<<num<<"*"<<i<<"="<<result<<endl;
i++;
}
return 0;
}
Output Window:
Task-4:
Part(a): Create a C++ program to calculate the power of a
number. Prompt the user for the base and exponent. Use a
loop to calculate the result by multiplying the base by
itself according to the provided exponent. Then, display
the result.
Code:
#include <iostream>
using namespace std;
int main()
{
int num, power,result;
cout<<"Please Enter number:"<<endl;
cin>>num;
result=num;
if(power==0)
{
result=1;
}
else if(power<0)
{
cout<<"This program is invalid for negative numbers"<<endl;
return 0;
}
else
{
}
cout<<"output="<<result;
return 0;
}
Output Window:
int main()
{
int num,i=1,power,result;
cout<<"Please Enter number:"<<endl;
cin>>num;
result=num;
if(power==0)
{
result=1;
}
else if(power<0)
{
cout<<"This program is invalid for negative numbers"<<endl;
return 0;
}
else
{
while(i<power)
{
result=num*result;
i++;
}
}
cout<<"output="<<result;
return 0;
}
Output Window:
Conclusion:
In this lab we learned following things,
For loops
While loops
Structure of Do while loops.
Problem solving with loops.