For Loop and Nested Loop
For Loop and Nested Loop
Lab Manual
Instructor: Waqar Ashiq
Lecturer, Software Engineering Department
Email: [email protected]
for Loop:
• Loop: a control structure that causes a statement or statements to repeat
• Useful for counter-controlled loop
• General Format:
for(initialization; test; update)
statement; // or block in { }
• No semicolon after the update expression or after the )
for Loop - Mechanics
for(initialization; test; update)
statement; // or block in { }
1) Perform initialization
2) Evaluate test expression
– If true, execute statement
– If false, terminate loop execution
3) Execute update, then re-evaluate test expression
Programming Fundamentals
Example:
Code:
int count;
for (count = 1; count <= 5; count++)
cout << "Hello" << endl;
Execution Process:
Flow Chart:
Programming Fundamentals
cout << "Enter " << num << " elements one by one\n\n";
for(int i = 1; i <= num; i++)
{
cout<<"Enter the number: "<<i<<" :";
cin >> y;
total =total+ y;
}
average = total/ num;
cout << "\nThe average of the entered input numbers is = " << average;
return 0;
}
Programming Fundamentals
Example 2: Printing and counting odd and even numbers using for Loop
#include<iostream>
using namespace std;
int main()
{
int i,n,even=0,odd=0;
cout<<"\nEnter the Ending value:";
cin>>n;
cout<<"\nEven numbers:";
for(i=0;i<=n;i++)
{
if(i%2==0)
{
cout<<"\n"<<i;
even++;
}
}
cout<<"\nOdd numbers:";
for(i=1;i<=n;i++)
{
if(i%2==1)
{
cout<<"\n"<<i;
odd++;
}
Programming Fundamentals
}
cout<<"\nTotal even numbers:"<<even;
cout<<"\nTotal odd numbers:"<<odd;
return 0;
}
#include <iostream>
using namespace std;
int main() {
int weeks = 1, days_in_week = 7;
int main() {
int rows;
int main() {
int rows;
cout << "Enter number of rows: ";
cin >> rows;
int main() {
int rows;
cout << "Enter number of rows: ";
cin >> rows;
for(int i = rows; i >= 1; --i) {
for(int j = 1; j <= i; ++j) {
cout << "* ";
}
cout << endl;
}
return 0;
}
Programming Fundamentals
int main() {
int rows;
return 0;
}