Module 3-Looping & Arrays
Module 3-Looping & Arrays
Looping Constructs
Computers are very good at performing repetitive tasks very quickly. In this
section we will learn how to make computer repeat actions either a specified
number of times or until some stopping condition is met.
• Description
• The most basic loop in C is the while loop and it is used is to repeat a
block of code. A while loop has one control expression (a specific
condition) and executes as long as the given expression is true.
• Both while loops and do-while loops ( see below ) are condition-controlled,
meaning that they continue to loop until some condition is met.
• Both while and do-while loops alternate between performing actions and
testing for the stopping condition.
• While loops check for the stopping condition first, and may not execute the
body of the loop at all if the condition is initially false.
• Syntax:
while (condition)
{
statement(s);
}
where the body can be either a single statement or a block of statements within {
curly braces }.
• Example:
int i = 0;
while( i < 5 )
printf( "i = %d\n", i++ );
printf( "After loop, i = %d\n", i );
do-while Loops
• do-while loops are exactly like while loops, except that the test is performed
at the end of the loop rather than the beginning.
• This guarantees that the loop will be performed at least once, which is useful
for checking user input among other things ( see example below. )
• Syntax:
do {
body;
} while( condition );
• Note that the above example could be improved by reporting to the user
what the problem is if month is not in the range 1 to 12, and that it could
also be done using a while loop if month were initialized to a value that
ensures entering the loop.
• The following diagram shows the difference between while and do-while
loops. Note that once you enter the loop, the operation is identical from that
point forward:
Nested do while loop
The following program will print out a multiplication table of numbers 1,2,…,n.
The outer do-while loop is the loop responsible for iterating over the rows of
the multiplication table. The inner loop will, for each of the values of colnm,
print the row corresponding to the colnm multiplied with rownm. Here we use
the special "\t" character within printf() function to get a clear output.
#include <stdio.h>
main()
{
int rownm,nrow,colnm;
rownm=1;
colnm=1;
printf("Input number of rows for the table : ");
scanf("%d",&nrow);
do
{
colnm=1;
do
{
printf("%d\t",rownm*colnm);
colnm++;
}
while(colnm<=nrow);
rownm++;
printf("\n");
}
while(rownm<=nrow);
Output:
for Loops
A "For" Loop is used to repeat a specific block of code (statements) a known
number of times. The for-loop statement is a very specialized while loop,
which increases the readability of a program. Here is the syntax of the of for
loop.
• test counter : Verify the loop counter whether the condition is true.
Note : The for-loop must have two semi-colons between the opening and
closing parenthesis.
The following picture has clearly described the for loop syntax.
• Details:
o The initialization step occurs one time only, before the loop begins.
o The condition is tested at the beginning of each iteration of the loop.
▪ If the condition is true ( non-zero ), then the body of the loop is
executed next.
▪If the condition is false ( zero ), then the body is not executed,
and execution continues with the code following the loop.
o The incrementation happens AFTER the execution of the body, and
only when the body is executed.
• Example:
• Special Notes:
o The third part of the loop is labeled "incrementation", because it
usually takes the form of "i++" or something similar. However it can
be any legal C/C++ statement, such as "N += 3" or "counter = base +
delta".
o In the example above, the variable i is declared before the loop, and
continues to exist after the loop has completed. You will also see
occasions where the loop variable is declared as part of the for loop, (
in C99 ), in which case the variable exists only within the body of the
loop, and is no longer valid when the loop completes:
for( int i = 0; i < 5; i++ )
printf( "i = %d\n", i );
printf( "After loop, i is no longer valid\n" );
o ( In Dev C++ you can specify support for C99 by selecting Project-
>Project Options from the menu, and then selecting the Parameters
tab. Under "C compiler", add the line: -std=c99 )
Infinite Loops
• Infinite loops are loops that repeat forever without stopping.
• Usually they are caused by some sort of error, such as the following
example in which the wrong variable is incremented:
int i, j;
for( i = 0; i < 5; j++ )
printf( "i = %d\n", i );
printf( "This line will never execute\n" );
• Other times infinite loops serve a useful purpose, such as this alternate
means of checking user input:
CPPS – 18CPS13 Module 3
CHAPTER 1
ARRAYS
1. WHY DO WE NEED ARRAYS?
Arrays are used to represent multiple data items of the same type using single name.
2. DEFINITION OF ARRAYS
3. TYPES OF ARRAYS
I. One-Dimensional Array: A list of items can be given one variable name using only one subscript
and such a variable is called as one dimensional array.
Declaration of One-Dimensional Array: Here is general syntax for array declaration along with examples.
Initialization of One-Dimensional Array: After array is declared, next is storing values in to an array is
called initialization. There are two types of array initialization:
1. Compile-time initialization
2. Run-time initialization
1. Compile time initialization: If we assign values to the array during declaration it is called compile
time initialization. There are 4 different methods:
a) Initialization with size
b) Initialization without size
c) Partial initialization
d) Initializing all values zero
a) Initialization with size: we can initialize values to all the elements of the array.
Syntax: data_type array_name[array_size]={list of values};
Examples: int marks[4]={ 95,35, 67, 87};
float temperature[3]={29.5, 30.7, 35.6};
b) Initialization without size: We needn’t have to specify the size of array provided we are initializing
the values in beginning itself.
Syntax: data_type array_name[ ]={list of values};
Examples: int marks[ ]={ 95,35, 67, 87};
float temperature[ ]={29.5, 30.7, 35.6, 45.7, 19.5};
c) Partial initialization: If we not specify the all the elements in the array, the unspecified elements
will be initialized to zero.
Example: int marks[5]={10,12,20};
Here, marks[3] and marks[4] will be initialized to zero.
d) Initializing all the elements zero: If we want to store zero to all the elements in the array we can do.
Examples: int marks[4]={0};
2. Run time initialization: Run time initialization is storing values in an array when program is
running or executing.
Example:
printf(“Enter 4 marks”);
for(i=0; i<4; i++)
{
scanf(“ %d”, &marks[i]);
}
II. Two-Dimensional Array: A list of items can be given one variable name using two subscripts and
such a variable is called a single subscripted variable or one dimensional array.
It consists of both rows and columns. Ex: Matrix.
Declaration of Two-Dimensional Array: Here is general syntax for array declaration along with examples.
Initialization of Two-Dimensional Array: After array is declared, next is storing values in to an array is
called initialization. There are two types of array initialization:
1. Compile-time initialization
2. Run-time initialization
1. Compile time initialization: If we assign values to the array during declaration it is called compile
time initialization. Following are the different methods of compile time initialization.
1 2 3 4 29.5 30.5
marks city_temp
35.6 45.7
5 6 7 8
2. Run time initialization: Run time initialization is storing values in an array when program is
running or executing.
Following example illustrates run time storing of values using scanf and for loop:
Example: printf(“Enter the marks”);
for(i=0; i<3; i++)
for(j=0;j<3;j++)
{
scanf(“ %d”, &marks[i][j]);
}
More Examples: Other way of initialization:
int a[ ][3]= { 0, 1, 2, 3,4,5,6,7,8};
int b[ ][4] ={1,2,3,4,5,6,7,8,9,10,11,12};
012 1234
a b
345 5678
67 8 9 10 11 12
III. Multi-Dimensional Array: It can have 3, 4 or more dimensions. A three dimensional array is an
array of 2D arrays. It has row, columns, depth associated with it.
NOTE:
USING ARRAYS WITH FUNCTIONS:
In large programs that use functions we can pass Arrays as parameters. Two ways of passing arrays to
functions are:
1. Pass individual elements of array as parameter
2. Pass complete array as parameter
#include<stdio.h> #include<stdio.h>
int square(int); int sum(int [ ]);
Bubble Sort
Bubble sort will start by comparing the first element of the array with the second element, if the first element
is greater than the second element, it will swap both the elements, and then move on to compare the second
and the third element, and so on.
#include<stdio.h>
void main( )
{
int n, a[100], i, j, temp;;
printf("Enter size of array\n");
scanf("%d",&n);
printf("Enter elements of array\n");
for(i=0;i<n;i++)
scanf("%d", &a[i]);
for(i=0;i<n;i++)
{
for(j=0;j<(n-i)-1;j++)
{
if( a[j]>a[j+1])
{
temp=a[j];
a[j]=a[j+1];
a[j+1]=temp;
Dept. of CSE, SJEC, Mangalore 2021-22
5
CPPS – 18CPS13 Module 3
}
}
}
printf("The sorted array is\n");
for(i=0;i<n;i++)
printf("%d\n",a[i]);
}
Selection Sort
Selection sort will start by comparing the first element with other elements and finds minimum element and
swaps, then it starts comparing by taking second element with other elements and so on.
#include<stdio.h>
void main( )
{
int n, a[100], i, j, temp, pos;
printf("Enter size of array\n");
scanf("%d",&n);
printf("Enter elements of array\n");
for(i=0;i<n;i++)
scanf("%d", &a[i]);
for(i=0;i<n;i++)
{
pos=i;
for(j=i+1;j<n;j++)
{
if( a[pos]>a[j])
pos=j;
}
if(pos !=i )
{
temp=a[i];
a[i]=a[pos];
a[pos]=temp;
}
}
printf("The sorted array is\n");
for(i=0;i<n;i++)
printf("%d\n",a[i]);
}
SEARCHING: It is the process of finding the location of the specified element in a list.
The specified element is often called the search key.
If it is found search is successful, otherwise it is unsuccessful.
Ex: Binary Search, Linear Search, Sequential Search.
Dept. of CSE, SJEC, Mangalore 2021-22
6
CPPS – 18CPS13 Module 3
Linear Search
Linear search is a very basic and simple search algorithm. In Linear search, we search an element or value in
a given array by traversing the array from the starting, till the desired element or value is found.
#include<stdio.h>
void main( )
{
int n, a[100], i, key,loc;
printf("Enter size of array\n");
scanf("%d",&n);
printf("Enter elements of array\n");
for(i=0;i<n;i++)
scanf("%d",&a[i]);
printf("Enter the search element\n");
scanf("%d",&key);
loc = -1;
for(i=0;i<n;i++)
{
if(key == a[i])
{
loc=i+1;
break;
}
if(loc>=0)
printf("The element is found at %d \n",loc);
else
printf("Search unsuccessful\n");
}
Binary Search
Binary search works only on a sorted set of elements. To use binary search on a collection, the collection
must first be sorted. The array is divided into two parts, compared with middle element if it is not successful,
then it is compared whether it is lesser or greater than middle element. If it is lesser, search is done towards
left part else right part.
#include<stdio.h>
void main( )
{
int n, a[100], i, key, loc, high, low, mid;
printf("Enter size of array\n");
scanf("%d",&n);
printf("Enter elements of array\n");
for(i=0;i<n;i++)
scanf("%d",&a[i]);
printf("Enter the search element\n");
scanf("%d",&key);
loc=-1;
low=0;
high=n-1;
while(low<=high)
{
mid=(low+high)/2;
if(key==a[mid])
{
loc = mid+1;
break;
}
else
{
if(ele<a[mid])
high=mid-1;
else
low=mid+1;
}
}
if(loc>=0)
printf("The element is found at %d \n",,loc);
else
printf("Search unsuccessful\n");
}
CHAPTER 2
STRINGS
1. INTRODUCTION
Operations on string: