II-106 Programming Concepts
15. Explain the different ways of specifying the 'for' loop.
Ans: The 'for' loop can be used in different ways. Table 6.1 shows the different ways of using the for loop.
Table 6.1 Different ways to use the for loop
Syntax Output Remarks
(1) for ( ; ; ) Infinite loop No arguments
(2) for (a=0; a<=20; ) Infinite loop 'a' is neither incremented nor decremented.
(3) for (a=0; a<=10; a++)
printf ("%d",a);
Displays value
from 0 to 10
'a' is incremented from 0 to 10. Curly braces are not
necessary. Default scope of 'for' loop is one
statement after
'for' loop.
(4) for (a=10; a>=0; a--) Displays value
from 10 to 0
'a' is decremented from 10 to 0.
16. Write a program to display the square of first five numbers by using 'for' loop.
Ans:
void main()
{
int i;
clrscr();
for (i=1;i<=5;i++)
printf ("
umber: %5d its square: %8d",i,i*i);
}
OUTPUT:
Number: 1 its square: 1
Number: 2 its square: 4
Number: 3 its square: 9
Number: 4 its square: 16
Number: 5 its square: 25
Explanation:
1. The value of i is initialized to 1 when the program execution begins.
2. The condition i<=5 is specified and tested in each iteration. Initially, the condition is true since the
value of i is 1. The statements following the 'for' loop executes.
3. Upon execution of printf() statement, compiler sends control back to the 'for' loop where
the value of i is incremented by one. This is repeated till the value of i is less than or equal to 5.
4. The new updated value of i if exceeds 5, the control exits from the loop.
5. The printf() statement executes as long as the value of i reaches to 5.
17. What is nested 'for' loops?
Ans: Nested means loops within the loop. In 'nested for' loops, one or more 'for' state-
ments are included in the body of the loop. In other words, C allows multiple 'for' loops in nested
forms. The numbers of iterations in this type of structure will be equal to number of iteration in the outer
loop multiply by number of iterations in the inner loop.
M06_ITL-ESL4791_02_SE_C06.indd 106 12/22/2012 5:02:20 PM