Sie sind auf Seite 1von 10

C & DS for I MCA Unit-2 VVIT

Looping Control Structures


Looping control statement allows a statement or a set of/ block of statement to be
executed for repetitive number of times conditionally. In other words, as long as certain
condition is true, a statement or a block of statements are repeatedly executed.
A loop generally contains two segments, one the body of the loop and the other control
statement which tests the condition for repetition of loop. Depending on the position of the
control statement in the loop, a control structure may be of two types:

• Entry Controlled Loops - If the condition check (control statement) is at the start of the
loop then the loops are called Entry controlled loops. There is a possibility of loop body
not getting executed even once when the condition fails in the very first attempt.

• Exit Controlled Loops - If the condition check (control statement) is at the end (while
exiting) of the loop then the loops are called Exit controlled loops. The loop body is
guaranteed to execute at least once.

The flow chart for the 2 kinds of loops is shown below:

Loops can be classified into 2 other types based on fact that repeat for a definite amount of times
or indefinite amount of times. They are:

Count Control Loops (Definitive repetition): If number of times that a loop can execute can be
decided before the actual execution of them, then they are called Count Control Loops. A control
variable is used which is called counter (or index) of the loop which is should be initialized,
tested and updated properly for the desired loop operations.

Sentinel Control Loops (Indefinite repetition): A special value called sentinel value is used to
change the loop control expression from true to false. These are generally used when a series of
inputs are read from the user. A special value like -1 or 999 or ‘#’ is entered by the user to

Staff: Janaki Ram and Krishna Prasad Dept of IT and CSE Page:1
C & DS for I MCA Unit-2 VVIT

indicate the “end of data”. This is called sentinel value and the control variable that contains it is
called Sentinel variable. The sentinel value must be selected such that it is not part of actual data.

C language provides three control structures for looping. They are:


1. while
2. do..while
3. for

The while statement:


The while is the simplest of the looping structures in C. It is an entry controlled loop. The
general form of while statement is:
while(test-expression)
{
statement-block; //body of the loop
}
If the test condition evaluates to true (1 or any non-zero value) then the statement-block
in the body of the loop is executed. Once the statement-block is executed, the test-condition is
tested again, if it is true then the body executes again. This continues until the condition
evaluates to false. Once the condition is false, the control transferred to the statement after the
l oop.
The body of the loop can contain any number of statements. The flower braces or simply
braces are needed only when there are multiple statements. When there is only one statement,
braces can be omitted.
while(test-condition)
statement;

Eg: int i = 5; //initialization


while (i<=10) //condition check
{
printf (“%d”,i);
i++; //incrementing
}
The above code will display numbers from 5 to 10. This is an example of Counter Control loop
where i is the control variable.

while(getch()==’t’)
printf(“Hello\n”);

The above code keeps printing Hello until a ‘t’ read from the user. This is an example of Sentinel
Control Loop. In the above case sentinel value is ‘t’.
More Eg: Please refer Lab Exercise 1a and Exercise 7b (sentinel control loop)

The do statement (do.. while loop):


In contrast with while loop, in do-while loop the loop condition is testing while exiting
the loop structure. Therefore do-while is an exit controlled loop. This allows the body of the loop
to be executed at least once. The general form follows:

Staff: Janaki Ram and Krishna Prasad Dept of IT and CSE Page:2
C & DS for I MCA Unit-2 VVIT

do
{
set of statements;
}while(test-condition);

Note: do-while structure (since it is also a statement) should always be ended with a semi colon
after the test condition.
Once the do statement is reached, the program proceeds to evaluate the body of the loop
first and at end of the loop if the test-condition is evaluated to true (1 or Non-Zero) then the loop
body is repeated and so on. If the test-condition is evaluated to false (0) then the control exits the
loop and continues to the next statement after loop if one exists.
Eg:
i nt x;
{
printf (“Enter a value: ”);
scanf(“%d”, &x);
}while(x<90);

The above code continuously reads the value of x until it is entered below 90.
More Eg: Please refer to Lab Exercise 1d and 2c.

The for statement:


The for loop is another entry controlled loop. It is one of the powerful & flexible control
structure used for repetitive tasks. The general form is as follows:

for( initialization ; test-condition; increment/decrement)


{
loop-body;
}

• Generally for loops are controlled by the count of a control variable (counter or loop
variable) and so they best suit to implement counter control loops.
• General form of for loop has three sections initialization, condition check and
increment/decrement section.
• The counter is initialized in the initialization section when the loop is first reached.
• The test-condition is verified before executing the loop body every time and if it
evaluated to true, the loops continues to iterate (repeat). If the condition fails for very first
time, loop will execute at all.
• After each execution of for loop (iteration), the counter is either incremented or
decremented as required.

Eg: 1. for(x = 1;x<=10;x++)


printf(“%d ”,x);

Output: 1 2 3 4 5 6 7 8 9 10

Staff: Janaki Ram and Krishna Prasad Dept of IT and CSE Page:3
C & DS for I MCA Unit-2 VVIT

Eg: 2. for(x=10;x>=1;x---)
printf(“%d ”,x);

Output: 10 9 8 7 6 5 4 3 2 1

Additional Features of for loop:

 There can be more than one comma separated initializations in the initialization section
of for loop.
 There can be more than one comma separated increment/decrement in the
increment/decrement section of for loop.
Eg: for(i-0,sum=0; i<10 && sum<1000; i++,sum+=x)
 All three sections of the for loop are optional. Therefore a empty for loop for(;;) can also
exit. Since there is no condition check to terminate the loop, this executes infinite times.

Note: while coding with any kind of loops, enough care should be taken that the condition is
specified such that the loop terminates at some point of time. If not it may result in infinite loop
and the program will never terminate.

Nesting of Loops:
Any of the control structures can be nested with another control structure. If loop control
structure appears within the body of another loop, then that can be called Nesting of loops. We
can nest any number of loops at a time. Any combination of the above three loops can be used
for nesting.
Eg: for(i=0; i<3; i++)
{
for(j=0;j<2;j++)
printf(“i=%d, j=%d“,i,j);
}
Output: i=0, j=0 i=0, j=1 i=1, j=0 i=1, j=1 i=2, j=0 i=2, j=1
In the above code 2 for loops are nested. In the outer loop i varies from 0 to 3 and for every value
of i, j varies from 0 to 1. Therefore the printf() within the inner most executes (3x2) 6 times.

Use of break statement to jump out of a loop:


The break statement can be used to jump out of the loop (early exit). When a break is
executed inside a loop (any of the three) the execution of the loop will be terminated and the
control will be transferred to the statement after the loop.
In a nested structure if a break appears inside an inner loop, then the execution of inner
loop for that particular iteration of outer loop will be terminated. The control continues to
execute with next statement (after inner loop)in outer loop body and consecutive iterations of
outer loop are continued as usual.
If there is a requirement that the control should completely jump out of the inner loop
then goto should be used whose label is defined just before the statement after the outermost
loop. For details of goto refer to notes of Unit-1.

Staff: Janaki Ram and Krishna Prasad Dept of IT and CSE Page:4
C & DS for I MCA Unit-2 VVIT

Eg: for(i=0; i<=5; i++)


{
if(i==3) //when i is equal to 3
break; //will terminate the loop
printf(“%d “, i);
}
Output: 0 1 2 (notice the loop body not executed after i value 3)

Note: In lab exercises, the use break is illustrated in Non recursive logic of GCD (Exercise 3b)

Use of continue statement:


The continue statement is used for skipping a part of the loop body. When a continue
statement is executed, the compiler skips the statements following the continue statement and
continues execution with the next iteration of the loop.
In contrast with break, the continue will not terminate the entire execution of the loop
rather it just skips the execution of the code for the current iteration and continues with the next
iteration.
In a nested structure, if continue is used in the inner loop, then the portion of code inside
inner loop is skipped for that particular iteration of the inner loop and continues with next
iteration of inner loop. It will not affect the iterations of the outer loop (same is the case with
break).
Eg: for(i=0; i<5; i++)
{
if(i==3) //when i is equal to 3
continue; //skip the rest of the loop body for the current iteration
printf(“%d “, i);
}
Output: 0 1 2 4 5 (notice the part of loop body is skipped for i value 3 and is continued for the
next iterations)

Note: In lab exercises, the use of continue is illustrated in Exercise 10a (2’s complement)

Arrays
An array is a contiguous blocks of memory that holds similar kind of values. In some
other way, an array is a sequence of homogeneous or similar kind of items. An array can be
defined as a group of similar kind of items referred by a common name. A specific element in
the array is located or identified by its index value (also called subscript). C supports different
types of Arrays. They are:
Single dimensional arrays
Two-dimensional arrays
Multi-dimensional arrays.

Single dimensional arrays:

An array with one subscript variable is known as single dimensional array. It is also
known as linear list or simply list.

Staff: Janaki Ram and Krishna Prasad Dept of IT and CSE Page:5
C & DS for I MCA Unit-2 VVIT

Declaring of arrays:
The general form of array declaration is as follows:
type array_name[size];

where type is the data type of the elements that the array can store, array_name can be any
identifier to identity the array and size is a integer value which indicated the maximum number
of elements the array can store. The size is mentioned in square brackets following the name.
Eg: int a[10]; // an array of 10 integers
char s[20]; // an array of 20 characters or simple a string.
float f[15]; // an array of 15 floating point values.

Initializing of arrays:
The elements of a array can be initialized when they are declared. The following
is the general form:
type array_name[n]={v1,v2,v3,v4,…..vn};

Where n is size of array and v1,v2,v3,….vn are the initial values of the elements in the array.
Eg: int a[6] = { 10, 15, 12, 18, 20, 25};

When arrays are initialized mentioning of size in square brackets is optional for example the
statement, int a[] = { 10, 15, 12, 18, 20, 25}; will automatically create any array “a” of size 6
with mentioned initial values for its elements.

A statement int a[6] = { 10, 15, 12} will actually create 6 memory locations but will initialize
only first three elements.

Symbolic representation of elements of the arrays:

int a[6] = { 10, 15, 12, 18, 20, 25};


Array name
a
10 15 12 18 20 25 Array values

0 1 2 3 4 5 Index positions

Accessing elements of a array:

The individual elements of an array can be accessed (or referenced) by specifying the
subscript (or Index). Index values always start from 0. Each element is referred as a[0], a[1],
a[2]…… Index values should not be negative values and the range of indices is 0 to n-1 (bounds
of the array) where n is the size of the array. While programming, care should be taken that the
index should not be out of the array bounds. Size of array should always be positive.

Staff: Janaki Ram and Krishna Prasad Dept of IT and CSE Page:6
C & DS for I MCA Unit-2 VVIT

Reading all values or displaying all values of array:


In general loops are used to read all values or display all values or to perform any
operation on each of the elements in array. And most often for loop is used

Eg: #include<stdio.h>
void main()
{
int i, sum=0, scores[11] ={0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0};
float avg;
clrscr();
for(i=0; i<11; i++) //for each of 11 players
{
printf(“Enter the score of player %d: ”,i+1);
scanf(“%d”, &scores[i]); //read the score of the player
sum+=scores[i]; //accumulate the sum of scores
}
avg=(float)sum/11; //calculate avg; use explicit conversion to make it float instead of integer division

printf(“The total score of team is %d and average of per player is %f”,sum,avg);


getch();
}

Note: Also refer Lab Exercise 5a

Two-dimensional arrays (2D- Arrays):

An array with two subscript variables is known as two-dimensional array (2D-Array).


These are generally used to store a table of values. The first subscript specifies number of rows
& the second subscript specifies number of columns. It is also called as double dimensional
array. Declaration general form is as follows:

Data_type array_name [ no. of rows][no. of columns];

Eg:
int a[4][4];// an integer array with 4 rows & 4 columns
Char str [5][15]; //a char. Array with 5 rows & 15 columns (or) a set of 5 names
// with 15 characters in each name.
Initializing of 2D-Array can be done like this.
int [3][2] = {{4,6},{10,56},{-4,5}}; or
int[3][2]={4,6,10,56,-4,5}

Note: Refer Lab Exercise 5b for example for 2-D array

Staff: Janaki Ram and Krishna Prasad Dept of IT and CSE Page:7
C & DS for I MCA Unit-2 VVIT

Symbolic representation follows:

int a[3][4] = { 11, 55, 44, 33, 77, 99, 88, 67, 22, 25, 78, 87};
0 1 2 3

0 11 55 44 33

1 77 99 88 67

2 22 25 78 87

Here
a[0][0] = 11 , a[0][1] = 55, a[0][2] = 44, a[0][3] = 33
a[1][0] = 77, a[1][1] = 99 ………………………..
a[2][0] = 22, a[2][1] = 25 …………………………

Advantages of Arrays:

1. Arrays can hold a collection of identical values.


2. Accessing of array elements is easy (since they are stored in continuous memory
locations).
3. Pointer can be applied on arrays.
4. More flexible.

Disadvantages of arrays:

1. As the array size is fixed, we cannot increase or shrink the size. Hence it may lead to
wastage of memory.
2. Insertions & deletions are difficult to perform.
3. Unable to hold different kinds values.

Note:: If the dimension of an array is increased beyond 2 then it is called Multi-Dimensional


array. In general, more than 3D-arrays are not used.

Strings:

• A string is a collection of character data. In other words, a set of characters followed by a


null is known to be a string i.e., at the end of every string, there exists a null terminating
character (‘\0’). It represents end of string. Strings can hold words or sentences.
• In C strings are represented using a character array. String constants are placed between 2
double quotations.

Staff: Janaki Ram and Krishna Prasad Dept of IT and CSE Page:8
C & DS for I MCA Unit-2 VVIT

Eg: char str[6]= “INDIA”;


char str[6]={‘I’,’N’,’D’,’I’,’A’,’\0’};

Note: When double quotes (“ ”) are used to assign the string, the null character need not be
specifically mentioned at the end. It is implied.

Input and Output of Strings:


In order to perform input/output operations on strings, C provides different functions.
They are called as unformatted I/O. gets(), puts(), getch() and putch() are few of them.

 void gets(char *s)  reads a string from user console and makes s to point to the string.
This can read multi-word sentences but cannot read multi-line text.
 void puts(char *s)  display the string contained in the s.
 char getch()  This is used to read a single character from user console. This return the
character read from the user.
 void putch(char c)  Display the single character stored in variable c. New line is added
by default after displaying the string.
 The functions scanf() and printf() functions can also be used to read and write the strings
by using the format specifier ‘%s’. The limitation with scanf() function is that it cannot
handle strings with multiple words. So in general gets() is used to read strings with
multiple words.

Eg:
#include<stdio.h>
#include<conio.h>
void main()
{
char str[10];
clrscr();
puts(“Enter any string:”); // unformatted Output function
gets(str); // unformatted Input function.
printf(“\nThe entered string is: “);
puts(str);
getch();
}

Output:
Enter any string:
Hello VVIT
The entered string is:
Hello VVIT

Staff: Janaki Ram and Krishna Prasad Dept of IT and CSE Page:9
C & DS for I MCA Unit-2 VVIT

String Handling:

Certain operations on strings may be required while implementing applications. To


simplify such operations user may require functions. C provides a set of library functions in
string.h. Some of the functions that are used often are as follows:

Function name Function Signature Operation

strlen(s) int strlen(char [ ]) or To find length of a given string


int strlen(char*)
strrev(s) void strrev(char [ ]) or To reverse a given string.
void strrev(char*)
strcpy(s2,s1) void strcpy(char dest[], char To copy one string into another.
source[]) S1 is copied into s2.
strcat(s1,s2) void strcat(char [ ], char [ ]) To concat two different strings; s2
is attached to s1.
strcmp(s1,s2) int strcmp(char [ ], char[ ]) It compares s1,s2 and returns:
0 : if equal
<0 : if first string is less than
second string
>0 : if first string is greater
than second string.
strlwr(s) void strlwr(char *) Converts all the characters in s to
lower case
strupr(s) void strupr(char *) Converts all the characters in s to
upper case
strchr(s,ch) int strchr(char *, int ) Finds the first occurrence of ch in
s.
strstr(s1, s2) char* strstr(char*, char*) Finds the first occurrence of string
s2 in main string s1

For examples based on string operations, please refer to the Lab Exercises 6 and 7.

Staff: Janaki Ram and Krishna Prasad Dept of IT and CSE Page:10

Das könnte Ihnen auch gefallen