st05-flow_control_2-sol

st05-flow_control_2-sol - CSC 1111 Introduction to...

This preview shows pages 1–7. Sign up to view the full content.

1 CSC 1111 Introduction to Computing using C++ for loop and nested loop, break and continue

This preview has intentionally blurred sections. Sign up to view the full version.

View Full Document
2 for Loop (Exercise) Using a for loop to perform each of these tasks: 1. Print all odd numbers in reverse order from N to 1. (N can be and odd or even number) 1. Print 1, 4, 7, 10, 13, 16, . .., 100 1. Calculate sum of the first N positive integers 1. Print 1, 2, -3, -4, 5, 6, -7, -8, 9, 10, …, -99, -100 1. Calculate 1 2 – 2 2 + 3 2 – 4 2 + … + 99 2 – 100 2
3 // Problem 1: if (N % 2 == 0) // Make N an odd number N--; for (int i = N; i >= 1; i -= 2) cout << i << endl; // Problem 2: for (int i = 1; i <= 100; i += 3) cout << i << endl; // Problem 3: int sum = 0; for (int i = 1; i <= N; i ++) sum += i;

This preview has intentionally blurred sections. Sign up to view the full version.

View Full Document
4 // Problem 4: for (int i = 1; i <= 100; i +=2 ) if (i % 4 == 1) cout << i << " " << i+1 << " "; else cout << -i << " " << -(i+1) << " "; // Problem 5: int sum = 0, multiplier = 1; for (int i = 1; i <= N; i ++) { sum += multiplier * i * i; multiplier *= -1; }
5 Nested Loop What's the output produced by the following segment of code? for (int i = 10; i > 0; i--) for (int j = 0; j < i; j++) cout << i << " " << j << endl; 10 0 10 1 10 2 10 3 10 4 10 8 10 9 9 0 9 1 9 8 8 0 8 1 8 7 7 0 7 1 7 6 . . . 3 0 3 1 3 2 2 0 2 1 1 0

This preview has intentionally blurred sections. Sign up to view the full version.

View Full Document
Nested Loop Print an N by N (1 ≤ N ≤ 19) table containing integers from 1 to N 2 row by row. Each number is right aligned in an invisible cell of 4 characters wide. e.g. When N = 5, the output should look like
This is the end of the preview. Sign up to access the rest of the document.

{[ snackBarMessage ]}

Page1 / 24

st05-flow_control_2-sol - CSC 1111 Introduction to...

This preview shows document pages 1 - 7. Sign up to view the full document.

View Full Document
Ask a homework question - tutors are online