For statement

Hello!

Now that we’ve talked about loops it is time to bring up the for statement. The for statement let’s you repeat a block of code over and over again and it is usually used to create loops that must be executed a specified number of times.

Syntax:

for ( init-expression ; cond-expression ; loop-expression){

//your code

}

Syntax Name When Executed Description
init-expression

 

Before any other element of the for statement, init-expression is executed only once. Control then passes to cond-expression. Often used to initialize loop indices. It can contain expressions or declarations.
cond-expression

 

Before execution of each iteration of statement, including the first iteration. statement is executed only if cond-expression evaluates to true (nonzero). An expression that evaluates to an integral type or a class type that has an unambiguous conversion to an integral type. Normally used to test for loop-termination criteria.
loop-expression

 

At the end of each iteration of statement. After loop-expression is executed, cond-expression is evaluated. Normally used to increment or decrement loop indices.

For example:

for (int i = 1; i<=5 ; i++)

cout << i;

This will output : 12345

Loop expression can be incremented ,decremented or modified in other ways too

Examples:

  • for (int i = 1; i<=20 ;i = i+2)
  • for (int i = 1; i<=20 ;i*i)
  • for (int i = 1; i<=20 ;i = i*3)

and so on!

I hope that now you have a basic understanding of the for statement in C++ 🙂

Keep on coding! 😉

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s