Page 56 - Modular_V1.1_Flipbook
P. 56
statements is the statement block, that is to be repeatedly executed until the provided
condition becomes false.
Tech
Funda Do not put a semicolon after the right parenthesis. If you do, the for
loop will think that there are no statements to execute. It will continue
looping doing nothing each time, until the test expression becomes
false.
Program 1: To print first 10 natural numbers.
#include<iostream.h>
#include<conio.h>
Output:
void main(){
1 2 3 4 5 6 7 8 9 10
int counter;
clrscr();
for (counter = 1; counter <= 10; counter++)
{
cout<<counter << “ “;
}
getch();
}
Using Comma (,) Operator with for Loop
C++ allows you to combine two expressions using the comma operator. When two or more
variables are used to control the loop, they are separated by comma operator. Comma operator
allows more than one initialization, more than one condition and more than one counter variable.
Program 2: To use the comma operator in for loop.
#include<iostream.h>
#include<conio.h> Output:
void main(){ 1 20 3 18 5 16 7 14 9 12 11 10 13 8 15 6 17 4 19 2
int num1, num2;
for (num1 = 1, num2 = 20; num1 <= 10, num2 >= 1; num1+=2, num2 = num2-2){
cout<< num1 << “ “ << num2 << “ “;
}
getch();
}
54 Touchpad MODULAR (Version 1.1)-X

