Multiple initialisation and multiple step instructions in for loop – CSKC
Sign In

Search

Code Learning #CPP#2003    siteicon   siteicon  

Multiple initialisation and multiple step instructions in for loop

A demonstration program to show how multiple initialisation and multiple step instructions in for loop can be used

Learning Objectives

  • Learning to initialise more than one variable and more than one step instructions in the for construct.

Source Code

TC++ #2003

 

Source Code

×

Ask AI About This Code

Default Prompt that is passed along with the code is given below, You can write your own prompt if you so desire.



×

Test CPP

Code Understanding

for(int i=1,j=1;i<=10;i++,j++) 
Here we initialise both i and j indexes as int i=1,j=1;. Between two initialisation instructions we use the comma operator. Similarly the step instructions are two instructions with coma in between as i++,j++ .

sum=sum+i+j;
Here both the index variables i and j have been used to add to sum. This will make first value as 2 and then subsequently 4, 6, 8, 10 are added.

cout<<“Sum of alternate numbers from 2 to 20 = “<<sum<<endl;
This is how we display the final result outside the loop.

Notes

  • This code is for demonstration purpose only. This can easily be done by using a simple one variable construct like –
    for(int i=2;i<=20;i+=2)
    {
    sum=sum+i;
    }


Suggested Filename(s): multiinit-multistep.cpp



Share

Created: 28-Dec-2017 23:48 | Updated: 15-Sep-2018 12:07|