Loops 2
Muhammad Magdi
For Loops
for ( INITIALIZATION; CONDITION; ASSIGNMENT ) {
BODY
}
INITIALIZATION: What to do before starting the loop?
CONDITION: What is the condition to continue looping?
ASSIGNMENT: What to do after each iteration?
1
2
3
4
10 Hellos
Print Hello 10 times
#include <iostream>
using namespace std;
int main() {
for(int i = 0; i < 10; i++){
cout << "Hello" << endl;
}
return 0;
}
Zero to Nine
Print the numbers 0 to 9
#include <iostream>
using namespace std;
int main() {
for(int i = 0; i < 10; i++){
cout << i << endl;
}
return 0;
}
Zero to n
Print the numbers 0 to n
#include <iostream>
using namespace std;
int main() {
int n;
cin >> n;
for(int i = 0; i < n; i++){
cout << i << endl;
}
return 0;
}
URI 1067 - Odd Numbers
[Problem Summary]
Given x print all the odd numbers from 1 to x -including x-
URI 1067 - Odd Numbers
[Solution #1]
#include <iostream>
using namespace std;
int main() {
int x;
cin >> x;
for (int i = 1; i <= x; i++) {
if (i%2 != 0) {
cout << i << endl;
}
}
return 0;
}
URI 1067 - Odd Numbers
[Solution #2]
#include <iostream>
using namespace std;
int main() {
int x;
cin >> x;
for (int i = 1; i <= x; i = i + 2) {
cout << i << endl;
}
return 0;
}
URI 1074 - Even or Odd
[Problem Summary]
- Given N
- Given N numbers
- Classify each of these N Numbers into:
- EVEN POSITIVE
- EVEN NEGATIVE
- ODD POSITIVE
- ODD NEGATIVE
- NULL
URI 1074 - Even or Odd
[Solution]
#include <iostream>
using namespace std;
int main() {
int n;
cin >> n;
for(int i = 0; i < n; i++) {
int x;
cin >> x;
if (x%2 == 0 && x > 0) {
cout << "EVEN POSITIVE" << endl;
} else if (x%2 == 0 && x < 0) {
cout << "EVEN NEGATIVE" << endl;
} else if (x%2 != 0 && x > 0) {
cout << "ODD POSITIVE" << endl;
} else if (x%2 != 0 && x < 0) {
cout << "ODD NEGATIVE" << endl;
} else {
cout << "NULL" << endl;
}
}
return 0;
}
Assignment
Thanks
Content
- For Loop Structure
- 10 Hellos
- Zero to Nine
- Zero to n
- URI 1067 - Odd Numbers
- URI 1074 - Even or Odd
Loops 2
By Muhammad Magdi
Loops 2
- 185