18bma55s U3
18bma55s U3
The test condi ons should be carefully stated in order to perform the desired number of loop
execu ons. It is assumed that the test condi on will eventually transfer the control out of the loop.
Some mes the control sets up an infinite loop and the body is executed over and over again.
The while is an entry controlled loop statement. The test-condi on is evaluated and if the condi on is
true, then the body of the loop is executed. A er execu on of the body, the test-condi on is once
again evaluated and if it is true, the body is executed once again. This process of repeated execu on of
the body con nues un l the test-condi on finally becomes false and the control is transferred out of
the loop. On exit, the program con nues with the statement immediately a er the body of the loop.
The body of the loop may have one or more statements. The braces are needed only if the body
contains two or more statements. However, it is a good prac ce to use braces even if the body has
only one statement.
Example program
-----------
-----------
sum = 0;
n = 1;
while ( n <= 10)
{
sum = sum + n * n;
n = n + 1;
}
prin (“sum = %d\n”, sum);
-------
-------
The body of the loop is executed 10 mes for n = 1, 2, …, 10 each me adding the square of the value
of n, which is incremented inside the loop. The test condi on may also be wri en as n < 11; the result
would be the same. This is a typical example of counter-controlled loops. The variable n is called
counter or control variable.
Another example of while statement which uses the keyboard input is shown below
----
----
character = ‘ ‘;
while ( character != ‘y’)
character = getchar( );
xxxxx;
----
----
First the character is ini alized to ‘ ‘. The while statement then begins by tes ng whether character is
not equal to y. since the character was ini alized to ‘ ‘, the test is true and the loop statement
character = getchar ( ); is executed. Each me a le er is keyed in, the test is carried out and the loop
statement executed un l the le er y is pressed. When y is pressed, the condi on becomes false
because character equals y and the loop terminates thus transferring the control to the statement
xxxxx;. This is a typical example of sen nel-controlled loops.
THE DO STATEMENT:
The while loop tests the condi on before the loop is executed. But in some occasions it is necessary to
execute the body of the loop before the test is performed. Such situa ons can be handled with the
help of the do statement. The general form is
do
{
body of the loop
}
while (test-condi on);
On seeing the do statement, the program proceeds to evaluate the body of the loop first. Then the test
condi on near while statement is evaluated. If the condi on is true, the program con nues to
evaluate the body of the loop once again. This process con nues as long as the condi on is true.
When the condi on becomes false, the loop will be terminated and the control goes to the statement
that appears immediately a er the while statement. The do … while statement is a exit-controlled
loop. For example
---
do
{
prin (“input a number\n”);
number = getnum( );
}
while (number > 0);
----
This segment of a program reads a number from the keyboard un l a zero or a nega ve number is
keyed in and assigned to the sen nel variable number. The test condi ons may have compound
rela ons as well. For instance the statement while (number > 0 && number < 100); the loop will be
executed as long as the number keyed in lies between 0 and 100.
Is perfectly valid. The mul ple arguments in the increment sec on are separated by commas. The
third feature is that the test-condi on may have any compound rela on and the tes ng need not be
limited only to the loop control variable.
Nes ng of loops, that is one for statement within another for statement, is allowed in C. for example,
two loops can be nested as follows:
The nes ng may con nue up to any desired level. The loops should be properly indented so as to
enable the reader to easily determine which statements as contained within each for statement. For
example
JUMPS IN LOOPS
Loops perform a set of opera ons repeatedly un l the control variable fails to sa sfy the
test-condi on. The number of mes a loop is repeated is decided in advance and the test condi on is
wri en to achieve this. Some mes, when execu ng a loop it becomes desirable to skip a part of the
loop or to leave the loop as soon as a certain condi on occurs. C permits a jump from one statement
to another within a loop as well as a jump out of a loop.
JUMPING OUT OF A LOOP
As early exit from a loop can be accomplished by using the break statement or the goto statement.
These statements can also be used within while, do or for loops. For example
UNIT III
DECISION MAKING AND LOOPING
In decision making statements like if statement, switch, goto statements branches the control to
another statement by the result of the rela onal expression associated with the decision making
statements. In some occasions the same set of statements needs to be executed repeatedly for certain
number of mes, this can be done using looping statements like while, do and for statements.
In looping a sequence of statements are executed un l some condi ons for termina on of the loop
are sa sfied. A program loop therefore consists of two segments, one known as the body of the loop
and the other known as the control statement. The control statement tests certain condi ons and
then directs the repeated execu on of the statements contained in the body of the loop.
Depending on the posi on of the control statement in the loop, a control structure may be classified
either as the entry-controlled loop or as the exit controlled loop. The entry-controlled loop and
exit-controlled loops are also known as pre-test and post-test loops respec vely.
The test condi ons should be carefully stated in order to perform the desired number of loop
execu ons. It is assumed that the test condi on will eventually transfer the control out of the loop.
Some mes the control sets up an infinite loop and the body is executed over and over again.
The while is an entry controlled loop statement. The test-condi on is evaluated and if the condi on is
true, then the body of the loop is executed. A er execu on of the body, the test-condi on is once
again evaluated and if it is true, the body is executed once again. This process of repeated execu on of
the body con nues un l the test-condi on finally becomes false and the control is transferred out of
the loop. On exit, the program con nues with the statement immediately a er the body of the loop.
The body of the loop may have one or more statements. The braces are needed only if the body
contains two or more statements. However, it is a good prac ce to use braces even if the body has
only one statement.
Example program
-----------
-----------
sum = 0;
n = 1;
while ( n <= 10)
{
sum = sum + n * n;
n = n + 1;
}
prin (“sum = %d\n”, sum);
-------
-------
The body of the loop is executed 10 mes for n = 1, 2, …, 10 each me adding the square of the value
of n, which is incremented inside the loop. The test condi on may also be wri en as n < 11; the result
would be the same. This is a typical example of counter-controlled loops. The variable n is called
counter or control variable.
Another example of while statement which uses the keyboard input is shown below
----
----
character = ‘ ‘;
while ( character != ‘y’)
character = getchar( );
xxxxx;
----
----
First the character is ini alized to ‘ ‘. The while statement then begins by tes ng whether character is
not equal to y. since the character was ini alized to ‘ ‘, the test is true and the loop statement
character = getchar ( ); is executed. Each me a le er is keyed in, the test is carried out and the loop
statement executed un l the le er y is pressed. When y is pressed, the condi on becomes false
because character equals y and the loop terminates thus transferring the control to the statement
xxxxx;. This is a typical example of sen nel-controlled loops.
THE DO STATEMENT:
The while loop tests the condi on before the loop is executed. But in some occasions it is necessary to
execute the body of the loop before the test is performed. Such situa ons can be handled with the
help of the do statement. The general form is
do
{
body of the loop
}
while (test-condi on);
On seeing the do statement, the program proceeds to evaluate the body of the loop first. Then the test
condi on near while statement is evaluated. If the condi on is true, the program con nues to
evaluate the body of the loop once again. This process con nues as long as the condi on is true.
When the condi on becomes false, the loop will be terminated and the control goes to the statement
that appears immediately a er the while statement. The do … while statement is a exit-controlled
loop. For example
---
do
{
prin (“input a number\n”);
number = getnum( );
}
while (number > 0);
----
This segment of a program reads a number from the keyboard un l a zero or a nega ve number is
keyed in and assigned to the sen nel variable number. The test condi ons may have compound
rela ons as well. For instance the statement while (number > 0 && number < 100); the loop will be
executed as long as the number keyed in lies between 0 and 100.
Is perfectly valid. The mul ple arguments in the increment sec on are separated by commas. The
third feature is that the test-condi on may have any compound rela on and the tes ng need not be
limited only to the loop control variable.
Nes ng of loops, that is one for statement within another for statement, is allowed in C. for example,
two loops can be nested as follows:
The nes ng may con nue up to any desired level. The loops should be properly indented so as to
enable the reader to easily determine which statements as contained within each for statement. For
example
JUMPS IN LOOPS
Loops perform a set of opera ons repeatedly un l the control variable fails to sa sfy the
test-condi on. The number of mes a loop is repeated is decided in advance and the test condi on is
wri en to achieve this. Some mes, when execu ng a loop it becomes desirable to skip a part of the
loop or to leave the loop as soon as a certain condi on occurs. C permits a jump from one statement
to another within a loop as well as a jump out of a loop.
JUMPING OUT OF A LOOP
As early exit from a loop can be accomplished by using the break statement or the goto statement.
These statements can also be used within while, do or for loops. For example
ARRAYS
INTRODUCTION
We know that the fundamental data types are char, int, float, double and variations of int and
double are useful in defining variables. These variables can store only one value at any given
time, to handle large amount of data, we need a powerful data type that would facilitate efficient
storing, accessing and manipulation of data items. C supports a derived data type known as array
that can be used for such applications.
An array is a fixed-size sequenced collection of elements of the same data type. It is simply
grouping of like-type data. An array can be used to represent a list of numbers, a list of names,
etc. some examples are
1. List of temperatures recorded every hour in a day or a month or a year.
2. List of employees in an organization.
3. List of products and their cost sold by a store.
4. Test scores of a class of students
5. Table of daily rainfall data.
Array is one of the data structures in C which provides a convenient structure for representing
data. For instance, we can use an array name salary to represent a set of salaries of a group of
employees in an organization as salary [10], which represents the salary of 10th employee. While
the complete set of values is referred to as an array, individual values are called elements.
We can use arrays not only to represent simple lists of values but also tables of data in
two, three or more dimensions. The types of arrays are
● One-dimensional arrays
● Two-dimensional arrays
● Multidimensional arrays
ONE-DIMENSIONAL ARRAYS
A list of items can be given one variable name using only one subscript and such a variable is
called a single-subscripted variable or a one-dimensional array. For example to calculate the
n
∑ xi
average of n values of x we use the formula A = i=1n . The subscripted variable xi refers to the
ith element of x. In C, these x can be expressed in array form as
x (1) , x (2) , x (3) , x (4) , . . . , x[n] or x (0) , x (1) , x (2) , x (3) , . . . , x[n−1]
Both are allowed in C. If we want to represent a set of 5 numbers, we should declare the array as
x (1)
x (2)
x (3)
x (4)
x (5)
x (1) =
32;
x (2) =
34;
x (3) =
54;
x (4) =
29;
x (5) =
47;
This would cause the array number to store the values as shown below:
x (1) 32
x (2) 34
x (3) 54
x (4) 29
x (5) 47
These elements may be used in programs just like any other c variable. For example
A = (x (1) + x (2) + x (3) + x (4) + x[5] ) / n;
Value[6] = number[2]*3;
Salary[i]=basic[i]+DA[i];
Are all valid statements. The subscripts of an array can be integer constants, integer variables
like i, j or expressions that yield integers. C performs no bounds checking and therefore, care
should be exercised to ensure that the array indices are within the declared limits.
Like any other variable, arrays must be declared before they are used so that the compiler can
allocate space for them in memory. The general form of array declaration is
The data type specifies the type of elements that will be contained in the array, such as int, float
or char and size indicates the maximum number of elements that can be stored inside the array.
For example
‘W’
‘E’
‘L’
‘L’
‘‘
‘D’
‘O’
‘N’
‘E’
‘\0’
When the compiler sees a character string, it terminates it with an additional null character. Thus
the element name [10] holds the null character ‘\0’. When declaring character arrays, we must
allow one extra element space for the null terminator.
10
Program to evaluate the expression total = ∑ x2i
i=1
The values of x1 , x2 , . . . are read from the terminal
main()
{
int i;
float x [10], value, total;
printf(“Enter 10 real numbers\n”);
for ( i = 0; i < 10 ; i++ )
{
scanf(“%f”, &value);
x[i] = value;
total = 0.0;
for ( i = 0 ; i < 10 ; i++ )
total = total + x[i] * x[i];
printf(“\n”);
for ( i = 0 ; i > 10 ; i++ )
printf(“x[%2d] = %5.2f\n”, i+1, x[i] );
printf(“\nTotal = %.2f\n”, total);
}
Output
Enter 10 real numbers
1.2 2.4 4.2 3.5 5.2 2.3 1.4 4.2 3.1 6.7
X[1] = 1.2
X[2] = 2.4
X[3] = 4.2
X[4] = 3.5
X[5] = 5.2
X[6] = 2.3
X[7] = 1.4
X[8] = 4.2
X[9] = 3.1
X[10] = 6.7
Total = 34.2
After an array is declared, its elements must be initialized. An array can be initialized at either
of the following stages
● At compile time
● At run time
COMPILE TIME INITIALIZATION
We can initialize the elements of arrays in the same way as the ordinary variables when they are
declared. The general form of initialization of arrays is
The values in the list are separated by commas. For example, the statement
will declare the variable number as an array of size 3 and will assign zero to each element. If the
number of values in the list is less than the number of elements, then only that many elements
will be initialized. The remaining elements will be set to zero automatically. For instance,
will initialize the first three elements to 0.0, 15.3 and -10.0 and the remaining two elements to
zero.
In some cases size may be omitted, then the compiler allocates enough space for all initialized
elements. For example int counter[ ] = { 1, 1, 1, 1 }; will declare the counter array to contain
four elements with initial values 1. This approach works fine as long as we initialize every
element in the array. Character arrays may be initialized in a similar manner. Thus, the statement
Declares the name to be an array of five characters, initialized with the string “JOHN” ending
with the null character. Alternatively, we can assign the string literal directly as under
Compile time initialization may be partial. That is the number of initializers may be less than the
declared size. In such cases the remaining elements are initialized to zero, if the array type is
numeric and NULL if the type is char. For example int number [5] = { 10, 20 }; will initialize
the first two elements to 10 and 20 respectively and the remaining elements to 0. Similarly the
declaration char city [5] = { ‘B’ }; will initialize the first element to “B” and the remaining four
to NULL. It is a good idea to declare the size explicitly, as it allows the compiler to do some
error checking. However if we have more initializers than the declared size, the compiler will
produce an error. That is the statement int number [3] = { 10, 20, 30, 40 }; will not work. It is
illegal in C.
An array can be explicitly initialized at run time. This approach is usually applied for initializing
large arrays. For example in the program segment
------
------
for ( i = 0 ; i < 100 ; i = i + 1)
{
if i < 50
sum[i] = 0.0;
else
sum[i] = 1.0;
}
-----
-----
The first 50 elements of the array sum are initialized to zero while the remaining elements are
initialized to 1.0 at run time. Also by using scanf statement we can initialize an array. For
example the statements int x[3];
scanf(“%d%d%d”, &x[0], &x[1], &x[2]);
will initialize array elements with the values entered through the keyboard.
TWO-DIMENSIONAL ARRAYS
In one-dimensional array, a list of values can be stored. To store a table of values we use
two-dimensional array. Consider the following data table, which shows the value of sales of three
items by four sales girls:
The table contains a total of 12 values in four rows and three columns. To represent sales of item
3 by salesgirl#2 in C we shall use v[4][3], where v is the array name.
Two-dimensional arrays may be initialized by the declaration with a list of initial values enclosed
in braces. For example int table[2][3] = { 0, 0, 0, 1, 1, 1 }; initializes the elements of the first
row to zero and the second row to one. The initialization is done row by row. The above
statement can be equivalently written as int table [2][3] = {
{0, 0, 0},
{1, 1, 1}
};
Note the syntax of the above statements. Commas are required after each brace that closes off a
row, except in the case of the last row.
When the array is completely initialized with all values, explicitly, we need not specify the size
of the first dimension. For example int table [ ] [3] = {
{0, 0, 0},
{1, 1, 1}
}; is also permitted.
If the values are missing in an initializer, they are automatically set to zero. For instance the
statement int table [2][3] = {
{1,1},
{2}
}; this will initialize the first two elements of the first
row
to one, the first element of the second row to two and all other elements to zero.
When all the elements are to be initialized to zero, the following short-cuts may be used.
int m [3] [5] = { {0}, {0}, {0} }; or int m [3] [5] = { 0, 0 };
Program: A survey to know the popularity of four cars (Ambassador, Fiat, Dolphin and
Maruti) was conducted in four cities (Bombay, Calcutta, Delhi and Madras). Each person
surveyed was asked to give his city and the type of car he was using. The results, in coded form
are tabulated as follows
M 1 C 2 B 1 D 3 M 2 B 4
C 1 D 3 M 4 B 2 D 1 C 3
D 4 D 4 M 1 M 1 B 3 B 3
C 1 C 1 C 2 M 4 M 4 C 2
D 1 C 2 B 3 M 1 B 1 C 2
D 3 M 4 C 1 D 2 M 3 B 4
main()
{
int i, j, car;
int frequency [5] [5] = { {0}, {0}, {0}, {0}, {0} };
char city;
printf(“for each person, enter the city code \n”);
printf(“followed by the car code. \n”);
printf(“enter the letter x to indicate end. \n”);
for ( i = 1 ; i < 100 ; i++ )
{
scanf(“%c”, &city);
if (city == ‘x’ )
break;
scanf(“%d”, &car );
switch (city)
{
case ‘b’: frequency [1] [car]++;
break;
case ‘c’: frequency [2] [car]++;
break;
case ‘d’: frequency [3] [car]++;
break;
case ‘m’: frequency [4] [car]++;
break;
}
}
printf(“\n\n”);
printf(“popularity table\n\n”);
printf(“-------------------------------------------------\n“);
printf(“city Ambassador Fiat Dolphin Maruti \n”);
printf(“-------------------------------------------------\n“);
for ( i = 1 ; i <= 4 ; i++ )
{
switch (i)
{
case 1: printf(“Bombay “);
break;
case 2: printf(“Calcutta “);
break;
case 3: printf(“Delhi “);
break;
case 4: printf(“Madras “);
break;
}
for ( j = 1 ; j <= 4 ; j++ )
printf(“%7d”, frequency [i] [j] );
printf(“\n”);
}
printf(“------------------------------------------\n”);
Output
for each person, enter the city code
followed by the car code.
enter the letter x to indicate end.
M1C2B1D3M2B4
C1D3M4B2D1C3
D4D4M1M1B3B3
C1C1C2M4M4C2
D1C2B3M1B1C2
D3M4C1D2M3B4 X
Popularity table
------------------------------------------------------
City Ambassador Fiat Dolphin Maruti
------------------------------------------------------
Bombay 2 1 3 2
Calcutta 4 5 1 0
Delhi 2 1 3 2
Madras 4 1 1 4
------------------------------------------------------
MULTIDIMENSIONAL ARRAYS
C allows arrays of three or more dimensions. The exact limit is determined by the compiler. The
general form of a multidimensional array is
The array survey may represent a survey may represent a survey data of rainfall during the last
three years from January to December in five cities.
If the first index denotes year, the second city and the third month, then the element survey [2]
[3] [10] denotes the rainfall in the month of October during the second year in city-3.
Month
1 2 …………… 12
City
1
.
.
Year 1 .
.
5
Month
1 2 …………… 12
City
1
.
.
Year 2 .
.
5
Month
1 2 …………… 12
City
1
Year 3 .
.
.
.
5
ANSI C does not specify any limit for array dimension. However most compilers permit seven to
ten dimensions, some allow even more.
--------------------------------------unit3over-------------------------------------------------------------------
-