Professional Documents
Culture Documents
Theory Notes Unit-Ii: Loops
Theory Notes Unit-Ii: Loops
return 0;
}
METHOD 2 using loops
1. Entry Controlled loops: In this type of loops the test condition is tested before entering
the loop body. For Loop and While Loop are entry controlled loops.
2. Exit Controlled Loops: In this type of loops the test condition is tested or evaluated at
the end of loop body. Therefore, the loop body will execute at least once, irrespective
of whether the test condition is true or false. do – while loop is exit controlled loop.
Flowchart of every kind of loop will probably look like the one in figure1. As per the above
diagram, if the Test Condition is true, then the loop is executed, and if it is false then the
execution breaks out of the loop.
After the loop is successfully executed the execution again starts from the Loop entry and
again checks for the Test condition, and this keeps on repeating.
Figure 1
1 while loop
2 for loop
Executes a sequence of statements multiple times and abbreviates the code
that manages the loop variable.
3 do-while loop
It is more like a while statement, except that it tests the condition at the end of
the loop body.
4 nested loops
You can use one or more loops inside any other while, for, or do..while loop.
1. while loop
Syntax:
variable initialization;
while(condition)
{
statements;
variable increment or decrement;
}
Example program
Output
Example program 2
Output
Example program 3 to find sum of first n natural numbers using for loop
Ouput
2. for loop
This is one of the most frequently used loop in C programming. It is used to execute a set of
statements repeatedly until a particular condition is satisfied. We can say it is an open ended
loop.
In for loop we have exactly two semicolons, one after initialization and second after the
condition. In this loop we can have more than one initialization or increment/decrement,
separated using comma operator. But it can have only one condition.
The for loop is executed as follows:
i. It first evaluates the initialization code.
ii. Then it checks the condition expression.
iii. If it is true, it executes the for-loop body.
iv. Then it evaluate the increment/decrement condition and again follows from step 2.
v. When the condition expression becomes false, it exits the loop.
Example Program 1
Output
Example program 2
Output
Example program 3 to find sum of first n natural numbers using for loop
Output
2) Initialization part can be skipped from loop as shown below, the counter variable is
declared before the loop.
int num=10;
for (;num<20;num++)
Note: Even though we can skip initialization part but semicolon (;) before condition is must,
without which you will get compilation error.
3) Like initialization, you can also skip the increment part as we did below. In this case
semicolon (;) is must after condition logic. In this case the increment or decrement part is
done inside the loop.
4) This is also possible. The counter variable is initialized before the loop and incremented
inside the loop.
int num=10;
for (;num<20;)
{
//Statements
num++;
}
3. do-while loop
In some situations it is necessary to execute body of the loop before testing the condition.
Such situations can be handled with the help of do-while loop.
do statement evaluates the body of the loop first and at the end, the condition is checked
using while statement. It means that the body of the loop will be executed at least once, even
though the starting condition inside while is initialized to be false.
Syntax is:
do
{
.....
.....
}
while(condition);
Example program 1
Output
Output
4. Nested loops
C programming allows to use one loop inside another loop. The following section shows a few
examples to illustrate the concept.
Syntax
The syntax for a nested for loop statement in C is as follows −
for ( init; condition; increment ) {
for ( init; condition; increment ) {
statement(s);
}
statement(s);
}
The syntax for a nested while loop statement in C programming language is as follows −
while(condition) {
while(condition) {
statement(s);
}
statement(s);
}
The syntax for a nested do...while loop statement in C programming language is as follows −
do {
statement(s);
do {
statement(s);
}while( condition );
}while( condition );
A final note on loop nesting is that you can put any type of loop inside any other type of loop.
For example, a 'for' loop can be inside a 'while' loop or vice versa.
Sometimes, while executing a loop, it becomes necessary to skip a part of the loop or to leave
the loop as soon as certain condition becomes true. This is known as jumping out of loop.
1) break statement
When break statement is encountered inside a loop, the loop is immediately exited and the
program continues with the statement immediately following the loop.
2) continue statement
It causes the control to go directly to the test-condition and then continue the loop process.
On encountering continue, cursor leave the current cycle of loop, and starts with the next
cycle.
An array is a group (or collection) of same data types. For example an int array holds the
elements of int types while a float array holds the elements of float types.
A one-dimensional array is like a list; A two dimensional array is like a table; The C
language places no limits on the number of dimensions in an array, though specific
implementations may.
Some texts refer to one-dimensional arrays as vectors, two-dimensional arrays as
matrices, and use the general term arrays when the number of dimensions is
unspecified or unimportant.
1) Define 100 variables with int data type and then perform 100 scanf() operations to store
the entered values in the variables and then at last calculate the average of them.
2) To have a single integer array to store all the values, loop the array to store all the entered
values in array and later calculate the average.
Which solution is better according to you? Obviously the second solution, it is convenient to
store same data types in one single variable and later access them using array index.
Instead of declaring individual variables, such as number0, number1, ..., and number99, you
declare one array variable such as numbers and use numbers[0], numbers[1], and ...,
numbers[99] to represent individual variables. A specific element in an array is accessed by
an index.
All arrays consist of contiguous memory locations. The lowest address corresponds to the first
element and the highest address to the last element.
Declaring an Array
Like any other variable, arrays must be declared before they are used. General form of array
declaration is,
data-type variable-name[size];
int arr[10];
Memory representation of above array will look like this:
Here int is the data type, arr is the name of the array and 10 is the size of array. It means array
arr can only contain 10 elements of int type.
Index/subscript of an array starts from 0 to size-1 i.e first element of arr array will be stored
at arr[0] address and the last element will occupy arr[9].
Other declarations:
int num[35]; /* An integer array of 35 elements */
char ch[10]; /* An array of characters for 10 elements */
Similarly an array can be of any data type such as double, float, short etc.
Array variables are declared identically to variables of their data type, except that the
variable name is followed by one pair of square [ ] brackets for each dimension of the
array.
Uninitialized arrays must have the dimensions of their rows, columns, etc. listed within
the square brackets.
Example:
int i, j, intArray[ 10 ], number;
float floatArray[ 1000 ];
int tableArray[ 3 ][ 5 ]; /* 3 rows by 5 columns */
In general arr[n-1] can be used to access nth element of an array. where n is any integer
number.
For example:
int main()
{
int mydata[20];
mydata[0] /* first element of array mydata*/
mydata[19] /* last (20th) element of array mydata*/
}
Initialization of an Array
After an array is declared it must be initialized. Otherwise, it will contain garbage value (any
random value). An array can be initialized at either compile time or at runtime.
Example Program 1
Output
In the above program, array is initialised in the source code which is compile time
initialisation.
Example program 2
Output
/* Example */
int a[3][4];
Example Program
#include<stdio.h>
int main()
{
int arr[3][4];
int i, j, k;
printf("Enter array elements");
for(i = 0; i < 3;i++)
{
for(j = 0; j < 4; j++)
{
scanf("%d", &arr[i][j]);
}
}
printf("You entered\n");