0% found this document useful (0 votes)
2 views16 pages

Module 3-Looping & Arrays

This document provides an introduction to C programming focusing on looping constructs, including while loops, do-while loops, and for loops, explaining their syntax and usage. It also covers arrays, defining their types, declaration, initialization methods, and how to use them with functions. Additionally, it discusses control flow statements like break and continue, as well as the concept of infinite loops.

Uploaded by

iamnihal415
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views16 pages

Module 3-Looping & Arrays

This document provides an introduction to C programming focusing on looping constructs, including while loops, do-while loops, and for loops, explaining their syntax and usage. It also covers arrays, defining their types, declaration, initialization methods, and how to use them with functions. Additionally, it discusses control flow statements like break and continue, as well as the concept of infinite loops.

Uploaded by

iamnihal415
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 16

Introduction to C Programming

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.

while Loops ( Condition-Controlled Loops )

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

• In theory the body can be either a single statement or a block of statements


within { curly braces }, but in practice the curly braces are almost always
used with do-whiles.
• Example:
int month;
do {
printf( "Please enter the month of your birth > " );
scanf( "%d", &month );
} while ( month < 1 || month > 12 );

• 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.

for ( initialize counter ; test counter ; increment counter)


{
execute the statement(s);
}

• initialize counter : Initialize the loop counter value.

• test counter : Verify the loop counter whether the condition is true.

• increment counter : Increasing the loop counter value.

• execute the statement : Execute C statements.

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.

• for-loops are counter-controlled, meaning that they are normally used


whenever the number of iterations is known in advance.
• Syntax:
where again the body can be either a single statement or a block of statements
within { curly braces }.

• 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 )

The comma operator


• C has a comma operator, that basically combines two statements so that they
can be considered as a single statement.
• About the only place this is ever used is in for loops, to either provide
multiple initializations or to allow for multiple incrementations.
• For example:
int i, j = 10, sum;
for( i = 0, sum = 0; i < 5; i++, j-- )
sum += i * j;

break and continue


• break and continue are two C/C++ statements that allow us to further
control flow within and out of loops.
• break causes execution to immediately jump out of the current loop, and
proceed with the code following the loop.
• continue causes the remainder of the current iteration of the loop to be
skipped, and for execution to recommence with the next iteration.
o In the case of for loops, the incrementation step will be executed
next, followed by the condition test to start the next loop iteration.
o In the case of while and do-while loops, execution jumps to the next
loop condition test.
• ( We have also seen break used to jump out of switch statements. Continue
has no meaning in switch statements. )

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

 The array is a collection of homogeneous elements of same data type.


 The array index starts with 0.
 Arrays are called as subscripted variables because; it is accessed using subscripts/indexes.
 Ex: 1. List of employees in an organization.
2. List of products and their cost sold by a store.
3. Test scores of a class of students.

 Here marks[0]=10, marks[1]=20, marks[2]=30 and marks[3]=40. This subscript/index notation is


borrowed from Mathematics where we have the practice of writing: marks4, marks3, marks2 and so on.

3. TYPES OF ARRAYS

I. One dimensional array/ Single-Subscripted Variable


II. Two dimensional array/ Double-Subscripted Variable
III. Multidimensional array

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.

Ex: int marks[4];


 Here marks is the name of the array which is capable of storing 4 integer values. The first value will
be stored in marks[0], the second value will be stored in marks[1] and so on and the last value will be in
marks[3].

Dept. of CSE, SJEC, Mangalore 2021-22


1
CPPS – 18CPS13 Module 3

Declaration of One-Dimensional Array: Here is general syntax for array declaration along with examples.

Syntax: data_type array_name[array_size];


Examples: int marks[4];
float temperature[5];
Note: Declaration specifies the data type of array, its name and size.

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

Dept. of CSE, SJEC, Mangalore 2021-22


2
CPPS – 18CPS13 Module 3

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.

Syntax: data_type array_name[row_size][column_size];


Examples: int marks[4][4];
float city_temper[3][3];
Note: Declaration and definition specify the data type of array, its name and size.

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.

Syntax: data_type array_name[row_size][column_size]={list of values};


Examples: int marks[3][4]={ 1,2,3, 4, 5, 6, 7,8,9,10,11,12};
float city_temper[2][2]={29.5, 30.7, 35.6, 45.7};
Note: In the above examples we are storing values in marks array and temperature array respectively.
The pictorial representation is also given below

 After initialization the arrays appear as follows:

1 2 3 4 29.5 30.5
marks city_temp
35.6 45.7
5 6 7 8

Dept. of CSE, SJEC, Mangalore 2021-22


3
CPPS – 18CPS13 Module 3

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

Example for Invalid initialization


int A[3][ ]={1,2,3};
Note: Never have column size undeclared in two dimension array.

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

Pass individual elements of array as parameter Pass complete array as parameter


Here, each individual element of array is passed to Here, the complete array is passed to the function.
function separately.
Example: Example:

#include<stdio.h> #include<stdio.h>
int square(int); int sum(int [ ]);

Dept. of CSE, SJEC, Mangalore 2021-22


4
CPPS – 18CPS13 Module 3

int main( ) int main( )


{ {
int num[5], i; int marks[5], i;
num[5] ={1, 2, 3, 4, 5}; marks[5] ={10, 20, 30, 40, 50};
for(i=0; i<5; i++) sum(marks);
{ }
square(num[i]); int sum(int n[ ])
} {
} int i, sum=0;
int square(int n) for(i=0; i<5; i++)
{ {
int sq; sum = sum+n[i];
sq= n * n; }
printf(“%d ”, sq); printf(“Sum = %d ”, sum);
} }

4. OPERATIONS PERFORMED ON ONE_DIMENSIONAL ARRAY


SORTING: It is the process of arranging elements in the list according to their values in ascending or
descending order. A sorted list is called an ordered list.
Ex: Bubble Sort, Selection Sort, Insertion Sort, Shell Sort, Merge Sort, Quick Sort.

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

Dept. of CSE, SJEC, Mangalore 2021-22


7
CPPS – 18CPS13 Module 3

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

 A group of characters together is called String.


 String is always enclosed within double quotes (“ “)
 String always ends with delimiter (NULL – ‘\0’ )
 Ex: a = “SJEC”

Operations on string:

 Reading and writing a string


 Combining string together
 Copying one string to another
 Comparing string for equality
 Extracting a portion of string

Dept. of CSE, SJEC, Mangalore 2021-22


8

You might also like