100 likes | 230 Views
C++ programming I Lab#5. Functions Instructor: Eng. Ruba A. Salamah Tuseday: 10/12/2010. Exercise #1: a) Write a function that computes the sum of digits in an integer. Use the following function header: i nt SumDigits ( long n)
E N D
C++ programming ILab#5 Functions Instructor: Eng. Ruba A. Salamah Tuseday: 10/12/2010
Exercise #1: a) Write a function that computes the sum of digits in an integer. Use the following function header: intSumDigits( long n) b) Write a program that reads an integer and prints the sum of its digits using the function in (a).
EX1: solution #include <iostream> using namespace std; int SumDigits(long n) {int sum=0; while(n!=0) {sum += n% 10; n=n/10;} return sum; } int main() {long x; cout<<"enter an integer"; cin>>x; cout<< "the sum of your integer digits is: "<<SumDigits(x); system("pause"); return 0; }
Exercise #7: The value for π (PI) can be determined by the series equation write an interactive program that asks the user how many terms of series equation to use in approximating PI. Then calculate and display the approximation. Here is a sample run:
EX7 : solution #include <iostream> #include <cmath> using namespace std; int main() { double sum = 0; double item ; cout<<"PI Approximation Program\nHow many terms of the series should be included?\n"; cin>>item; for (int i = 1; i <= item; i+=2) sum=sum+1.0/(2*i-1)-1.0/(2*i+1); cout<<"Approximation value of pi is "<<4*sum<<endl; system("pause"); return 0; }
18_a #include <iostream> #include <iomanip> using namespace std; int main() { for(int i=1;i<=6;i++) { for(int j=1;j<=i;j++) cout<<j; cout<<endl; } system("pause"); return 0; }
18_b include <iostream> #include <iomanip> using namespace std; int main() { for(int i=6;i>=1;i--) { for(int j=1;j<=i;j++) cout<<j; cout<<endl; } system("pause"); return 0; }
18_c #include <iostream> #include <iomanip> using namespace std; int main() { for(int i=1;i<=6;i++) {//cout<<setw(7-i); For(int s=1;s<=6-I;s++) Cout<<“ “; for(int j=1;j<=i;j++) cout<<j; cout<<endl; } system("pause"); return 0; }