Looping Control Structures: C&Dsforimca Unit-2 Vvit
Looping Control Structures: C&Dsforimca Unit-2 Vvit
Looping Control Structures: C&Dsforimca Unit-2 Vvit
• 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.
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.
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)
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.
• 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.
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
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.
Staff: Janaki Ram and Krishna Prasad Dept of IT and CSE Page:4
C & DS for I MCA Unit-2 VVIT
Note: In lab exercises, the use break is illustrated in Non recursive logic of GCD (Exercise 3b)
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.
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.
0 1 2 3 4 5 Index positions
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
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
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}
Staff: Janaki Ram and Krishna Prasad Dept of IT and CSE Page:7
C & DS for I MCA Unit-2 VVIT
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:
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.
Strings:
Staff: Janaki Ram and Krishna Prasad Dept of IT and CSE Page:8
C & DS for I MCA Unit-2 VVIT
Note: When double quotes (“ ”) are used to assign the string, the null character need not be
specifically mentioned at the end. It is implied.
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:
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