كلية الهندسة/جامعة النهرين
قسم هندسة الطب الحياتي
Loop Statement
Lec-1
1st year
2nd Semester
Asst. Lec. Zaid Mustafa
Asst. Lec. Ahmed Lateef
1
Objectives
• Learn the student the use of for loop statement.
• Write several C++ program which use of for loop statements.
For Loop Statement
For Loop Statement
• In C++, a for loop is a control flow statement that allows you to repeatedly execute a block of
code a specified number of times. The syntax of a for loop is as follows:
For Loop Statement
• Example 1:
for ( i = 0; i < 10; i ++ ) cout << i; Output: 0123456789
• Example 2:
for ( i = 0; i < 10; i += 2 ) cout << i; Output: even numbers only 02468
• Example 3:
for ( i = 1; i < 10; i += 2 ) cout << i; Output: odd numbers only 13579
Procedure
Procedure
Example 1: Write C++ program to sum the numbers between 1 and 100 using For statement?
Procedure
Example 2: Write C++ program using For statement to find the factorial of n?
n! = n * n-1 * n-2 * n-3 * … * 2 * 1
Procedure
Example 3: Write C++ program to read 10 integer numbers, and find the sum of positive
numbers only:
Procedure
Example 4: Write C++ program to print the following series: 1, 2, 4, 8, 16, 32, 64
More about For Statement
• We can use more than one control with for statement, as follow:
for ( int m = 1, int n = 8 ; m < n ; m ++ , n -- )
• We can create infinite loop, as follow:
for ( ; ; )
Nested Loops
Nested Loops
• We can put loops one inside another to solve a certain programming problems.
Loops may be nested as follows:
Nested Loops
Example 1: Write C++ program to evaluate the following series:
Nested Loops
Example 2: Write C++ program to read a line using for loop.
Discussion
Discussion
1. Write C++ program to read 7 marks, if pass in all marks (>=50) print “pass”
otherwise print “fail”.
2. Write C++ program to add the numbers between 1 and 100 and find its average.
3. Write C++ program to find e from the following series:
e = 1 + x + (x² / 2!) + (x³ / 3!) + … (xª / a!)
4. Write C++ program to read 10 marks, suppose the student pass if all marks
greater than or equal 50, and the average greater than or equal 50. If student
fails in some lessons then print the number of these lessons, if student fails in
average then print “fail in average”.