Professional Documents
Culture Documents
c++ session 4
c++ session 4
Loops
Go through a cycle until a condition is not met
For Statement - Syntax
For (initiation;Boolean_Expression; Update)
examples
for (int num = 20; num<12; num--)
Cout<<num <<“ Dollars on the table, \n” ;
for (int n = 0; n > - 21; n -= 7)
Cout<<“n is now equal to ”<<n<<endl;
for(double sizes = 0.3; sizes<=5; sizes +=0.14)
cout<< “Size now is equal to ”<<sizes<<endl;
Pitfall, do not terminate with a semi colon
for (int n = 0; n > - 21; n -= 7);
Example
#include <iostream> Answer
using namespace std;
The value of a is 1
int main() The value of a is 2
{ The value of a is 3
float a =1; The value of a is 4
for(a; a<10;a++)
The value of a is 5
{
cout<<"The value of a is "<<a<<endl; The value of a is 6
The value of a is 7
} The value of a is 8
The value of a is 9
return 0;
}
Terminating the loop with break
#include <iostream>
using namespace std;
The value of a is 1
int main()
{ The value of a is 2
float a =1;
for(a; a<10;a++)
The value of a is 3
{ The value of a is 4
cout<<"The value of a is "<<a<<endl;
The value of a is 5
if(a==5)
break;
return 0;
Terminating the loop with break
#include <iostream>
using namespace std;
The value of a is 1
int main()
{
float a =1;
for(a; a<10;a++)
{
cout<<"The value of a is "<<a<<endl;
break;
return 0;
}
Another example
#include <iostream>
cout<<"The sum of the
using namespace std;
numbers from 1 to 10 is "
<<sum;
int main()
{ return 0;
int sum = 0; }
for(int n= 1; n<=10; n++)
sum += n;
return 0;
For Loop
#include <iostream>
using namespace std; 1
2
int main() 3
{ 4
5
for (int num = 1;num<=7;num++) 6
cout<<num<<endl; 7
return 0;
}
For loop with multiple statement body
• Syntax
for (initialization; BooleanExpression; update)
{
statement1;
statement2;
………………
statementn;
}
Factorial of a number
#include <iostream>
using namespace std;
int main()
{
int num, factorial=1;
cout<<"Please enter a number: ";
cin>>num;
cout<<"the factorial of "<<num <<" is ";
int main()
{
float go;
string aman ="Bongobar";
for (go=3;go<aman.length();go++)
cout<<go<<", ";
return 0;
}
goto
A goto statement provides an unconditional
jump from the goto to a labelled statement in
the same function.
Use of goto statement is highly discouraged
because it makes difficult to trace the control
flow of a program, making the program hard to
understand and hard to modify.
Any program that uses a goto can be rewritten
so that it doesn't need the goto.
// goto loop example
#include <iostream>
using namespace std;
int main ()
{ int n=10; //Should be declared before mylabel
mylabel: //if not you hit an infinite loop
cout << n << ", ";
n--;
if (n>0) goto mylabel;
cout << endl<<“now out of go to !\n";
return 0; }
#include <iostream>
if (n<0)
using namespace std; goto rotation;
cout<<"This is the end";
int main () return 0;
}
{
int n = -8;
rotation:
cout<<n<<",";
n++;