You are on page 1of 3

Birla Institute of Technology & Science, Pilani, Hyderabad Campus

Computer Programming [CS F111]


2021-22 First Semester
Lab Sheet 5

Topics to be covered: loops

The ‘for’ Loop


There are three basic types of loops which are:
_ for loop
_ while loop
_ do...while loop

The syntax of for loop is:

for(initialization Statement(s) ; testExpression ; updateStatement(s))


{
// body
}

The syntax of for while is:


initialization Statement(s);
while
(testExpression)
{
// body
updateStatement(s)
}

The syntax of for do while is:


initialization Statement(s);
do
{
// body
updateStatement(s)
} while (testExpression)
Let us understand the various components of the for loop. The
initializationStatement(s) is executed only once. If we want to write multiple
statements in this section they are separated by a comma (,). The testExpression
can be any valid C conditional expression. It is evaluated before execution of the loop
body ({}). If the test expression is false (0), for loop is terminated. But if the test
expression is true (nonzero), codes inside the body of for loop is executed and then the
updateStatement(s) is executed. This process repeats until the testExpression
is evaluated to false (0). The for loop is commonly used when the number of iterations
is known. Figure 1 represents the behaviour of a for loop.

A for, while and do while loop to print Hello World 10 times in given below:
#include<stdio.h>

int main (void)


{
for (int i=0; i<10; i++){
printf("Hello World\n");
}

i=0;
while(i<10){
printf("Hello World\n");
i++;
}
do{
printf("Hello World\n");
i++;
} while(i<10)

return 0;
}
Exercises:
1. Write a program to calculate the average of first ten natural numbers using loop.

2. Write a program to check if a number is prime.

3. Write a program that reads an integer with 5 digits and finds the sum and average of
digits of the number.

4. Write a program to find whether a positive integer (6 digits) entered by the user is a
palindrome or not. E.g. 12321 is a palindrome whereas 112233 is not.

5. Write a program to print the following pyramid for a user given positive n(<10). All the
below sample outputs are for N=4.

1
12
123
1234

You might also like