Sunteți pe pagina 1din 42

MODULE 2

MCA- 105 Structured Programming in C

ADMN
2014-17

2.1 OPERATORS INTRODUCTION


An operator is a symbol which helps the user to command the computer to do a certain mathematical
or logical manipulations. They are used in programs to manipulate data and variables. C has
a rich set of operators which can be classified as:
1. Arithmetic operators
2. Relational Operators
3. Logical Operators
4. Assignment Operators
5. Increments and Decrement Operators
6. Conditional Operators
7. Bitwise Operators
8. Special Operators
All the basic arithmetic operations can be carried out in C. All the operators have almost the
same meaning as in other languages. Both unary and binary operations are available in C language.
Unary operations operate on a single operand; therefore the number 5 when operated by unary will
have the value 5.

2.1.1 ARITHMETIC OPERATORS


Operator
+

*
/
%

Meaning
Addition or Unary Plus
Subtraction or Unary Minus
Multiplication
Division
Modulus Operator

(Table: 2.1)
Examples of arithmetic operators are
x+y
x-y
-x + y
a*b+c
-a * b
etc.,
Here a, b, c, x, y are known as operands. The modulus operator is a special operator in C
language which evaluates the remainder of the operands after division. It acts only on integer
operands.
Dept.of Computer Science And Applications, SJCET, Palai
Page 34

MODULE 2
MCA- 105 Structured Programming in C

ADMN
2014-17

2.1.1.1 INTEGER ARITHMETIC


When an arithmetic operation is performed on two whole numbers or integers than such an
operation is called as integer arithmetic. It always gives an integer as the result. Let x = 27and y = 5
be 2 integer numbers. Then the integer operation leads to the following results.
x+y = 32
x y = 22
x * y = 115
x%y=2
x/y=5
In integer division the fractional part is truncated.
2.1.1.2 FLOATING POINT ARITHMETIC
When an arithmetic operation is preformed on two real numbers or fraction numbers such an
operation is called floating point arithmetic. Operands will assume either decimal or exponential
notation. The floating point results can be truncated according to the properties requirement. The
remainder operator (%) is not applicable for floating point arithmetic operands.
Let x=14.0 and y=4.0 then
x+y=18.0
x-y=10.0
x*y=56.0
x/y=3.50
2.1.1.3 MIXED MODE ARITHMETIC
When one of the operand is real and other is an integer and if the arithmetic operation is
carried out on these 2 operands then it is called as mixed mode arithmetic. If anyone operand is of
real type then the result will always be real thus 15/10.0 = 1.5

2.1.2 RELATIONAL OPERATORS


Often it is required to compare the relationship between operands and bring out a
decision and proceed accordingly. This is when the relational operator comes into picture. C supports
the following relational operators.
Operator
Meaning
< is less l less than
<= is less less than or equal to
> is great greater than
>= is great greater than or equal to
!= is not e not equal to
== is equa equal to
Dept.of Computer Science And Applications, SJCET, Palai
Page 35

MODULE 2
MCA- 105 Structured Programming in C

ADMN
2014-17

(Table: 2.2)
It is required to compare the marks of 2 students, salary of 2 persons; we can compare them
using relational operators. A simple relational expression contains only one relational operator and
takes the following form.
exp1 relational operator exp2
Where exp1 and exp2 are expressions, which may be simple constants, variables or
combination of them. Given below is a list of examples of relational expressions and evaluated
values.
6.5<=25
TRUE
-65>0
FALSE
10 < 7 + 5
TRUE
The value of a relational expression will be 0 if the expression is false and it will be 1 if the
expression is true. Relational expressions are used in decision making statements of C language such
as if, while and for statements to decide the course of action of a running program.

2.1.3 LOGICAL OPERATORS


Logical operators are used when we want to test more than one condition and make decision.
It combines 2 or more relational expressions. The value of a logical expression will be 0 if the
expression is false and it will be 1 if the expression is true.
Operator
&&
||
!

Meaning
Logical AND
Logical OR
Logical NOT
(Table: 2.3)

2.1.3.1 LOGICAL AND (&&)


This operator is used to evaluate 2 conditions or expressions with relational operators
simultaneously. If both the expressions to the left and to the right of the logical operator is true then
the whole compound expression is true.
EXAMPLE:
a > b && x = = 10
The expression to the left is a > b and that on the right is x == 10 the whole expression is true
only if both expressions are true i.e., if a is greater than b and x is equal to 10.

Dept.of Computer Science And Applications, SJCET, Palai


Page 36

MODULE 2
MCA- 105 Structured Programming in C

ADMN
2014-17

2.1.3.2 LOGICAL OR (||)


The logical OR is used to combine 2 expressions or the condition evaluates to true if any one
of the 2 expressions is true.
EXAMPLE :
a < m || a < n
The expression evaluates to true if any one of them is true or if both of them are true. It
evaluates to true if a is less than either m or n and when a is less than both m and n.
2.1.3.3 LOGICAL NOT (!)
The logical not operator takes single expression and evaluates to true if the expression is false
and evaluates to false if the expression is true. In other words it just reverses the value of the
expression.
EXAMPLE :
! (x >= y) the NOT expression evaluates to true only if the value of x is
neither greater than or equal to y

2.1.4 ASSIGNMENT OPERATOR(=)


General for of a statement containing assignment operator is:
variable_name=expression;
The value of expression is evaluated and the content of the location variable_name is replaced
by expression value. Operand to left of assignment operator should be a variable and its right operand
can be any arbitrary expression.
EXAMPLE:
x=a+b
Here the value of a + b is evaluated and substituted to the variable x.
In addition, C has a set of shorthand assignment operators of the form.
var oper = exp;
Here var is a variable, exp is an expression and oper is a C binary arithmetic operator. The
operator oper = is known as shorthand assignment operator
EXAMPLE:
x + = 1 is same as x = x + 1 .
The commonly used shorthand assignment operators are as follows
simple assignment operator

shorthand assignment operator

Dept.of Computer Science And Applications, SJCET, Palai


Page 37

MODULE 2
MCA- 105 Structured Programming in C

a=a+1
a=a1
a = a * (n+1)
a = a / (n+1)
a=a%b

ADMN
2014-17

a += 1
a -= 1
a *= (n+1)
a /= (n+1)
a %= b
(Table: 2.4)

EXAMPLE
#define N 100
#define A 2
main()
{
int a;
a = A;
while (a < N)
{
printf(%d \n,a);
a *= a; //shorthand form of a = a * a
}
}
OUTPUT
2
4
16
If 2 operands in an assignment expression are of different types, the value of expression on
right hand side is automatically converted to the type of identifier on left. It is also possible to have
multiple assignments in a single line.
i=j=2;

2.1.5 INCREMENT AND DECREMENT OPERATORS


The increment and decrement operators are one of the unary operators which are very useful
in C language. They are extensively used in for and while loops. The syntax of the operators is given
below
++ variable name
variable name++
variable name
variable name

Dept.of Computer Science And Applications, SJCET, Palai


Page 38

MODULE 2
MCA- 105 Structured Programming in C

ADMN
2014-17

The increment operator ++ adds the value 1 to the current value of operand and the decrement
operator subtracts the value 1 from the current value of operand. ++variable name and variable
name++ mean the same thing when they form statements independently, they behave differently
when they are used in expression on the right hand side of an assignment statement.
Consider the following
m = 5;
y = ++m; (prefix)
In this case the value of y and m would be 6
Suppose if we rewrite the above statement as
m = 5;
y = m++; (post fix)
Then the value of y will be 5 and that of m will be 6. A prefix operator first adds 1 to the
operand and then the result is assigned to the variable on the left. On the other hand, a postfix
operator first assigns the value to the variable on the left and then increments the operand.

2.1.6 CONDITIONAL OR TERNARY OPERATOR


The conditional operator consists of 2 symbols the question mark (?) and the colon (:).The
syntax for a ternary operator is as follows
exp1 ? exp2 : exp3
Here exp1 is evaluated first. If the expression is true then exp2 is evaluated & its value
becomes the value of the expression. If exp1 is false, exp3 is evaluated and its value becomes the
value of the expression. Note that only one of the expressions is evaluated.
EXAMPLE:
a = 10;
b = 15;
x = (a > b) ? a : b
Here x will be assigned to the value of b. The condition follows that the expression is false
therefore b is assigned to x.
EXAMPLE :
//to find the maximum value using conditional operator)
#include <stdio.h>
void main()
{
int i,j,larger;
printf (Input 2 integers : );
Dept.of Computer Science And Applications, SJCET, Palai
Page 39

MODULE 2
MCA- 105 Structured Programming in C

ADMN
2014-17

scanf(%d %d,&i, &j);


larger = i > j ? i : j;
printf(The largest of two numbers is %d \n, larger);
}
OUTPUT
Input 2 integers : 34 45
The largest of two numbers is 45

2.1.7 BITWISE OPERATORS


C has a distinction of supporting special operators known as bitwise operators for
manipulation data at bit level. A bitwise operator operates on each bit of data. Those operators are
used for testing, complementing or shifting bits to the right on left. Bitwise operators may not be
applied to a float or double.
2.1.7.1 BITWISE AND(&)
The bitwise-AND operator compares each bit of its first operand to the corresponding bit of
its second operand. If both bits are 1, the corresponding result bit is set to 1. Otherwise, the
corresponding result bit is set to 0.
EXAMPLE:

01001000 &
10111000 =
---------------00001000

2.1.7.2 BITWISE OR(|)


The bitwise-inclusive-OR operator compares each bit of its first operand to the corresponding
bit of its second operand. If either bit is 1, the corresponding result bit is set to 1. Otherwise, the
corresponding result bit is set to 0.
EXAMPLE

01001000 |
10111000 =
---------------11111000

2.1.7.3 BITWISE XOR(^)

Dept.of Computer Science And Applications, SJCET, Palai


Page 40

MODULE 2
MCA- 105 Structured Programming in C

ADMN
2014-17

The bitwise-exclusive-OR operator compares each bit of its first operand to the corresponding
bit of its second operand. If one bit is 0 and the other bit is 1, the corresponding result bit is set to 1.
Otherwise, the corresponding result bit is set to 0.
EXAMPLE:

01110010 ^
10101010
--------------11011000

2.1.7.4 BITWISE COMPLEMENT(~)


The ~ (tilde) operator performs a bitwise complement on its single integer operand (unary
operator), which inverts all the bits represented by its operand.ie,0s become 1s and 1s become 0s.
EXAMPLE: x= 1001 0110 1100 1011
~x= 0110 1001 0011 0100
2.1.7.5 BITWISE LEFT SHIFT(<<)
Format is: op<<n where op is the integer expression that is to be shifted and n is the number
of bit positions to be shifted. The left-shift operation causes all the bits in the operand op to be shifted
to the left by n positions by removing n bits from the left side of integer and adding n 0s to the
right side.
EXAMPLE:

x=
1001 0110 1100 1011
x<<4= 0110 1100 1011 0000

2.1.7.6 BITWISE RIGHT SHIFT(>>)


Format is: op>>n where op is the integer expression that is to be shifted and n is the number
of bit positions to be shifted.The right-shift operation causes all the bits in the operand op to be
shifted to the right by n positions by removing n bits from the right side of integer and adding n 0s
to the left side.
EXAMPLE:
x=
1001 0110 1100 1011
x>>4=0000 1001 0110 1100

2.1.8 SPECIAL OPERATORS


C supports some special operators of interest such as comma operator, size of operator, pointer
operators (& and *) and member selection operators (. and ->). The size of and the comma operators
are discussed here. The remaining operators are discussed in forth coming chapters.

Dept.of Computer Science And Applications, SJCET, Palai


Page 41

MODULE 2
MCA- 105 Structured Programming in C

ADMN
2014-17

2.1.8.1 THE COMMA OPERATOR


The comma operator can be used to link related expressions together. Comma-linked, lists of
expressions are evaluated left to right and value of right most expression is the value of the combined
expression.
EXAMPLE:
value = (x = 10, y = 5, x + y);
First assigns 10 to x and 5 to y and finally assigns 15 to value. Since comma has the lowest
precedence in operators the parenthesis is necessary. Some examples of comma operator are in for
loops:
for (n=1, m=10, n <=m; n++,m++)
In while loops
while (c=getchar(), c != 10)
Exchanging values
t = x, x = y, y = t;
2.1.8.2 THE SIZE OF OPERATOR
The operator size of gives the size of the data type or variable in terms of bytes occupied in
the memory. The operand may be a variable, a constant or a data type qualifier.
EXAMPLE
m = sizeof (sum);
n = sizeof (long int);
k = sizeof (235L);
The size of operator is normally used to determine the lengths of arrays and structures when
their sizes are not known to the programmer. It is also used to allocate memory space dynamically to
variables during the execution of the program.
Example program that employs different kinds of operators. The results of their evaluation are also
shown in comparison
main()
{
int a, b, c, d;
a = 15; b = 10; c = ++a-b;
printf (a = %d, b = %d, c = %d\n, a,b,c);
d=b++ + a;
printf (a = %d, b = %d, d = %d\n, a,b,d);
printf (a / b = %d\n, a / b);
printf (a %% b = %d\n, a % b);
printf (a *= b = %d\n, a *= b);
Dept.of Computer Science And Applications, SJCET, Palai
Page 42

MODULE 2
MCA- 105 Structured Programming in C

ADMN
2014-17

printf (%d\n, (c > d) ? 1 : 0 );


printf (%d\n, (c < d) ? 1 : 0 );
}
Notice the way the increment operator ++ works when used in an expression. In the statement
c = ++a b; new value a = 16 is used thus giving value 6 to C. That is a is incremented by 1 before
using in expression. However in the statement d = b++ + a; the old value b = 10 is used in the
expression. Here b is incremented after it is used in the expression.
We can print the character % by placing it immediately after another % character in the control string.
This is illustrated by the statement.
printf(a %% b = %d\n, a%b);
This program also illustrates that the expression
c>d?1:0
Assumes the value 0 when c is less than d and 1 when c is greater than d.

2.2 TYPE CONVERSIONS IN EXPRESSIONS


2.2.1 IMPLICIT TYPE CONVERSION:
C permits mixing of constants and variables of different types in an expression. C
automatically converts any intermediate values to the proper type so that the expression can be
evaluated without losing any significance. This automatic type conversion is known as implicit type
conversion.
During evaluation it adheres to very strict rules and type conversion. If the operands are of
different types the lower type is automatically converted to the higher type before the operation
proceeds. The result is of higher type. The following rules apply during evaluating expressions: All
short and char are automatically converted to int then
1. If one operand is long double, the other will be converted to long double and result will be
long double.
2. If one operand is double, the other will be converted to double and result will be
double.
3.

If one operand is float, the other will be converted to float and result will be float.

4.

If one of the operand is unsigned long int, the other will be converted into unsigned long int
and result will be unsigned long int.

5.

If one operand is long int and other is unsigned int then

Dept.of Computer Science And Applications, SJCET, Palai


Page 43

MODULE 2
MCA- 105 Structured Programming in C

ADMN
2014-17

6.

a). If unsigned int can be converted to long int, then unsigned int operand will
be
converted as such and the result will be long int.
b). Else both operands will be converted to unsigned long int and the result will be
unsigned long int.
If one of the operand is long int, the other will be converted to long int and the result will be
long int.

7.

If one operand is unsigned int the other will be converted to unsigned int and the
result will be unsigned int.

2.2.2 EXPLICIT CONVERSION:


Many times there may arise a situation where we want to force a type conversion in a way that
is different from automatic conversion.
Consider for example the calculation of number of female and male students in a class.
Female students
Ratio =
Male students
If female students and male students are declared as integers, the decimal part will be
rounded off and its ratio will represent a wrong figure. This problem can be solved by converting
locally one of the variables to the floating point as shown below.
Ratio = (float) female students / male students;
The operator float converts the female students to floating point for the purpose of evaluation
of the expression. Then using the rule of automatic conversion, the division is performed by floating
point mode, thus retaining the fractional part of the result. The process of such a local conversion is
known as explicit conversion or coasting a value. The general form is,
(type_name) expression;

2.3 LIBRARY FUCNTIONS


Library functions carry out various commonly used operations or calculations. Some
functions return a data item to their access point, others indicate whether a condition is true or false
by returning 1 or 0 respectively, still others carry out specific operations on data items but do not
return anything. Features which tend to be computer dependent are generally written as library
functions. Functionally similar library functions are usually grouped together as object programs in
separate library files. These library files are supplied as a part of each C compiler.
A library function is accessed simply by writing the function name, followed by a list of
arguments that represent information being passed to the function. The arguments must be enclosed in
parentheses and separated by commas. The arguments can be constants,variable names or more
Dept.of Computer Science And Applications, SJCET, Palai
Page 44

MODULE 2
MCA- 105 Structured Programming in C

ADMN
2014-17

complex expressions. The parentheses must be present, even if there are no arguments, A function
that returns a data item can appear anywhere within an expression in place of a constant or an
identifier. A function that carries out operations on data items but does not return anything can be
accessed simply by writing the function name, since this type of function reference constitutes an
expression statement.
In order to use a library function it may be necessary to include certain specific information
within the main portion of the program. This information is generally stored in special files supplied
with the compiler. Thus, the required information can be obtained simply by accessing these special
files. This is accomplished with the preprocessor statement.
# include <filename>
The list of some commonly used library functions are:
abs(i) to determine absolute value of i.
exp(i) raise e to the power i.
log(d) determine natural logarithm of d.
pow(d1,d2) returns d1 raised to the d2 power
putchar(c) send a character to the standard output device
sqrt(d) return the square root of d.

2.4 DATA INPUT AND OUTPUT STATEMENTS


In any programming language, the interface forms a very important part. It deals with taking
data from the user and displaying back the output. For this purpose, we require the input-output
operations.
Reading, processing, and writing of data are the three essential functions of a computer
program. The input operation involves movement of data from an input device to computer memory,
while in output operation the data moves from memory to output device (generally screen).
In C the input and output is performed through a set of library functions that are supplied with
every C compiler. The set of library functions that perform input-output operations is known as
standard I/O library.
There are several header files that provide necessary information in support of various library
functions. These header files are included in the program using #include directive at the beginning of
the program. Each program that uses a standard input/output function must contain the statement
#include <stdio.h> at the beginning. However, there might be exceptions. For example, this is not
necessary for the functions printf and scanf which have been defined as part of the C language.
Dept.of Computer Science And Applications, SJCET, Palai
Page 45

MODULE 2
MCA- 105 Structured Programming in C

ADMN
2014-17

The file name stdio.h is an abbreviation for standard input -output header file. The instruction
#include <stdio.h> tells the compiler to search for a file named stdio.h and place its contents at this
point in the program. The contents of the header file become part of the source code when it is
compiled.

2.4.1 SINGLE CHARACTER INPUT OUTPUT:


The simplest of all input/output operations is reading a character from the standard input
unit (usually the keyboard) and writing it to the standard output unit (usually the screen). Reading a
single character can be done by using the function getchar. The getchar takes the following form:
variable_name = getchar();
variable_name is a valid C name that has been declared as char type. When this statement is
encountered, the computer waits until a key is pressed and then assigns this character as a value to
getchar function. Since getchar is used on the right-hand side of an assignment statement, the
character value of getchar is in turn assigned to the variable name on the left.
EXAMPLE:
char name;
name = getchar();
Will assign the character 'H' to the variable name when we press the key H on the keyboard.
Since getchar is a function, it requires a set of parentheses as shown.
The putchar function which in analogous to getchar function can be used for writing characters one
at a time to the output terminal. The general form is
putchar (variable name);
Where variable is a valid C type variable that has already been declared
EXAMPLE:
putchar ( c);
Displays the value stored in variable C to the standard screen.
Program shows the use of getchar function in an interactive environment.
#include < stdio.h >
void main ( )
{
char in;
printf ( please enter one character);
in = getchar ( ) ;
Dept.of Computer Science And Applications, SJCET, Palai
Page 46

MODULE 2
MCA- 105 Structured Programming in C

ADMN
2014-17

putchar (in);
}
C supports testing of the character keyed in by the user by including the file ctype.h & the
functions which can be used after including this file are:
isalnum(c) Is c an alphanumeric character?
isalpha(c) Is c an alphabetic character?
isdigit(c) Is c a digit?
islower(c)Is c a lower case character?
isprint(c)Is c a printable character?
ispunct(c)Is c a punctuation mark?
isspace(c)Is c a white space character?
isupper(c) Is c a upper case character?

2.4.2 STRING INPUT AND OUTPUT:


The gets function recieves the string from standard input device while puts outputs the string
to the standard output device. A string is an array or set of characters. The function gets accepts the
name of the string as a parameter, and fills the string with characters that are input from the keyboard
till newline character is encountered. (That is till we press the enter key). The puts function displays
the contents stored in its parameter on the standard screen.
The standard form of the gets function is
gets (str); where str is a string variable.
The standard form for the puts character is
puts (str); where str is a string variable.
The above statement will display the value stored in str on the output device
Eample program (Involving both gets and puts)
# include < stdio.h >
void main ( )
{
char s [80];
printf (Type a string less than 80 characters:);
gets (s);
printf (The string types is:);
puts(s);
}

2.4.3 FORMATTED INPUT


Dept.of Computer Science And Applications, SJCET, Palai
Page 47

MODULE 2
MCA- 105 Structured Programming in C

ADMN
2014-17

Formatted input refers to an input data that has been arranged in a particular format. For
example, consider the following data:
15.73 123 John
This line contains three pieces of data, arranged in a particular form. Such data has to be read
conforming to the format of its appearance. For example, the first part of the data should be read into
a variable float, the second into int, and the third part into char. This is possible in C using the scanf
function.
The general form of scanf is
scanf("control string", arg1, arg2,......argn);
The control string specifies the field format in which the data is to be entered and the
arguments arg1, arg2,.....argn specify the address of locations where the data is stored . Control
string and arguments are separated by commas.
Control string consist of:

Field specifications-Consists of conversion character %,data type character and an optional


number specifying field width

blanks tabs or new lines


Note; Data type character indicates type of data that is to be assigned to the variable associated with
corresponding argument
Inputting Integer Numbers
The field specification for reading an integer number is:
%wd
The percent (%) indicates a conversion specification follows.
w - integer number that specifies the field width of the number to be read and
d- known as data type character, indicates that the number to be read is in integer mode
EXAMPLE:

scanf(%2d %5d,&num1,&num2);
50
31246

Here 50 is assigned to num1 and 31246 is assigned to num2


If input data was 31426 and 50
31 is assigned to num1(since field width mentioned is 2) and
426 is assigned to num2
value 50 that is unread will be assigned to first variable in next scanf call.
These type of errors can be eliminated if we use field specification without field width.
Points to be noted:
Dept.of Computer Science And Applications, SJCET, Palai
Page 48

MODULE 2
MCA- 105 Structured Programming in C

ADMN
2014-17

input data items should be separated by spaces tabs or newlines. When scanf searches input
data line for a value to be read, it will always bypass white space characters.

input field may be skipped by specifying * in place of field width

EXAMPLE:
scanf(%d%*d%d,&a,&b);
let the input data be 123 456 789
Here 123 is assigned to a
456 is skipped(because of *)
789 to b
Inputting Real Numbers
Unlike integers numbers , the field width of real numbers is not to be specified and therefore
scanf reads real numbers using the simple specification %f for both the notations, namely, decimal
point notation and exponential notation. For example, the statement
scanf("%f %f %f , &x, &y , &z);
with the input data
472.34 43.21E-1 678
will assign the value 472.34 to x, 4.321 to y, and 678.0 to z. The input field specifications may
be separated by any arbitrary blank spaces.

Inputting Character Strings


We have already seen how a single character can be read from the terminal using the getchar
function. The same can be achieved using the scanf function also. In addition, a scanf function can
input strings containing more than one character strings:
%ws or %wc
The corresponding argument should be a pointer to a character array. However %c may be
used to read a single character when the argument is a pointer to a char variable. Some versions of
scanf supports the following conversion specification for strings
%[characters]
%[^characters]
The specification %[characters] means that only the character specified within the brackets
are permissible in the input string. If the input string contains any other character the string will be
terminated at the first encounter of such a character.
Dept.of Computer Science And Applications, SJCET, Palai
Page 49

MODULE 2
MCA- 105 Structured Programming in C

ADMN
2014-17

The specification %[^characters] does exactly the reverse. That is, the characters specified
after the (^) are not permitted in the input string. The reading of the string will be terminated at the
encounter of one of these characters.
Reading Mixed Data Types
It is possible to use one scanf statement to input a data line containing mixed mode data. In
such cases care should be given to ensure that input data items match the control specifications in
order and type. When an attempt is made to read an item that doesnt match the type expected the
scanf function doesnt read any further and immediately returns the value read.
EXAMPLE;
scanf(%d%c%f%s,&count,&code,&ratio,name);
will read data 15 p 1.24 xyz
correctly and assign the values to variables in the order in which they appear.
scanf Format Codes:
%c reads a single character
%d read a decimal integer
%e read a floating point value
%f read a floating point value
%g read a floating point value
%h read a short integer
%i read a decimal, hexadecimal, or octal integer
%o read an octal integer
%s read a string
%u read an unsigned decimal integer
%x read a hexadecimal integer
%[..] read a string of word(s)
The following letters may be used as prefixes for certain conversion character
h for short integers
l for long integers or doubles
L for long double

2.4.4 FORMATTED OUTPUT


printf() is a versatile function. It can handle any basic data type, that offers several features
with which you can specify the way in which data must be displayed.printf() performs formatted o/p
to standard o/p device. It provides features that can be used to control the alignment and spacing of
print-outs on terminals.
printf(control string,arg1.arg2,argn);
Dept.of Computer Science And Applications, SJCET, Palai
Page 50

MODULE 2
MCA- 105 Structured Programming in C

ADMN
2014-17

Control string consists of 3 types of items:


1. Characters that will be printed on the screen as they appear
2. format specifications that define the o/p format for display of each item
3. escape sequence characters such as \n,\t and \b.
The control string indicates how many arguments follow and what their types are. The
arguments arg1,arg2..argn are the variables whose values are formatted and printed according to the
specifications of the control string. The arguments should match in number, order and type with
format specifications. A simple format specification has the following form:
%w.p type-specifier
where w is an integer number that specifies the total number of columns for the output value
and p is another integer number that specifies the number of digits to the right of the decimal point or
the number of characters to be printed from a string.Both w and p are optional.
Output of Integer Numbers
The format specification for printing an integer number is:
%wd
where w specifies the minimum field width for the output. However if a number is greater
than the specified field width, it will be printed in full overriding the minimum specification. d
specifies that the value to be printed is an integer. The number will be printed right justified in the
given field width.
EXAMPLE:

printf(%6d,9876);

Here the value is displayed right justified.


It is possible to force printing to be left-justified by placing minus sign directly after % character
EXAMPLE: printf(%6d,9876);
9
8
6
7
Output of Real Numbers
The output of a real number may be displayed in decimal notation by using the following
format specification:
%w.pf
The integer w indicates the minimum number of positions that are to be used for the display of
value and the integer p indicates the no:of digits to be displayed after decimal point (precision).The
default precision is 6 decimal places.

Dept.of Computer Science And Applications, SJCET, Palai


Page 51

MODULE 2
MCA- 105 Structured Programming in C

ADMN
2014-17

We can also display a real number in exponential notation by using the specification:
%w.pe
The field width w should satisfy the condition w>=p+7
The display takes the form: [-]m.nnnne[+-]xx
EXAMPLE: let y=-98.7654
printf(%11.4e,y) will display

9 .

8 7 6 5 e + 0 1

Specifier Meaning
%c Print a character
%d Print a Integer
%i Print a Integer
%e Print float value in exponential form.
%f Print float value
%g Print using %e or %f whichever is smaller
%o Print actual value
%s Print a string
%x Print a hexadecimal integer (Unsigned) using lower case a F
%X Print a hexadecimal integer (Unsigned) using upper case A
F
%a Print a unsigned integer.
%p Print a pointer value
%hx hex short
%lo octal long
%ld long

2.5 CONTROL STATEMENT: BRANCHING


A C program is a set of statements which are normally executed sequentially in the order in
which they appear. This happens when no options or no repetitions of certain calculations are
necessary. However there are a number of situations in which we need to change the order of
execution of statements based on certain conditions, or repeat a group of statements until certain
specified conditions are met. This involves a kind of decision making to see whether a particular
condition has occurred or not and then direct the computer to execute certain statements accordingly.
C language posses such decision-making capabilities by supporting the following statements:
1.if statement
2.switch statement
3.Conditional operator statement
Dept.of Computer Science And Applications, SJCET, Palai
Page 52

MODULE 2
MCA- 105 Structured Programming in C

ADMN
2014-17

4.goto statement.

2.5.1 DECISION MAKING WITH IF STATEMENT


The if statement is a powerful decision-making statement and is used to control the flow of
execution of statements. It is basically a two-way decision statement and is used in conjunction with
an expression. It takes the following form:
if(test expression)
It allows the computer to evaluate the expression first and then depending on whether the
expression is true or false, it transfers the control to a particular statement. This point of program has
two paths to follow, one for the true condition and other for the false condition.
Entry
False
test exp ?
True
fig 2.1
2.5.1.1 SIMPLE IF STATEMENT
The general form of simple if statement is
if (test expression)
{
statement-block; ;
}
statement-x;
The statement-block may be a single statement or a group of statements. If the test expression is
true, the statement-block will be executed; otherwise the statement-block will be skipped and
execution will jump to statement-x .If the condition is true both statement-block and statement-x
are executed in sequence.

True

Dept.of Computer Science And Applications, SJCET, Palai

False

Page 53

MODULE 2
MCA- 105 Structured Programming in C

ADMN
2014-17

Test exp
statement-block
False
statement-x
next statement
fig 2.2
EXAMPLE:
-----------------------if (category==sports)
{
marks=marks+bonus_marks;
}
printf(%f,marks);
.
2.5.1.2 IF ELSE STATEMENT
if (test expression)
{
True-block statement ;
}
else
{
False-block statement;
}
statement-x;
If the test expression is true then the true-block statements immediately following the if
statements are executed. Otherwise the false-block statements are executed. In either case,either true
-block or false-block will be executed, not both. In both cases, the control is transferred to statementx.
EXAMPLE:
..

if(code==1)
boy=boy+1;
else
girl=girl+1;

Dept.of Computer Science And Applications, SJCET, Palai


Page 54

MODULE 2
MCA- 105 Structured Programming in C

true

ADMN
2014-17

false
test exp

true-block stmts

false-block stmts

statement x
fig 2.3
2.5.1.3 NESTING OF IF ELSE STATEMENTS
When a series of decisions are involved, we may have to use more than one if else
statement in nested form as follows:
if(test condition1)
{
if (test condition 2)
{
Statement 1;
}
else
{
Statement 2;
}
}
else
{
Statement 3;
}
statement x;
EXAMPLE:
.
if(sex ==female)
{
if(balance>5000)
bonus=.05*balance;
else
bonus=.02*balance;
}
else
{
bonus=.01*balance;
Dept.of Computer Science And Applications, SJCET, Palai
Page 55

MODULE 2
MCA- 105 Structured Programming in C

ADMN
2014-17

}
balance=balance+ bonus;
..
The logic of execution is in figure. If the condition1 is false, the statement3 will be executed;
otherwise it continues to perform the second test. If the condition 2 is true, the statement1 will be
evaluated; otherwise the statement2 will be evaluated and then the control is transferred to the
statement x.
Entry

False

Test
Condition
1
Fals
e

Stateme
nt3

Stateme
nt2

True

Test
Condition
2

Stateme
nt1

True

Statement
x

Next
Statement

(Fig: 2.4)
2.5.1.4 The ELSE IF LADDER
There is another way of putting ifs together when multipath decisions are involved. A
multipath decision is a chain of ifs in which the statement associated with each else is an if. It takes
the following general form:
if (condition 1)
{
Statement 1;
}
else if(condition 2)
{
Statement 2;
Dept.of Computer Science And Applications, SJCET, Palai
Page 56

MODULE 2
MCA- 105 Structured Programming in C

ADMN
2014-17

.
}
else if(condition n)
{
Statement n;
}
else
default statement;
Statement x;
The conditions are evaluated from the top (of the ladder), downwards. As soon as a true
condition is found, the statement associated with it is executed and the control is transferred to the
statement-x (skipping the rest of the ladder). When all the n conditions become false, then the final
else containing the default-statement will be executed.

Dept.of Computer Science And Applications, SJCET, Palai


Page 57

MODULE 2
MCA- 105 Structured Programming in C

ADMN
2014-17

entry
true
cond1
stmt 1

false
false

true
cond2
true

stmt 2

false
cond3

stmt 3

true

false
condn

stmt n

default stmt

stmt -x

next stmt

fig 2.5

2.5.2.SWITCH STATEMENT
When one of the many alternatives is to be selected, we can use an if statement to control the
selection. However the complexity of such a program increases when the number of alternative
increases. The program becomes difficult to read and follow. In C there is a built-in multi way
decision statement known as switch. The switch tests the value of a variable(or expression) against a
list of case values and when a match is found ,block of statements associated with that case is
executed.
Syntax :switch(expression)
{
Dept.of Computer Science And Applications, SJCET, Palai
Page 58

MODULE 2
MCA- 105 Structured Programming in C

ADMN
2014-17

case value-1:
block-1
break;
case value-2:
block-2
break;
------------------default:
default-block
break;
}
statement x;
The expression is an integer expression or characters.Value-1,value-2are constants or
constant expressions and are known as case labels. Each of these values should be unique within a
switch statement.block-1,block-2.. are statement lists and may contain zero or more statements.
There is no need to put braces around these blocks. Note that case labels end with a colon(:).
When the switch is executed, the value of the expression is compared against the values of
Value-1,value-2If a case is found whose values match with the value of the expression, then the
block of statements that follows the case are executed.
The break statement at the end of each block signals the end of a particular case and causes
an exit from the switch statement, transferring the control to the statement following the switch.The
default is an optional case. When present, it will be executed if the value of the expression doesnt
match with any of the case values. If not present no action takes place if all matches fail and the
control goes to the statement-x.
EXAMPLE:
switch(c)
{
case + : printf(Enter the values for a & b\n);
scanf(%d %d,&a,&b);
printf(a + b = %d\n,a+b);
break;
case - : printf(Enter the values for a & b\n);
scanf(%d %d,&a,&b);
printf(a - b = %d\n,a-b);
break;
Dept.of Computer Science And Applications, SJCET, Palai
Page 59

MODULE 2
MCA- 105 Structured Programming in C

ADMN
2014-17

case * : printf(Enter the values for a & b\n);


scanf(%d %d,&a,&b);
printf(a * b = %d\n,a*b);
break;
case / : printf(Enter the values for a & b\n);
scanf(%d %d,&a,&b);
printf(a / b = %d\n,a/b);
break;
default : printf(Invalid operator\n);
}
2.5.2.1 NESTED SWITCH () CASE
C supports the nested switch() statements. The inner switch() can be a part of an outer
switch().the inner and outer switch() case constants may be same. No conflict arises even if they are
same.
Program to detect whether the entered number is even or odd. Use nested switch() case
statements.
void main()
{
int x,y;
printf(Enter a number);
scanf(%d,&x);
switch(x)
{
case 0:
printf(Number is even);
break;
case 1:
printf(Number is odd);
break;
default:
y=x%2;
switch(y)
{
case 0:
printf(Number is even);
break;
default:
printf(Number is odd);
}
}
}
Dept.of Computer Science And Applications, SJCET, Palai
Page 60

MODULE 2
MCA- 105 Structured Programming in C

ADMN
2014-17

THE SWITCH () CASE AND NESTED IFS


Switch()
Nested ifs
The switch() can only test
The if can evaluate relational or logical expressions
for equality. only constant values are
applicable.
No two case statements have identical
Same conditions may be repeated for
Constants in the same switch
Number of times.
Character constants are automatically
Character constants are automatically converted to
converted to integers
integers
In switch()case statement nested
In nested if statement switch() case can be used
If can be used
(Table: 2.5)

2.5.3 THE GOTO STATEMENT


The goto statement is used to alter the normal sequence of program execution by transferring
control to some other part of the program. it is useful to provide branching within a loop. It can be
used to exit out of a loop also.
while(test-condition 1)
{
if(condition 2)
goto stop;
Jump within ----------loop
if(condition 3)

goto abc;

Exit from
loop

--------abc:
------}
stop:
In its general form, the goto statement is written as
goto label;
Where label is an identifier that is used to label the target statement to which control will be
transferred.
Control may be transferred to any other statement within the program. The target statement
must be labeled, and the label must be followed by a colon. Thus the target statement will appear as
label: statement
Dept.of Computer Science And Applications, SJCET, Palai
Page 61

MODULE 2
MCA- 105 Structured Programming in C

ADMN
2014-17

Each labeled statement within the program must have a unique label; i.e., no two statements can have
the same label.
goto label;

label:
statement;
--------------------------goto label;

--------------------------label:
statement
Forward jump

Backward jump

If the label: is before the statement goto label; a loop will be formed and some statements will
be executed repeatedly. Such a jump is known as a backward jump. On the other hand, if the label: is
placed after the goto label; some statements will be skipped and the jump is known as a forward
jump.
A goto is often used at the end of a program to direct the control to go to the input statement,to
read further data.
Points to be remembered while using the goto statement:
The use of goto statement in a structured programming language like C should be
avoided. Use if and only if it is unavoidable
The goto statement may create an infinite loop where the computer enters a
permanent loop. The careful and cautious design would resolve such situations.
A program may contain any number of goto statements.
No two statements can have the same label.

goto jumps to be avoided


Write a C program to accept an integer number and reverse it
void main()
{
int number, rev=0, digit,temp_num;
printf(Enter a number\n);
scanf(%d,&number);
temp_num=number;
START:
Dept.of Computer Science And Applications, SJCET, Palai
Page 62

MODULE 2
MCA- 105 Structured Programming in C

ADMN
2014-17

digit=number%10;
rev=rev*10+digit;
number/=10;
if (number>0)
goto START;
printf(Input number=%5d\n,temp_num);
printf(Reversw number=%5d\n,rev);
}
OUTPUT
Enter a number
9876
Input number=9876
Reverse number=6789

2.6 DECISION MAKING AND LOOPING


In looping, sequences of statements are executed until some conditions for termination of the
loop are satisfied. 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 conditions and
then directs the repeated execution of the statements contained in the body of the loop.
A looping process, in general, would include the following four steps:
1. Setting and initialization of a condition variable
2. Execution of the statements in the loop
3. Test for a specified value of the condition variable for execution of the loop.
4. Incrementing or updating the condition variable
The test may be either to determine whether the loop has been repeated the specified number
of times or to determine whether a particular condition has been met.
Depending on the position 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. In the entry controlled
loop, the control conditions are tested before the start of loop execution. If the conditions are not
satisfied, then the body of the loop will not be executed .In the case of an exit-controlled loop, the test
is performed at the end of the body of the loop and therefore the body is executed unconditionally for
the first time. The entry-controlled and exit controlled loops are also known as pre-test and post-test
loops respectively.

Dept.of Computer Science And Applications, SJCET, Palai


Page 63

MODULE 2
MCA- 105 Structured Programming in C

ADMN
2014-17

The C language provides for three constructs for performing loop operations.They are:

The while statement


The do statement
The for statement

Based on the nature of control variable and the kind of value assigned to it for testing the
control expression, the loops may be classified into two general categories:

Counter-controlled loops
Sentinel-controlled loops

When we know in advance how many times a loop should be executed, we use a
counter controlled loop.We use a control variable called counter. The counter must be initialized,
tested and updated properly for desired loop operations.The no;of times the loop should be executed
may be constant or a variable that is assigned value. It is also called definite repetition loop
.EXAMPLE:
sum=0;
n=1;
while(n<=10)
{
sum=sum+n*n;
n=n+1;
}
Here this loop will be executed 10 times. The variable n is called counter or control variable.

Dept.of Computer Science And Applications, SJCET, Palai


Page 64

MODULE 2
MCA- 105 Structured Programming in C

ADMN
2014-17

In a Sentinel-Controlled loop, a special value called a sentinel value is used to change the loop
control expression from true to false. For example, when reading data we may indicate the "end of
data" by a special value, like -1 and 999. The control variable is called sentinel variable. A sentinelControlled loop is often called indefinite repetition loop because the number of repetitions is not
known before the loop begins executing
char character=;
while(character!=y)
{
character = getchar();
putchar(c);
}
Here the loop is executed as long as the key y is pressed. When Y is pressed the condition
becomes false the loop terminates and control transfers to the statement following the loop. Here the
value Y is called sentinel value and the variable character is called the sentinel variable.

2.6 .1 WHILE STATEMENT


The simplest of all the c looping structures in C is the while statement. The while statement is
an entry-controlled loop statement. The test condition is evaluated and if the condition is true then
the body of the loop is executed. After the execution of the body the test condition is once again
evaluated and if it is true, the body is executed once again. This process of repeated execution of the
body is continued until the test condition becomes false and the control is transferred out of the loop.
On exit the program is continued with the statement after 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. The format of while statement is :
while (test condition)
{
body of the loop
}
EXAMPLE:
x = 10;
while (x < 16)

-------------------------

Initialization
Test condition

{
printf("%d",x);

-------------

body of the loop

x = x+1;
}
Dept.of Computer Science And Applications, SJCET, Palai
Page 65

MODULE 2
MCA- 105 Structured Programming in C

ADMN
2014-17

PROGRAM:
# include<stdio.h>
main()
{
int count,n;
float x,y;
printf(Enter the values of x and n:);
scanf(%f %d, &x, &n);
y= 1.0;
count = 1;
/* LOOP BEGINS*/
while(count<= n)
{
y = y * n;
count ++;
}
/*End of loop*/
printf( x = %f ; n = %d ; to power n = %f n , x , n, y);
}

2.6 .2 DO STATEMENT
The do while loop is also a kind of loop, which is similar to the while loop in contrast to while
loop, the do while loop tests at the bottom of the loop after executing the body of the loop. Do is an
exit-controlled loop. Since the body of the loop is executed first and then the loop condition is
checked we can be assured that the body of the loop is executed at least once.
The syntax of the do while loop is:
do
{
statement;
}
while(expression);
Here the statement is executed, then expression is evaluated. If the condition expression is true
then the body is executed again and this process continues till the conditional expression becomes
false. When the expression becomes false the loop terminates. while loop says "Loop while the
condition is true, and execute this block of code", a do..while loop says "Execute this block of code,
and then continue to loop while the condition is true".
EXAMPLE:
void main()
{
int c;
Dept.of Computer Science And Applications, SJCET, Palai
Page 66

MODULE 2
MCA- 105 Structured Programming in C

ADMN
2014-17

do
{
printf(enter number);
scanf(%d,&c);
printf(%d\n,c);
} while (c>0);
}
Here the loop is executed at least once. Even if we are entering a value less than 0 at first time
itself, the loop will be executed once and then terminates. Or else the loop will be iterated as long as
the value of c is greater than 0

2.6.3 FOR LOOP


Syntax:
for (initialization ; test ; increment)
{
statements ;
}
Program flow
1.

The initialization of control variable is done first,using assignment statements like int i=0 or
count=0.The variables i and count are called loop control variable. int i=0,which creates a new
variable with initial value 0, to act as a counter. Multiple,
comma separated, expressions are
allowed in the initialization section. But declaration expressions may not be mixed with other
expressions.

2.

Value of the control variable is evaluated using test condition. It is a relational expression like
i<0 that determines when the loop will exit. If condition is true, body of the loop is executed,
Otherwise loop is terminated and execution will continue with statement that immediately follow
the loop.

3.

When the body of the loop is executed, the control is transferred back to the for statement
after evaluating last statement in loop control. Now the control variable is
incremented
using assignment statement such as i=i+1 and the new value is tested to check whether it
satisfies the test condition. If condition is satisfied body of the loop will be again executed. This
process continues till value of control variable fails to satisfy test condition.

EXAMPLE:

Dept.of Computer Science And Applications, SJCET, Palai


Page 67

MODULE 2
MCA- 105 Structured Programming in C

ADMN
2014-17

for(x=0;x<10;x=x+1)
{
printf(%d\n,x);
}
Here loop will be executed 10 times and the digits 0 to 9 will be printed. The 3 sections should be
separated by semicolon.
for statement allows negative increment also
EXAMPLE:
for(x=9;x>0;x=x-1)
{
printf(%d\n,x);
}

Here loop will be executed 10 times and the digits 9 to 0 will be printed.
Since we are checking condition at the beginning of loop, the body of loop may not be executed
if the condition fails at the start.
EXAMPLE:
for(x=9;x<9;x=x-1)
{
printf(%d\n,x);
}
The above loop will never be executed.
In for statement, initialization, testing and incrementing are placed in for statement itself making it
visible to programmers and users in one place.
Additional Features
More than one variable can be initialized and incremented at a time in a for loop.

for(n=1,m=50;n<=m;n=n+1,m=m-1)
{
p=m/n;
}
The test-condition may have any compound relation and the testing need not be limited only to
the loop control variable.
for(i=1;i<20 && sum<100;i++)
{
sum=sum+i;
Dept.of Computer Science And Applications, SJCET, Palai
Page 68

MODULE 2
MCA- 105 Structured Programming in C

ADMN
2014-17

printf(%d%d,i,sum);
}
It is permissible to use expressions in the assignment statements of initialization and increment
sections.
EXAMPLE:
for(x=(m+n)/2;x>0;x=x/2)
One or more sections of the for loop can be omitted ,if necessary
EXAMPLE:
m=0;
for(; m<100;)
{
printf(%d,m);
m=m+5;
}
We can set up time delay loops using for statement
EXAMPLE: for(j=0;j<1000;j++);
Here the semi colon at the end is known as null statement. Here the loop will be executed 1000
times without executing any output.
It is possible to use a scanf statement in for statement to assign value to the control variable
EXAMPLE: for(scanf(%d,&n);n>0;n=n/2)
2.6.3.1 NESTED FOR LOOPS
In some cases a set of statements which are repeated for a known number of times need to be
executed as long as a condition holds. In such case we will enclose this loop in another loop. The
enclosing loop is called Outer loop and the enclosed loop is called Inner loop.
for (i=0;i<5;i++)
{
-------Inner Loop
----------for(j=0;j<3;j++)
{
-----------------}

Outer Loop

Dept.of Computer Science And Applications, SJCET, Palai


Page 69

MODULE 2
MCA- 105 Structured Programming in C

ADMN
2014-17

}
EXAMPLE :Multiplication tables of a range of numbers
# include<stdio.h>
main ()
{
int m,n,i,j,p;
printf(enter the lower limit and upper limit\n);
scanf(%d%d,&m,&n);
for(i=m;i<=n;i++)
{
for(j=1;j<=10;j++)
{
p=i*j;
printf(%d,p);
printf();
}
printf(\n);
}
}
We need to generate multiplication table of the given range of numbers. So we need to nest
one loop within another. The outer loop is to select each number in the range and the inner loop is to
generate the multiplication table of the number selected by the outer loop.
In the outer loop when i takes m, the lower limit, the inner loop generates the multiplication
table of m. Once the inner loop completes, control goes to the outer loop again.i gets incremented it
becomes m+1.Then inner loop generates the multiplication table of m+1>this continues as long as the
test condition of outer loop is true.

2.7 BREAK AND CONTINUE STATEMENTS


C provides two commands to control how we loop

break

continue

2.7.1 THE BREAK STATEMENT:


The statements in a loop will be executed continuously as long as the test expression is true.
Sometimes while executing a loop it becomes desirable to skip a part of the loop or quit the loop as
soon as certain condition occurs. For example consider searching a particular number in a set of 100
numbers as soon as the search number is found it is desirable to terminate the loop. C language
Dept.of Computer Science And Applications, SJCET, Palai
Page 70

MODULE 2
MCA- 105 Structured Programming in C

ADMN
2014-17

permits a jump from one statement to another within a loop as well as to jump out of the loop. The
break statement allows us to accomplish this task. A break statement provides an early exit from for,
while, do and switch constructs. A break causes the innermost enclosing loop or switch to be exited
immediately.
A break statement used within a loop is expected to be associated with an if statement. When the
test expression of if statement evaluates to true, the loop is exited prematurely.
while(test-expression 1)
{
Statements-1;
If (test-expression 2)
break;
Statements-2;
}
During the course of iteration if the test expression-2 evaluates to true, The control reaches the
break statement and executes it causing the loop to be exited prematurely.
EXAMPLE :
# include<stdio.h>
main()
{
int n,i,sum=0,number;
printf(enter no;of elements\n);
scanf(%d,&n);
printf(enter numbers\n);
for(i=1;i<=n;i++)
{
scanf(%d,& number);
if(number<0)
break;
sum=sum+number;
}
printf(sum of %d positive numbers=%d,i-1,sum)
}
Here in the course of accepting numbers, if the positive numbers are entered, they are added to
the variable sum. But if a negative number is entered, then control reaches the break statement,
which, when executed causes the loop to be executed prematurely. The value of sum is then
displayed.

Dept.of Computer Science And Applications, SJCET, Palai


Page 71

MODULE 2
MCA- 105 Structured Programming in C

ADMN
2014-17

2.7.1.1 BREAK IN NESTED FOR LOOPS


In nested loops the break statement affects only the loop in which it is enclosed.
for(initialization1;test-condition1;increment1)
{
for(initialization2;test-condition2;increment2)
{
if(test-condition3)
break;
}
Statements;
}
Here on encountering break statement control will exit out of the inner for loop and continue with
the statements outside the inner loop.
for(initialization1;test-condition1;increment1)
{
for(initialization2;test-condition2;increment2)
{
Statements- 2;
}
if(test-condition3)
break;
}
Statements;
Here the break statement is enclosed in the outer for loop. On encountering the break statement the
control will exit out of outer for loop.

2.7.2CONTINUE STATEMENT
During loop operations it may be necessary to skip a part of the body of the loop under certain
conditions. Like the break statement C supports similar statement called continue statement. The
continue statement causes the loop to be continued with the next iteration after skipping any
statement in between. The format of the continue statement is simply:
continue;
Similar to the break statement ,continue statement is also associated with an if statement.
While(test-expression 1)
{
Statements-1;
if (test-expression 2)
Dept.of Computer Science And Applications, SJCET, Palai
Page 72

MODULE 2
MCA- 105 Structured Programming in C

ADMN
2014-17

continue;
Statements-2;
}
During the course of iteration if the test expression-2 evaluates to true, the control reaches the
continue statement ,the statement-2 are skipped for those iterations and the control goes to the
beginning of the loop. The loop is not prematurely exited as in the case of break statement
EXAMPLE
# include<stdio.h>
main()
{
int n,i,sum=0,number;
printf(enter no;of elements\n);
scanf(%d,&n);
printf(enter numbers\n);
for(i=1;i<=n;i++)
{
scanf(%d,& number);
if(number<0)
continue;
sum=sum+number;
}
printf(sum of %d positive numbers=%d,i-1,sum);
}
Here in the course of accepting numbers, if the positive numbers are entered, they are added to
the variable sum. But if a negative number is entered, then control reaches the continue statement,
which, when executed, causes the skipping of the statements following it within in the loop and
causes the control to be transferred back to the beginning of the loop, so that the loop continues with
the next iteration.
2.7.2.2 CONTINUE IN NESTED LOOPS
for(initialization1;test-condition1;increment1)
{
for(initialization2;test-condition2;increment2)
{
if(test-condition3)
continue;
}

Dept.of Computer Science And Applications, SJCET, Palai


Page 73

MODULE 2
MCA- 105 Structured Programming in C

ADMN
2014-17

Statements;
}
Here when test-condition 3 is true the continue statement is encountered control is transferred
to the next iteration of inner for loop skipping all the statements following continue in inner loop.
for(initialization1;test-condition1;increment1)
{
for(initialization2;test-condition2;increment2)
{
Statements- 2;
}
if(test-condition3)
continue;
}
Statements;

Differences between break and continue


Break

Continue

Can be used in switch statement

Cannot be used in switch statement

Causes premature exit of the loop


enclosing it

Causes skipping of the statements


following it in the body of the loop

The control is transferred to the


statement following the loop

Control is transferred back to the loop

The loop may not complete the


intended number of iterations

The loop completes the intended


number of iterations.

2.8 EXIT FUNCTION()


Exit function is defined in header file <stdlib.h>
Just as you can break out of a loop, you can break out of a program by using the standard
library function exit(). This function causes immediate termination of the entire program, forcing a
return to the operating system. In effect, the exit() function acts as if it were breaking out of the entire
program.
The general form of the exit() function is
if(test-condition)
exit(int return_code);
Dept.of Computer Science And Applications, SJCET, Palai
Page 74

MODULE 2
MCA- 105 Structured Programming in C

ADMN
2014-17

EXAMPLE:
# include<stdio.h>
# include<conio.h>
void main()
{
int num1,num2,res;
while(1)
{
scanf("%d%d",&num1,&num2);
if(num2==0)
exit(0);
else
{
res=num1/num2;
printf("result of division is %d\n",res);
}
}
}
Usually in our programs we will use exit(0) which indicates a normal termination of program.

Dept.of Computer Science And Applications, SJCET, Palai


Page 75

S-ar putea să vă placă și