Lecture 5 Loops
Lecture 5 Loops
Week 04 Sp 25
}
Loops
for (start; test; action) //the for loop
{
//Statements to be repeated
}
int main()
{
for (int loop = 1; loop <= 5; loop++)
{
cout << loop << endl;
}
}
The for loop
• Executed a fixed number of times
int main()
{
for (int loop = 0; loop < 10; loop++)
cout << loop << endl;
}
int main()
{
for (int loop = 9; loop >= 0; loop--)
cout << loop << endl;
}
Initialization expression Test expression Increment Expression
false
Test Exp
true
Body of Loop
Increment Exp
The for loop
for (initialization; Test; increment)
statement;
{
statement 1;
statement 2;
statement 3;
}
The for loop
• Blocks
void main(void)
{
for (int numb = 0; numb < 10; numb++)
{
int square = numb * numb;
cout << "Number: " << numb << "Square : " << square <<
endl;
}
}
The for loop
• Variations
• Increment Expression – May perform any operation
for (int i = 10; i >= 0; i--)
Variables defined in for Statements
int i;
for (i = 10; i >= 0; i--)
for(i = 2; i <= 6; i = i + 2)
cout<<i+1<<'\t';
cout i+1
The for loop (C code)
for(i = 2; i != 11; i = i + 3)
printf("%d\t", i + 1);
Print the times table for 8 in one column. To solve this problem you will need to:
int main(void)
{
const float PI = 3.141593;
double radians;
int value;
cout << "Enter a positive value : ";
cin >> value; // 5
int squareValue;
cout << "Enter a positive value for creating a star square
: ";
cin >> squareValue;