Lab 06@cs 121
Lab 06@cs 121
Practice Task:
Write a program to print and sum 1 – 10 numbers.
Solution
FOR LOOP WHILE LOOP DO-WHILE LOOP
1. #include <iostream> 1. #include <iostream> 1. #include <iostream>
2. using namespace std; 2. using namespace std; 2. using namespace std;
3. int main() 3. int main(){ 3. int main(){
4. { 4. int i=1; 4. int i=1;
5. int i; 5. int sum = 0; 5. int sum = 0;
6. int sum = 0; 6. while(i<=10) 6. do
7. for (i = 1; i <= 10; i++) 7. { 7. {
8. { 8. cout<<i<<" "; 8. cout<<i<<" ";
9. cout << i << " "; 9. sum = sum + I; 9. sum = sum + I;
10. sum = sum + i; 10. i++; 10. i++;
11. } 11. } 11. }
12. cout << endl; 12. cout<<endl<<sum; 12. while(i<=10);
13. cout << endl << sum; 13. 13. cout<<endl<<sum;
14. 14. return 0; 14.
15. return 0; 15. 15. return 0;
16. } 16. } 16. }
Page 1 of 4
CS121 Lab06 CS@SIBAU
Exercises
Refreshing Task01 (PRE/POST INCREMENT)
Code is provided below, perform following tasks:
a) Is there any syntax error in code? (Mention error names and line number).
b) Is there any logical error in code? (Mention error names and line number).
c) Resolve both errors on paper and observe the output.
d) Execute code on Machine/System and match the output, you noted/observed.
1. cout<<x<<", "<<y<<endl;
2.
3. int x, y;
4. cout<<x<<", "<<y<<endl;
5.
6. x = 5, y = 9;
7. cout<<x<<", "<<y<<endl;
8.
9. cout<<x++<<", "<<y<<endl;
10. cout<<"x"<<", "<<y<<endl;
11. cout<<++x<<", "<<y++<<endl;
12.
13. ++x;
14. y = 6;
15. cout<<++x<<", "<<y++<<endl;
16. cout<<x++<<", "<<++y<<endl;
17.
18. x = x + 1 // x++ or x += 1
19. y += 2 // y = y + 2
20.
21. cout<<++x<<", "<<y++<<endl;
22. cout<<x<<", "<<y<<endl;
1. cout<<x<<", "<<y<<endl;
2.
3. int x, y;
4. cout<<x<<", "<<y<<endl;
5.
Page 2 of 4
CS121 Lab06 CS@SIBAU
6. x = 5, y = 9;
7. cout<<x<<", "<<y<<endl;
8.
9. cout<<x--<<", "<<y<<endl;
10. cout<<--y<<", "<<--y<<endl;
11. cout<<--x<<", "<<y--<<endl;
12.
13. --x;
14. y = 6;
15. cout<<y--<<", "<<x<<endl;
16. cout<<++y<<", "<<--y<<endl;
17.
18. x = x - 1 // x-- or x -= 1
19. y -= 2 // y = y - 2
20.
21. cout<<y++<<", "<<"x"<<endl;
22. cout<<x<<", "<<y<<endl;
c) While testing on last two inputs, it may work abnormally. Now modify above
program so that it should work t time where t is difference between
start/end.
d) How for/while/do-while loop behaves?
Task03
Write a program to output the N terms of HARMONIC series and their SUM.
Page 3 of 4
CS121 Lab06 CS@SIBAU
Input: 5
Output: 1/1 + 1/2 + 1/3 + 1/4 + 1/5
Total Sum is: 2.28333
Task04 (CONTINUE/EXIT)
Write a program to ask user NAME and print “Welcome Dear NAME”, then ask user
whether user wants to continue or exit (y continue, e exit). Print appropriate
message to tell user how to EXIT/CONTINUE.
Note: In following each task, you have to ask user whether CONTINUE/EXIT, if
continue then program should RUN AGAIN otherwise TERMINATE.
Note: PRIME numbers are those which are perfectly divided by 1 and itself.
Input N = 5
Output:
1
1 2
1 2 3
1 2 3 4
1 2 3 4 5
A
A B
A B C
A B C D
A B C D E
Page 4 of 4