Loops in C Language
Loops in C Language
Loops in C Language
main()
{
int a;
printf("This program prints the count from 1 to 10.\n");
for ( a=1 ; a<=10 ; a++)
printf("%d\n",a);
getch();
}
For Loop Example 1 Output
In this program, first printf()
function is only printing a fixed
string for title purpose only
The second printf() under
the for, is printing a variable
(a) which is of integer type
(%d) and is incremented in
each loop iteration
There are no curly braces {}
under for-loop because we
only have one statement in the
for-loop
For Loop Task 1
In the above example we initialized the loop counter
(a=1) and gave a fixed value to (a<=10) to stop the
counter after certain number of times
Now modify this program to take inputs from user to
initialize the counter and set the test condition value,
both
Hints:
Use two scanf() statements separately
Declare another variable to input the value of test condition
For Loop Example 2
#include <stdio.h>
#include <conio.h>
main()
{
int a,b;
printf("This program prints the table of 5.\n \n");
getch();
}
For Loop Example 2 Output
This program increments the
value of a in each iteration
(repetition) and multiplies it
with a fixed number 5
%3d in printf() is similar to
%d but with a difference that
the variable printed with
%3d is printed in 3 spaces.
The number will be right
aligned in these three
spaces
For Loop Task 2
Modify the table program so that user must input a
number for which the table should be generated and
the maximum value of counter (table multiplier)
Suppose you want to run the table of 4 till 50, you can
be able to give these inputs on run-time, then the table
would be generated
While Loop
While is similar to for-loop, functionality wise
The only difference is its syntax
You can only put test condition in the brackets of while.
Initialization should be done before while and increment
in the body of while
While Loop
#include <stdio.h>
#include <conio.h>
main()
{
int a,b;
printf("This program prints the table of 5.\n \n");
a=1; //Initialization
while (a<=100) //test condition
{
b = 5 * a;
printf("\t 5 x %3d = %3d\n", a, b);
a++; //counter increment
}
getch();
}
DoWhile Loop
do..while evaluates the test condition after executing the
loop body
If the condition is false at the start of the loop, the dowhile
loop will still run but only once
Otherwise, the loop will keep repeating and will exit the body
when condition becomes false
for and while loops evaluate their test conditions before the
start of the loop.
This means dowhile runs at least once before exiting the
loop body