Programming For Problem Solving: Experiment - 4
Programming For Problem Solving: Experiment - 4
EXPERIMENT - 4
Task 1: For given algorithm write C++ code using for loop and while loop.
1. Start
2. Print “How many numbers”
3. Input N
S=0: For given algorithm write C++ code using for loop and while loop.
1. Start
2. Print “How many numbers”
3. Input N
4. S=0
5. C=1
6. Print “Enter the number”
7. Input A
8. S=S+A
9. C=C+1
10.If C<=N then GOTO Step 6
11.Avg=S/N
12.Print “Average is “ Avg
13.Stop
PROGRAM:
#include <iostream>
using namespace std;
int main()
{
int n;
cout<<"How many numbers ";
cin>>n;
float S = 0;
int C = 1;
float A;
while(C<=n){
cout<<"Enter the number ";
cin>>A;
S = S + A;
C = C + 1;
}
float avg = S/(float)n;
cout<<"Average is "<<avg;
return 0;
}
int main() {
int n, t1 = 0, t2 = 1, nextTerm = 0;
if(i == 1) {
cout << t1 << ", ";
continue;
}
if(i == 2) {
cout << t2 << ", ";
continue;
}
nextTerm = t1 + t2;
t1 = t2;
t2 = nextTerm;
return 0;
}
Task 5: Write a C++ program and draw flowchart to calculate the sum of
square of digits of a number given by the user. (while loop)
PROGRAM:
#include<iostream>
using namespace std;
int main()
{
int num, rem, sq, sum=0;
cout<<"Enter a Number: ";
cin>>num;
while(num>0)
{
rem = num%10;
if(rem==0)
sq = 1;
else
sq = rem*rem;
sum = sum + sq;
num = num/10;
}
cout<<"\nSum of squares of all digits = "<<sum;
cout<<endl;
return 0;
}
Task 6: Write a C++ program to print the sum of the following series up to
n terms where n is given by the user.
1+x+x2/2! + x3/3! +… n terms
PROGRAM:
#include <iostream>
using namespace std;
int main()
{
float x, sum, no_row;
int i, n;
cout << "\n\n Display the sum of the series [ 1+x+x^2/2!+x^3/3!+....]\n";
cout << " Input the value of x: ";
cin >> x;
cout << " Input number of terms: ";
cin >> n;
sum = 1;
no_row = 1;
for (i = 1; i < n; i++)
{
no_row = no_row * x / (float)i;
sum = sum + no_row;
}
cout << " The sum is : " << sum << endl;
return 0;
}