Download as pdf or txt
Download as pdf or txt
You are on page 1of 18

Academic Unit-1 Chandigarh University

THEORY NOTES UNIT-II


LOOPS
You may encounter situations, when a block of code needs to be executed several number of
times. In general, statements are executed sequentially: The first statement in a function is
executed first, followed by the second, and so on.
Loops in programming comes into use when we need to repeatedly execute a block of
statements. For example: Suppose we want to print “Hello World” 10 times. This can be done
in two ways as shown below:
METHOD 1 // C program to illustrate need of loops
#include <stdio.h>
int main()
{
printf( "Hello World\n");
printf( "Hello World\n");
printf( "Hello World\n");
printf( "Hello World\n");
printf( "Hello World\n");
printf( "Hello World\n");
printf( "Hello World\n");
printf( "Hello World\n");
printf( "Hello World\n");
printf( "Hello World\n");

return 0;
}
METHOD 2 using loops

There are mainly two categories of 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.

Er. Jasleen Kaur (Subject Coordinator)


Academic Unit-1 Chandigarh University

Figure 1

There are 4 types of Loop in C language, namely:


Sr.No. Loop Type & Description

1 while loop

Repeats a statement or group of statements while a given condition is true. It


tests the condition before executing the loop body.

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

while loop can be addressed as an entry control loop. It is completed in 3 steps.

 Variable initialization.(e.g int x = 0;)


 condition(e.g while(x <= 10))
 Variable increment or decrement ( x++ or x-- or x = x + 2 )

Er. Jasleen Kaur (Subject Coordinator)


Academic Unit-1 Chandigarh University

Syntax:
variable initialization;
while(condition)
{
statements;
variable increment or decrement;
}

Example program

Output

Example program 2

Er. Jasleen Kaur (Subject Coordinator)


Academic Unit-1 Chandigarh University

Output

Example program 3 to find sum of first n natural numbers using for loop

Ouput

Er. Jasleen Kaur (Subject Coordinator)


Academic Unit-1 Chandigarh University

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.

Syntax of for loop:


for (initialization; condition test; increment or decrement)
{
//Statements to be executed repeatedly
}

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

Er. Jasleen Kaur (Subject Coordinator)


Academic Unit-1 Chandigarh University

Example program 2

Output

Example program 3 to find sum of first n natural numbers using for loop

Er. Jasleen Kaur (Subject Coordinator)


Academic Unit-1 Chandigarh University

Output

Various forms of for loop in C

I am using variable num as the counter in all the following examples –


1) Here instead of num++, I’m using num=num+1 which is same as num++.

for (num=10; num<20; num=num+1)

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.

for (num=10; num<20; )


{
//Statements
num++;
}

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++;
}

Er. Jasleen Kaur (Subject Coordinator)


Academic Unit-1 Chandigarh University

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

Er. Jasleen Kaur (Subject Coordinator)


Academic Unit-1 Chandigarh University

Example program 2 to add numbers until the user enters zero

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);
}

Er. Jasleen Kaur (Subject Coordinator)


Academic Unit-1 Chandigarh University

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.

Jumping Out of Loops

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.

Er. Jasleen Kaur (Subject Coordinator)


Academic Unit-1 Chandigarh University

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.

Er. Jasleen Kaur (Subject Coordinator)


Academic Unit-1 Chandigarh University

ARRAYS AND STRINGS

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.

Why we need Array in C Programming?


Consider a scenario where you need to find out the average of 100 integer numbers entered
by user. In C, you have two ways to do this:

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.

Er. Jasleen Kaur (Subject Coordinator)


Academic Unit-1 Chandigarh University

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];

/* Example of array declaration */

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 */

const int NROWS = 100;


const int NCOLS = 200;
float matrix[ NROWS ][ NCOLS ];

Er. Jasleen Kaur (Subject Coordinator)


Academic Unit-1 Chandigarh University

How to access element of an array in C


You can use array subscript (or index) to access any element stored in array. Subscript starts
with 0, which means arr[0] represents the first element in the array arr.

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.

Compile time Array initialization


Compile time initialization of array elements is same as ordinary variable initialization. The
general form of initialization of array is,
data-type array-name[size] = { list of values };

/* Here are a few examples */


int marks[4]={ 67, 87, 56, 77 }; // integer array initialization

float area[5]={ 23.4, 6.8, 5.5 }; // float array initialization

int marks[4]={ 67, 87, 56, 77, 59 }; // Compile time error

Example Program 1

Er. Jasleen Kaur (Subject Coordinator)


Academic Unit-1 Chandigarh University

Output

In the above program, array is initialised in the source code which is compile time
initialisation.

Runtime Array initialization


An array can also be initialized at runtime using scanf() function. This approach is usually used
for initializing large arrays, or to initialize arrays with user specified values.

Example program 2

Output

Er. Jasleen Kaur (Subject Coordinator)


Academic Unit-1 Chandigarh University

Input data into the array


Here we are iterating the array from 0 to 3 because the size of the array is 4. Inside the loop
we are displaying a message to the user to enter the values. All the input values are stored in
the corresponding array elements using scanf function.
for (x=0; x<4;x++)
{
printf("Enter number %d \n", (x+1));
scanf("%d", &num[x]);
}

Reading out data from an array


Suppose, if we want to display the elements of the array then we can use the for loop in C like
this.
for (x=0; x<4;x++)
{
printf("num[%d]\n", num[x]);
}

Various ways to initialize an array


You can also initialize the array during declaration like this:

int arr[5] = {1, 2, 3, 4 ,5};


OR (both are same)
int arr[] = {1, 2, 3, 4, 5};
Un-initialized array always contain garbage values.

Facts about Array in C/C++:


1. Accessing Array Elements:
Array elements are accessed by using an integer index. Array index starts with 0 and goes till
size of array minus 1.
2. No Index Out of bound Checking:
There is no index out of bounds checking in C/C++, for example, the following program
compiles fine but may produce unexpected output when run.
3. Also, In C, it is not compiler error to initialize an array with more elements than the
specified size. For example, the below program compiles fine and shows just Warning.

Two dimensional Arrays


C language supports multidimensional arrays also. The simplest form of a multidimensional
array is the two-dimensional array. Both the row's and column's index begins from 0.

Er. Jasleen Kaur (Subject Coordinator)


Academic Unit-1 Chandigarh University

Two-dimensional arrays are declared as follows,


data-type array-name[row-size][column-size]

/* Example */
int a[3][4];

An array can also be declared and initialized together. For example,


int arr[][3] = {
{0,0,0},
{1,1,1}
};
Note: We have not assigned any row value to our array in the above example. It means we
can initialize any number of rows. But, we must always specify number of columns, else it will
give a compile time error. Here, a 2*3 multi-dimensional matrix is created.

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");

Er. Jasleen Kaur (Subject Coordinator)


Academic Unit-1 Chandigarh University

for(i = 0; i < 3; i++)


{
for(j = 0; j < 4; j++)
{
printf("%3d", arr[i][j]);
}
printf("\n");
}
return 0;
}

Er. Jasleen Kaur (Subject Coordinator)

You might also like