You are on page 1of 40

C-Programming 1

OVERVIEW OF C
Importance of C

(1) C is a robust language whose rich set of built in functions and operators can be used to
write any complex programs.
(2) The C compiler combines the capabilities of an assembly language with the features of high level
language. Hence it is well suited for writing system software and business packages.
(3) Programs written in C are efficient and fast.
(4) Several standard functions are available which can be used for developing programs.
(5) C is highly portable i.e. C programs written for one computer can be run
on another with little or no modification.
(6) C language is well suited for structured programming.
(7) C has the ability to extend itself. A C program is basically a collection of functions that are
supported by C library and we can add our own functions to C library. With the availability of
large number of functions, the programming task becomes simpler.
Sample C Programs
Program to print a message
main ()
{
/* ----------------------- Printing begins ------------------------ */
printf (“Welcome to the World of C.”);
/* ----------------------- Printing ends -------------------------- */
}
 The first line informs the system that the name of the program is main and the execution begins at this
line. The main is the special function used by the C system to tell the computer where the program
starts. Every program must have exactly one main function.
 The empty pair of parenthesis immediately following main indicates than function main has no
arguments (or parameters).
 The opening ‘{‘ and the closing ‘}’ indicates the beginning and the end of the program respectively.
 All the statement between these two braces for the function body.
 The lines beginning with /* and ending with / are known as comment lines. Comments lines are used
to enhance the readability and understandability of a program. They are not executable statements and

Dept of Computer Science St Aloysius College, Mangalore.


C-Programming 2

therefore anything enclosed between /* */ is ignored by the compiler. Comment can be inserted
anywhere in the program .
 Every statement in C should end with a semicolon (;) mark.

Basic Structure of C programs


A C program may contain one or more sections as shown in figure
Documentation section
Link section
Definition section
Global declaration section
Main() Function section
{
Declaration Part;
Executable part;
}
Subprogram section
Function 1
Function 2 (user-defined functions)
.
.
Function n

Detail about each section


(1) Documentation section: This section consists of a set of comment lines giving the name of the
program, the author and other details which the programmer would like to use later.
(2) The Link section: The Link section provides instructions to the compiler to link functions from
system library.
(3) Definition section: This section defines all symbolic constants.
(4) Global declaration section: There are some variables that are used in more than one function,
such variables are called global variables and are declared in global declaration section that is
outside all functions.
(5) Main function section: Every C program must have one main function section. This section
contains two parts, declaration part and executable part. The declaration part declares all the

Dept of Computer Science St Aloysius College, Mangalore.


C-Programming 3

variables used in executable part. These two parts must appear between opening and closing
braces. All the statements in the declaration and executable part ends with a semicolon.
(6) The subprogram section: This section contains all the user defined functions that are called in
main function. User defined functions are generally placed after main function. They may appear
in any order.
All sections except the main function section may be absent when they are not required.
(for eg refer any example programmes)

CHAPTER 2: CONSTANTS, VARIABLES AND DATA TYPES

Character Set
The characters that can be used to form words, numbers and expressions depend upon the
computers on which the program is run.
The characters in C are grouped into the following categories:
(a) Letters:
Uppercase letters A ………………. Z
Lowercase letters a ……………….. z

(b) Digits:
All decimal digits 0 …………………… 9
(c) Special Characters
, Comma & ampersand . period
^ caret : semicolon * asterisk
: colon  minus ? question mark
+ plus ‘ apostrophe < Less than sign
“ quotation mark > greater than sign
! Exclamation mark | vertical bar
/ slash ( left parenthesis
) right parenthesis \ back slash
[ left bracket ] right bracket
~ tilde _ underscore
$ dollar sign { left brace
} right brace % percentage
# number sign

Dept of Computer Science St Aloysius College, Mangalore.


C-Programming 4

(d) White spaces


Blank space, horizontal tab, Carriage return, new line, Form feed

C Tokens
In a passage of text,individual words and punctuation marks are called tokens.
C has six types of tokens as shown following:

C CTOKENS

KW CoC Str STRINGS Spec SPECIAL


KEYWORDS CONSTANTS OPERATORS SYMBOLS

Float -15.5 “abs” +-*/


While 100 [] {}
IDENTIFIERS

amount
Keywords and Identifiers
Keywords:
Keywords serve as basic building blocks for program statements. All keywords have fixed
meanings and these meanings cannot be changed. They can be used only for the intended purposes.
All keywords can be written in lowercase.
Following is the list of keywords provided by C:
Auto else long typedef
Break enum register union
Case extern return unsigned
Char float short void
Continue for sizeof while
Default goto static
Do if struct

Dept of Computer Science St Aloysius College, Mangalore.


C-Programming 5

Double int switch

Identifiers
Identifiers are the names given to various program elements, such as variables, functions and
arrays.
Rules:
(1) Identifiers consist of letters and digits in any order, except that the first character must be
a letter.
(2) Identifiers can contain both uppercase and lowercase letters, but upper and lowercase
letters are not interchangeable i.e., a uppercase letter is not equivalent to corresponding
lowercase letter.
(3) The only character allowed is underscore ( _ ). Underscore is treated as a character.
(4) The underscore character should not be used as the first character of an identifier.
(5) Identifiers can be of any length.
(6) Must not contain any white spaces.
(7) Cannot use a keyword.
(8) Must consist of only letters, digits and underscore.
Examples: Area, Gross_salary, Root1, StudName etc.

Constants
Constants in C refer to fixed values that do not change during the execution of a program. C supports
several types of constants.
CONSTANTS

Numeric constants character constants.

Integer constants real constants single character string constants


constant
Integer constants: An integer constant refers to whole numbers. It can be specified in three ways:
(a) Ordinary decimal number (base 10).
(b) Octal numbers (base 8)
(c) Hexadecimal numbers (base 16)
An integer constant has to follow the following rules:

Dept of Computer Science St Aloysius College, Mangalore.


C-Programming 6

(1) It contains a sequence of digits from 0 to 9 for decimal numbers, 0 to 7 for octal
numbers and 0 to 9 and letters A-F or a –f for hexadecimal numbers.
Eg(decimal integer) : 123 -321 0
Eg(octal integer) : 037 0 0435 0551
Eg(hexadecimal integer) : 0X2 0X9F 0Xbcd
(2) An octal constant is preceded with ‘0’ and hexadecimal constant with 0X or 0x.
(3) No commas, spaces or other symbols are allowed in between.
(4) The integer can be either positive or negative. It may or may not be prefixed by a
sign.
(5) A size or sign qualifier can be appended at the end of the constant.
U or u for unsigned. S or s for signed. L or l for long.
Examples: 123, -31000, 0x2A, etc.
Floating pointing constant(Real constants): These are real numbers having a decimal point or an
exponential or both. The rules governing the floating point representation are:
(d) They have a decimal point and digits from 0 to 9.
(e) No embedded spaces, commas and other symbols are allowed.
(f) They may or may not be prefixed by a – sign.
(g) It is possible to omit digits before or after the decimal point.
Examples: 0.246, 975.64, –.54, +5 etc.
Exponential notation:
This notation is used to represent real numbers whose magnitude is very large or
very small.
The general format is:
mantissa e exponent OR mantissa E exponent
(a) The mantissa can be a floating point number or an integer.
(b) It can be positive or negative.
(c) The exponent has to be an integer with optional plus or minus sign.
Examples: The number 231.78 can be written as 0.231178e3 representing 0.23178 
103
Single Character Constant: It is a single character enclosed within a pair of single quote marks.
Example: ‘5’, ‘X’, ‘:’ etc
String Constants: A string constant is a group of characters enclosed in double quotes. The
characters may be letters or special characters.
Examples: “Hello”, “1356” , “Well Done” etc.

Dept of Computer Science St Aloysius College, Mangalore.


C-Programming 7

Backslash Character Constants: c suppoets some special backslash character constants that are
used in output functions. These characters combinations are known as escape sequences

List of backslash constants


Constant Meaning
‘\b’ Back Space
‘\f’ Form fed
‘\n’ New line
‘\r’ Carriage return
‘\t’ Horizontal tab
‘\’’ Single quote
‘\0’ Null

Variables
A variable is a data name that may be used to store a data. A variable may take different
values at different times during execution. A variable name can be chosen by the programmer in a
meaningful way so as to reflect its function or nature in the program.
Examples: Average, Height, Total, counter_1, etc
Variable name may consist of letters, digits and underscore character.
While naming variables follow the following conditions:
(1) They must begin with a letter.
(2) Length should not be more than eight characters
(3) Uppercase and lowercase are significant. That is the variable ‘Total’ is not the same as
‘total’ or ‘TOTAL’.
(4) It should not be a keyword.
(5) White space is not allowed.
Examples: John, value, x1, mark etc.
Declaration of variable
We must declare variables to the compiler.
Declaration does two things:
(1) It tells the compiler what the variable name is.
(2) It specifies what type of data the variable will hold.
The declaration of variables must be done before they are used in the program.

Dept of Computer Science St Aloysius College, Mangalore.


C-Programming 8

The syntax (rule) for declaring a variable is as follows:


Data_type variable1, variable2, -------- variableN;
variable1, variable2, -------- variableN are the names of a variable. Variables are separated by
commas. A declaration statement must end with a semicolon.
Examples: int count;
int number, total;
double ratio;
Declaration of variables is usually done immediately after the opening brace of the program.

Assigning values to variables


Storing values into the variable can be done in two ways:
(1) Assignment Statement: Values can be assigned to variable using the assignment operator
‘=’
Its syntax is as follows:
Variable_name = constant value;
Examples: initial_value = 0;
balance = 75.84; etc
C permits multiple assignments in one line as initial_value = 0; balance = 75.84;
 An assignment statement implies that the value of the variable on the left side of the
‘equal sign’ is set equal to the value of the quantity on the right side.
 The assignment statement year = year + 1 indicates that new value of year is equal to old
value plus one.
 It is also possible to assign a value to a variable at the time the variable is declared. This
takes the following form:
Data_type variable_name = constant value;
Examples: int final_value = 0;
 The process of giving initial values to variables is called initialization.
C permits initialization of more than one variable in one statement using multiple
assignment operators.
Example: p = q = s = 0;

Reading data from keyboard: Another way of giving values to variables is to input data
through keyboard using the scanf function. It is general input function available in C.

Dept of Computer Science St Aloysius College, Mangalore.


C-Programming 9

It takes the following:


scanf(“control string “, &variable1, &variable2, ----------);
control string contains the format of data being received.
The ‘&’ symbol before each variable name is an operator that specifies the variable name’s
address. We must always use ‘&’ operator otherwise unexpected results may occur.
Example: scanf (“%d”, &number); when the computer, the execution stops and waits for the
value of the variable number to be typed in. Control string “%d” specifies that an integer value
is to be read from the terminal. Once the number is typed in and the ‘Enter key’ is pressed, the
computer then proceeds to the next statement.

Data Types
All C compilers support three basic data types namely
(1) Integer types:
Integers are whole numbers with a range of values supported by a particular machine. C provides
three classes of integer storage, namely short int, int and long int, in both signed and unsigned
forms.
(2) Floating point types:
Floating point (or real) numbers are stored in 32 bits with 6 digits of precision Floating point
numbers are defined in C by the keywords float. When the accuracy provided by a float number
is not sufficient, the type double can be used to define data types in C
Data types Description Size (bytes) Range
Char A single character 1 -128 to 127
Int An integer number 2 -32768 to 32767
Float Single precision 4 3.4 e-38 to 3.4 e
Real number +38
(6 precision digits)
double Double precision 8 1.7e-308 to
1.7e+308
Void Empty data type 0 valueless
Qualifiers
A qualifier, when applied to a data type alters its size or sign.
The size qualifiers are
(1) short
(2) long

Dept of Computer Science St Aloysius College, Mangalore.


C-Programming 10

The sign qualifiers are


(1) signed
(2) unsigned
Normally short and long cannot be applied to char and float and signed and unsigned cannot
be applied to float, double and long double.
All possible data types in C are

Data Type Size (in bytes) Range


Char 1 -128 to 127
Unsigned char 1 0 to 255
Signed char 1 -128 to 127
Int 2 -32768 to 32767
Unsigned int 2 0 to 65535
Signed int 2 -32768 to 32767
Short int 2 -32768 to 32767
Unsigned short int 2 0 to 65535
Signed short int 2 -32768 to 32767
Long int 4 -2147483647 to 2147483648
Unsigned long int 4 0 to 4294967295
Signed long int 4 -2147483647 to 2147483648
Float 4 3.4E-38 to 3.4E+38
Double 8 1.7E-308 to 1.7E+308
Long double 10 Compiler dependent

Void types: the void type has no values.this is usually used to specify the type of functions. The
type of a function is said to be void when it odes not retunn any value to the calling function.
Character types: a single character can be defines as a character(char) type data. Characters are
usually stored in 8 bits(one byte) of internal storage. The qualifier signes or unsigned may be
explicitly applied to char. While unsignes char s have values between 0 and 255,signed chars
have values for -128 to 127.
Defining symbolic constants

If we use constants in the program we face two problems

Dept of Computer Science St Aloysius College, Mangalore.


C-Programming 11

(1) Modifiability: We may like to change the value of constant, at that time we have to search
throughout the program and explicitly change the value of the constant wherever it has been
used. In this case if any value is left unchanged, the program may produce wrong outputs.
(2) Understandability: When a numeric value appears in a program, its use is not always clear,
especially when same value means different things in different places. For example, the number
50 may mean the number of students at one place and the pass marks at another place of the same
program. We may forget what a certain number meant when we read the program some days
later.

Assigning of such constants to a symbolic constant frees us from these problems. For example we
may use name STRENGTH to define number of students and PASS-MARK to define the pass marks
required in a subject.
A constant is defined as follows:
#define symbolic name value of constant
Examples: #define PI 3.142
#define STRENGTH 100
#define PASS_MARK 50
Following are the rules to define a symbolic constant:
(1) Symbolic name have the same form as variable names. (Symbolic names are usually written in
capitals to visually distinguish them from the normal variable names which are written in
lowercase.
(2) No blank space between the pound sign ‘#’ and the word define is permitted.
(2) The first character in the line must be ‘#’.
(3) A blank space is required between #define and symbolic name and between the symbolic
name and the constant.
(4) #define statements must not end with a semicolon.
(5) After definition, the symbolic name should not be assigned any other value within the
program by using an assignment statement.
(6) Symbolic names are not declared for data types. Its data type depends on the type of
constant.
(7) #define statements may appear anywhere in the program but before it is referenced in the
program

Dept of Computer Science St Aloysius College, Mangalore.


C-Programming 12

CHAPTER 3: OPERATORS AND EXPRESSIONS

An operator is a symbol that tells the computer to perform certain mathematical or logical
manipulations.
C supports a rich set of operators which are as follows:
(1) Arithmetic operators
(2) Relational operators
(3) Logical operators
(4) Assignment operators
(5) Increment and decrement operators
(6) Conditional operators
(7) Bitwise operators
(8) Special operators
1. Arithmetic operators
List of arithmetic operators provided by C is
Operator Meaning
+ Addition
 Subtraction or unary minus
* Multiplication
/ Division
% Modulo division
Integer division truncates any fractional part. The modulo division operation produces
the remainder of an integer division. The modulo division operator % cannot be used
on floating point data.
Examples: a  b a % b etc.
Here a and b are variables and called as operands.
(a) Integer Arithmetic: When both the operands in a single arithmetic expression are
integers, the expression is called integer arithmetic. Integer arithmetic always yields
an integer value.
(b) Real Arithmetic: An arithmetic operation involving only real operands is called real
arithmetic.
(c) Mixed Mode Arithmetic: When one of the operands is real and the other is integer,
the expression is called mixed mode arithmetic expression. If either operand is of the
real type, then only the real operation is performed and the result is always a real
number.

2. Relational operators
Relational operators are the operators that are used to compare two quantities and depending on their
relation take certain decisions. An expression containing relational operator is termed as a relational
expression.
Following are the set of relational operators:

Dept of Computer Science St Aloysius College, Mangalore.


C-Programming 13

Operator Meaning
< is less than
<= is less than or equal to
> is greater than
>= is greater than or equal to
== is equal to
!= is not equal to
The form of simple relational expression is:
Arithmetic expression1 relational operator arithmetic expression2

Arithmetic expression1 and Arithmetic expression2 are arithmetic expression, which may be
simple constants, variables or combination of them. The arithmetic expressions are evaluated first
and then the results are compared. Relational expressions are used in decision statements such as if
and while.

3. Logical operators
The logical operators are used when we want to test more than one condition and make
decisions. Following is the list of logical operators:
Operator Meaning
&& Logical AND
|| Logical OR
! Logical NOT
Example: a > b && x == 10
An expression of this kind, which combines two or more relational expressions, is termed as
a logical expression or a compound relational expression.
Logical expression yields a value of one or zero, according to the truth table given below:

Operand 1 Operand2 Operand 1 && Operand2 Operand1 || Operand2


1 (or non zero) 1 (or non zero) 1 1
1 (or non zero) 0 0 1
0 1 (or non zero) 0 1
0 0 0 0

Operand 1 ! (Operand)
1 (or non zero) 1
0 1

Examples:
(1) if (ang > 55 && salary < 1000)
(2) if (number < 0 || number > 100)

4. Assignment operator
Assignment operators are used to assign the result of an expression to a variable. The most
common assignment operator is ‘=’.
Its syntax is:
variable_name = expression or constant value;
The other assignment statement available is C is shorthand assignment operators.
Its Syntax is:
v op= exp;

Dept of Computer Science St Aloysius College, Mangalore.


C-Programming 14

Where v is a variable,
exp is an expression and op is a C arithmetic operator.
Operator op= is known as shorthand assignment operator.
The assignment statement v op= exp; is equivalent to v = v op (exp);
Examples: x += y + 1; is same as x = x + (y + 1);

Advantages of shorthand assignment operators:


(1) What appears on the right hand side need not be repeated and therefore it becomes
easier to write.
(2) The statement is more concise and easier to read.
(3) The statement is more efficient.

[5] Increment and Decrement operator


C has two very useful operators not generally found in other languages. These are increment
and decrement operators:
++ (Increment) and  (Decrement)
++ adds one to the operand while  subtracts one from the operand.
Increment and decrement statements are usually used in for and while loop extensively.
Two types of increment and decrement operators:
(1) Per increment and decrement operator: A prefix operator first adds 1 to the operand and
then the result is assigned to the variable on the left.
Example:
m = 5;
y = ++m;
In this case the value of m = 6 and y = 6 because m is incremented first then its value is
assigned to y.
(2) Post increment and decrement operators: A post operator first assigns the value to the
variable on the left hand side and then increments the operand.
Example:
m = 5;
y = m++;
In this case the value of m = 6 and y = 5 because m is assigned first then its value is
incremented by 1.

[6] Conditional operator


A ternary operator pair “?:” is available in C to construct conditional expressions of the form:
exp1?exp2:exp3;
Where exp1, exp2 and exp3 are the expressions.
The operator ?: works as follows:
(1) exp1 is evaluated first. If it is nonzero (true), then the exp the expression exp2 is
evaluated and becomes the value of the expression.
(2) If exp1 is false, exp3 is evaluated and its value becomes the value of the
expression.
(3) Only one of the expressions (either exp2 or exp3) is evaluated.
Example: a = 10;
b = 15;
x = (a > b) ? a : b;
In this example, x will be assigned the value of b.
[7] Bitwise Operator
Bitwise operators are used for testing the bits or shifting them right to left.
Bitwise operators may not be applied to float or double.

Dept of Computer Science St Aloysius College, Mangalore.


C-Programming 15

Operator Meaning

& Bitwise AND


| Bitwise OR
^ Bitwise exclusive OR
<< Shift left
>> Shift right

Examples:
Assume that ‘a’ and ‘b’ are two integers with values 13 and 7 respectively. Assuming that the integer
occupies 2 bytes,
a in binary = 0000 0000 0000 1101
b in binary = 0000 0000 0000 0111
a & b = 0000 0000 0000 0101
a | b = 0000 0000 0000 1111
a ^ b = 0000 0000 0000 1010

[8] Special Operators


C supports some special operators such as ‘,’ , ‘&’, ‘*’ and sizeof operator
(a)The comma operator (,): comma operator is used to separate a set of expressions. A pair
of expression separated by a comma is evaluated left to right and the type and the value of
the result is the type and value of the right operand. Example: i = (j = 3, j + 2); Here the right
hand side contains two expressions j = 3 and j + 2which are evaluated from left to right. Thus
3 isfirst assigned to j and the value 3 + 2 is assigned to i. The comma operator has the lowest
precedence.
(b) sizeof operator: This unary operator gives the size in bytes of the data types or variables.
Syntax: sizeof (data type); OR sizeof(Object);
Examples: sizeof(char) gives the result as 1.
© Address (&) and the indirection (*) operators: The & operator when used with a
variable yields its address. The * operators denotes indirection and returns the object to which
its operand points.

Arithmetic Expressions

An arithmetic expression is a combination of variables, constants and operators arranged as


per the as syntax of the language.

Evaluation of Expressions
Expressions are evaluated using an assignment statement of the form
Variable = expression;
When the statement is encountered, the expression is evaluated first and the result then replaces the
previous value of the variable on the left hand side. All the variables used in the expression must be
assigned values before evaluation is attempted.

Precedence of Arithmetic operators

There are two distinct priority levels of arithmetic operators In C:


High Priority = * / %

Dept of Computer Science St Aloysius College, Mangalore.


C-Programming 16

Low Priority = + 
(1) The basic evaluation procedure includes two left to right passes through the
expression.
(2) During the first pass, the high priority operators (if any) are applied as they are
encountered
(3) During the first pass, the low priority operators (if any) are applied as they are
encountered
(4) Example: Consider the following arithmetic expression
a = 9, b = 12 and c = 3
x = a – b / 3 + c * 2 –1; is evaluated as follows
(1) x = 9 – 12 / 3 + 3 * 2 – 1
(2) First Pass: Step 1: x = 9 – 4 + 3 * 2 – 1
Step 2: x = 9 – 4 + 6 – 1
(3) Second Pass: Step 3: x = 5 + 6 – 1
Step 4: x = 11 – 1
Step 5: x = 10
(5) The order of evaluation can be changed by introducing parentheses into an
expression.
(6) Whenever parentheses are used, the expression within parentheses assume highest
priority.

Type Conversions in expressions

Automatic Type conversion

(1) C permits mixing of constants and variables of different types in an expression, but
during evaluation, it adheres to very strict rules of type conversion.
(2) 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.
(3) Char and short is automatically converted to int. Similarly float is automatically
converted into double.
(4) If one of the operand is double, the other is converted to double and the result is
double.
(5) If one of the operand is long, the other is converted to long and the result is long.
(6) If one of the operand is unsigned, the other is converted to unsigned and the result is
un signed.
(7) If both are of type int then the result is of type int.
(8) Float to int conversion causes truncation of the fractional.
(9) Double to float conversion causes rounding of digits.
(10) long int to int conversion causes dropping of the excess higher order bits.

Casting a value
There are instances when we want to force a type conversion in a way that is different from the
automatic conversions
Example: The calculation of ratio of females to males in a town is:
Ratio = female_number / male_number
Since female_number and male_number are declared as integer in the program, the decimal
part of the division would be lost and ratio would represent wrong figure. This problem can
be solved by converting locally one of the variables to the floating point as follows:
ratio = (float) fmale_number / male number

Dept of Computer Science St Aloysius College, Mangalore.


C-Programming 17

The operator (float) converts the female number to floating point for the purpose of
evaluation of the expression. Then using the rule of automatic conversion, the division is
performed in floating point mode.
The process of such a local conversion is known as casting a value. The general form of a
cast is:
(type_name) expression
Where type_name is one of the standard C data types. The expression may be a constant,
variable or an expression.
Examples:
(1) x = (int) 7.5 7.5 is converted to integer.
(2) (int) 21.3 / (int) 4.5 evaluated as 21 / 4 and the result would be 5

Operator precedence and associativity

Each operator in C has a precedence associated with it. This precedence is used to determine how
an expression involving more than one operator is evaluated. The operator at higher level of
precedence is evaluated first. The operators of the same precedence are evaluated either from left to
right or from right to left, depending un the level. This is known as the associativity levels and their
rules of association.
(REFER CLASS NOTE FOR MORE DEATIL)

Mathematical Functions

For using mathematical functions we should include math header file in the beginning of the
program Following are the set of mathematical functions:

Function Meaning
Trigonometric functions
acos(x) Arc cosine of x
asin(x) Arc sin of x
atan(x) Arc tangent of x
atan2(x,y) Arc tangent of x/y
cos(x) cosine of x
sin(x) sin of x
tan(x) tangent of x

Hyperbolic

cosh(x) Hyperbolic cosine of x


sinh(x) Hyperbolic sin of x
tanh(x) Hyperbolic tangent of x

Other functions

ceil(x) x rounded up to the nearest integer


exp(x) e to the power x
fabs(x) Absolute value of x
floor(x) x rounded down to the nearest integer
fmod(x,y) remainder of x / y
log(x) natural log of x, x > 0

Dept of Computer Science St Aloysius College, Mangalore.


C-Programming 18

log10(x) base 10 log of x, x > 0


pow(x,y) x to the power y (xy)
sqrt (x) square root of x, x >= 0

CHAPTER 4: MANAGING INPUT AND OUTPUT OPERATIONS

All input output operations are carried out through functions calls such as printf and scanf. There
exist several functions that have more or less become standard for input and output operations in
C.These functions are collectively known as the standard I/O library. Each program that uses a
standard input/output function much contain the statement, #include<stdio.h> at the beginning. The
file name stdio.h stands for standard input output header file. The instruction #include<stdio.h> tells
the compiler to search for the file named stdio.h and place its contents at this point in the program.

READING A CHARACTER
Reading a single character can be done 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 type char. 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 on the left.
Example: char name;
name = getchar();
This two statements will assign the character ‘H’ to the variable name when we press the key
H on the keyboard.

Dept of Computer Science St Aloysius College, Mangalore.


C-Programming 19

CHARACTER TEST FUNCTIONS


C supports several character test functions. These functions are contained in the file ctype.h and
therefore the statement #include<ctype.h> must be included in the program.
Functions Test
isalpha(character) If character contains an alphabet isalpha returns
true otherwise false.

isdigit(character) If character contains a digit isdigit returns true


otherwise false.

isalnum(character) If character contains an alphanumeric character


then isalnum returns true otherwise false.

islower(character) If character is a lowercase character then islower


returns true otherwise false.

isupper(character) If character is a uppercase character then isupper


returns true otherwise false.

isprint (character) If character is a printable character then isprint


returns true otherwise false.

ispunct(character) If character is a punctuation mark then ispunct


returns true otherwise false.

isspace(character) If character is a white space character then


isspace returns true otherwise false.

WRITING A CHARACTER

Function putchar is used for writing characters one at a time to the terminal.

It takes the following form:

putchar(variable_name);

Where variable_name is a type char variable containing a character. This statement displays the
character contained in the variable_name at the terminal.

Example: answer = ‘Y’;

Putchar (answer);

These two statements will display Y on the screen.

Dept of Computer Science St Aloysius College, Mangalore.


C-Programming 20

FORMATTED INPUT

Formatted input refers to an input data that has been arranged in a particular format. The
scanf function returns the number of data items that have been entered successfully. The
general form of scanf function is:

scanf(“control string”,arg1,arg2, arg3,-----argn);

Where the control string specifies the field format in which the data is to be entered and the
argument arg1,arg2, arg3,-----argn specifies the address of locations where the data is stored.

The control string comprises individual groups of characters, with one character group
for each input data item. Each character group must begin with a percent (%) sign, that is a
single character group will consist of the percent sign, followed by a conversion character
which indicates the type of the corresponding data item. Control string may also include
blanks, tabs or new lines.

The table given below shows the frequently used conversion characters for data input along
with their meaning:

Conversion character Meaning

c Data item is single character

d Data item is decimal integer

e Data item is a floating point value

f Data item is a floating point value or double type

g Data item is double

h Data item is short integer

l Data item is long integer

o Data item is octal integer

s Data item is a string followed by a white space character.

u Data item is a unsigned decimal integer

x Data item is a hexadecimal integer

Dept of Computer Science St Aloysius College, Mangalore.


C-Programming 21

Each variable name in scanf () function should be preceded by an ampersand (&).

Example: scanf (“%d%d”, &num1, &num2);

If the input is 32 and 3507, then value 32 is assigned to num1 and 3507 is
assigned to num2. An input field can be skipped by specifying * in the place of field width.

Example: scanf (“%d%*d%d”, &a, &b, &c);

If the data entered is 10 20 30, then 10 is assigned to a, 20 is skipped because of


* and 30 is assigned to c.

[a] Inputting integer numbers

The field specification for reading an integer number is % w d

The percent sign (%) indicates that a conversion specification follows. w is an 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);

[b] Inputting Real numbers

Scanf reads real numbers using the simple specification % f for both the notations
decimal point and exponential.

Example: scanf (“%f %f %f”, &x, &y, &z);

If the number to be read is of double type, then the specification should be %lf. A number
may be skipped using %*f specification.

[c] Inputting character strings

Following are the specifications for reading 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.

[d] Reading mixed data types

Scanf statement can be used to input a data line containing mixed mode data. Care should
be taken that the input data items match the control specifications in order and type.

Dept of Computer Science St Aloysius College, Mangalore.


C-Programming 22

When an attempt is made to read an item that does not match the type expected, the scanf function
does not read any further and immediately returns the values read.

Example: scanf (“%d%c %f %s”, &count, &code, &ratio, &name);

This statement will read 15 p 1.456 coffeecorrectly and assign the


values to the variables in the order in which they appear.

Formatted output

The printf statement provides certain features that can be effectively exploited to control the
alignment and spacing of print outs on the terminals.

The general format of printf statement is:

printf (“control string”, arg1, agr2, -------- argn);

Control string consists of three types of items:

1. Characters that will be printed on the screen as they appear.


2. Format specifications that define the output 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 the
format specification. A simple format of 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 values and p is another integer number that specifies the number of digits to the right
of the decimal point or the number of character to be printed from a string.

Output of Integer numbers

The format specification for printing an integer number is:

%wd

Where w specifies the minimum field width for the output. If the number is greater than the specified
field width, it will be printed in full. D specifies the value to be printed is an integer. The number is
written right-justified in the given field width. To print left-justified by placing minus sign directly
after the % character.

Output of real numbers

Dept of Computer Science St Aloysius College, Mangalore.


C-Programming 23

The output of a real number may be displayed in decimal notation using the following format
specification:

% w.p f

The integer w indicates the minimum number of positions that are to be used for the display of the
value and the integer p indicates the number of digits to be displayed after the decimal point. The
value when displayed is rounded to p decimal places and printed right justified in the field of w
columns. We can also display a real number in exponential notation by using the specification %
w.p e

Padding the leading blanks with zeros and printing with left-justification is also possible by
introducing 0 or – before the field width specifier w.

Putting of a single character

A single character can be displayed in a desired position using the format % wc. The
character will be displayed right-justified in the field of w columns.

Printing of strings

The format specifications for outputting strings is similar to that of real numbers. It is of
form: % w.ps

Where w specifies the field width for display and p instructs that only the first p characters of
the string are to be displayed. The display is right justified.

Mixed data output

The format specifications should match the variables in number, order and type.

CHAPTER 4: DECISION MAKING AND BRANCHING


Introduction

Normally, the statements are executed in the same order in which they appear in the
program. This type of execution is known as sequential execution. Program of this type are
simple since they do not include any logical control structures. In particular, such program do
not include tests to determine if certain conditions are true or false, and they do not involve
the execution of individual groups of statements on a on a selective basis.

Dept of Computer Science St Aloysius College, Mangalore.


C-Programming 24

Many programs require that a logical test to be carried out at some particular point
within the program. An action will then be carried out depending upon the outcome of the
logical test. This is known as conditional.

Conditional control statement


Many program require testing of some conditions at some point in the program and selecting
one of the alternative paths depending upon the result of the conditions.
Different types of conditional control structures available in C are
(1) IF statement
(2) Switch statement
(3) Conditional operator
(4) Goto statement

IF Statement
This is the simplest form decision statement in C. It allows decisions to be made by evaluating an
expression. Depending upon the result (True or false), the program execution proceeds in one
direction or another. Basically it is two-way decision statement and is used in conjunction with an
expression. It takes the following form:
if (test expression)

Flow chart for if statement Entry

Test
Expressio
n
False
true

Different forms of IF statement


[a] Simple IF statement
The simplest form of IF statement is:
Single statement More than one statement
if (Expression) OR if (Expression)

Dept of Computer Science St Aloysius College, Mangalore.


C-Programming 25

statement; {
Statement;
}
statement –x;
The keyword if must be followed by set of parenthesis containing a single expression
to be tested. The statement is executed only if the expression is true(Non-zero). If the
condition evaluates to false, the statement is skipped.
Flow chart of simple if statement
Examples:
(1) if (n < 0)
printf(“The number is negative.”);
(2) if (age < 30 && salary > 10000)
printf(“You are young and rich!!”);
(3) if (basic_sal > 10000)
{
it = 30.0 * basic_sal / 100;
da = 200.00 * basic_sal / 100;
hra = 800.0;
}

[b] IF …… ELSE statement


The if statement will execute the statement if the expression is true otherwise it will
be skipped. However, in many cases we require an alternate statement to be executed if the
expression evaluates to false. This is possible using an if ….else statement.
The syntax of if …else statement is:-
if (Expression)
Statement1;
else
Statement2;
Statement3;
OR
if (Expression)
{
True statement block;

Dept of Computer Science St Aloysius College, Mangalore.


C-Programming 26

}
else
{
False statement block;
}
Statement –x;
Here if the test expression is evaluated. If it is true, statement 1 (true
statement block) is executed and if it is false, statement2 (False statement block) is
executed and then the control will be transferred to statement–x.

Flow chart of if – else statement Entry


Test
Expressio
n

True False
True statement False statement
Block Block

Statement – x

Examples:
(1) if (a > b)
printf (“a is larger”);
else
printf (“b is larger”);
(2) if (year % 4 == 0 && year % 100 != 0 || year % 400 ==0 )

Dept of Computer Science St Aloysius College, Mangalore.


C-Programming 27

printf (“%d is a leap year”, year);


(2) if (basic_sal < 10000)
{
it = 20 * basic_sal / 100;
da = 150 * basic_sal /100
hra = 500;
}
else
{
it = 30 * basic_sal / 100;
da = 200 * basic_sal /100
hra = 800;
}

[c] Nested if ….. else statements


As seen earlier, the if clause and the else part may contain a compound statement.
Moreover, either or both may contain another if or if ….. else statement. This is called as
nesting of if ….. else statements.
Nesting could take one of several forms as given below:
(a) if (Expression 1)
Statement 1;
else
if (Expression 2)
statement 2;

(b) if (Expression 1)
if (Expression 2)
Statement 1;
else
if (Expression 3)
statement 2;

(c) if (Expression 1)
if (Expression 2)

Dept of Computer Science St Aloysius College, Mangalore.


C-Programming 28

Statement 1;
else
statement 2;
else
statement 3;

(d) if (Expression 1)
statement 1;
else
if (Expression 2)
Statement 2;
else
statement 3;

(e) if (Expression 1)
if (Expression 2)
statement 1;
else
statement 2;
else
if (Expression 3)
Statement 3;
else
statement 4;

Examples:
(1) if (a>b)
if (a > c)
printf(“a is larger.”);
else
printf(“b is larger.”);
else
if (b >c)
printf(“b is larger”);
else
printf(“c is larger.”);

(2) if ( ( ch > = ‘a’ && ch < = ‘z’ ) || (ch > ‘A’ && ch <= ‘Z’))
printf(“%c is anTest
alphabet”,ch);
else condition
if (ch >= ‘0’ &&1ch <= ‘9’)
printf(“%c is a digit”, ch);
Statement else
-3
printf(“%c is an special symbol.”,
Test ch);
condition
2
Flow chart for nested if ...... elseStatement
statement-2
Statement -1

Dept of Computer Science St Aloysius College, Mangalore.


Statement -3
C-Programming 29

[d] The else – if ladder


If there is an if else statement nested in each else of an if – else construct, it is called
an else – if ladder.
Its general form is:

if (Expression 1)
Statement 1;
Else
if (Expression 2)
Statement 2;
else
if (Expression 3)
Statement 3;

else
if (Expression n)
Statement n;
else
Statement n+1;

The conditions (expressions) are evaluated from top to bottom. As soon as a true
expression is found the statement associated with it is executed and the rest of the ladder is
bypassed. If none of the expressions are true, the final else is executed. The last else often
acts as a default condition i.e., if all other test fail, the last else statement is executed. If it is
not present, no action takes place if all other conditions are falss.
Example:
if (isalpha (ch))
printf (“%c is an alphabet.”, ch);
else
if (isdigit (ch))
printf (“%c is a digit.”, ch);

Dept of Computer Science St Aloysius College, Mangalore.


C-Programming 30

else
if (ispunct (ch))
printf (“%c is a punctuation mark.”, ch);
else
printf (“%c is a special character.”, ch);

The switch statement


The switch statement is useful where control flow within a program must be directed
to one of several possible execution paths. Nested if –else can be used for this but the
structure becomes very complicated and the code becomes difficult to read and trace.
For these reasons C has built in multiple branch decision statement called switch.
This statement test whether an expression matches one of a number of constant values and
branches accordingly.
The format of switch is:
switch (Expression)
{
case value 1 : statements;
break;
case value 2 : statements;
break;
case value 3 : statements;
break;

case value n : statements;


break;
default :
statements;
}

When the switch is entered following actions are taken:


(i) The expression enclosed within parenthesis is successively compared against the
values in each case. They are called as case labels and must end with a colon.
(ii) The statement in each case must contain zero or more statements. If there are
multiple statements for a case they need not be enclosed in braces.
(iii) All case expressions must be different.
(iv) The case labelled default is executed if none of the other cases match.. The default
case is optional and if not included, no action takes place at all if none other
match.
(v) Cases and the default case can occur in any order.
(vi) More than one case value may be associated with a particular statement.
(vii) The break statement is used to exit a control structure. If break statement is not
included in case, then when a match occurs, not only the statement associated with
the matching case is executed but those of all the remaining cases are also
executed. Using break statement solves this problem.
(viii) As soon as a break statement is encountered, program control is transferred to the
first statement outside the structure to which the break belongs.
(ix) To associate more than one case value with a particular statement, you have to
simply list the multiple case values before the common statement (s) that are to be
executed. This is called falling through cases.

Dept of Computer Science St Aloysius College, Mangalore.


C-Programming 31

(x) It is also possible to have switch statement as a part of a statement in another


switch statement. Even if the case constants of the inner and outer switch contain
common values there is no conflict.

Examples:
(1) #include<stdio.h>
main()
{
int number;
printf (“\nEnter the number:\t”);
scanf(“%d”,number);
switch(number)
{
case 1 : printf(“You have entered 1\n”);
break;
case 2 : printf(“You have entered 2\n”);
break;
case 3 : printf(“You have entered 3\n”);
break;
default: printf(“Out of range\n”);

}
}
(2) switch (operator)
{
case ‘*’ :
case ‘×’: result = value 1 * value 2;
printf (“Multiplication =%f” , result);
break;

Flow chart for switch


Comparing if –else and switch statement

No. if –else statement Switch statement


1 The if –else structure allows Switch allows multi way
only two way branching branching from a single
from a single expression. expression.
2 The nested if –else structure Switch statement is very
is inelegant and elegant and easier to write.
complicated.
3 If multiple alternative exist, No such problem occurs
the nesting can go many using switch statement.
levels and it becomes
difficult to match the else

Dept of Computer Science St Aloysius College, Mangalore.


C-Programming 32

part to its corresponding if.


4 Debugging becomes Tracing errors and
difficult. debugging is easy.
5 The test expression can be Only constant integer
constant expression or an expression and values are
expression involving allowed.
relational or logical
operators. Float and double
are also allowed.
6 Multiple statements within The statement belonging to
if or else have to be a case need not be enclosed
enclosed in braces. in braces.

[3] Conditional operators


The ternary operator ?: can also be used for decision making. The general form of
ternary operator is:
Expression 1 ? Expression 2 : Expression 3
If Expression 1 is true, the entire ternary expression takes the value of Expression 2 else if
Expression 1 is false the entire ternary expression takes the value of Expression 3.
Thus value = Expression 1 ? Expression 2 : Expression 3 is equivalent to
if (Expression 1 )
value = Expression 2;
else
value = Expression 3;

[4] goto and labels


The goto statement is an unconditional jump statement. The goto statement is used to
alter the normal sequence of program execution by unconditionally transferring control to
some other part of the program that is marked by label.
The general form of goto statement:
goto label;
The statement where control has to be transferred is identified by the label.
 A label is a valid C identifier.
 A label is followed by a colon.
 The label can be attached to any statement in the same function as the goto.
 The label does not have to be declared like other identifiers.
 Goto breaks the normal sequential execution of the program. If the label is placed
immediately before the statement goto label; a loop will be formed and some
statements will be executed repeatedly. Such a jump is known as backward jump. On
the other hand, if the label is placed after the goto label; soem statements will be
skipped and the jump is known as a forward jump.

The general forms goto statements are:


Forward jump Backward jump
Goto label; label:
---------- statement;
---------- -----------
label: ------------
statement ; goto label:
Dept of Computer Science St Aloysius College, Mangalore.
C-Programming 33

Example:
x = 1;
loop : x++;
if (x < 100)
goto loop;
Control cannot be transferred from outside to within a loop using the goto statement.

DECISION MAKING AND LOOPING

Loop
A segment of program code that is executed repeatedly is called a loop. The repetition
is done until some condition for termination of the loop is satisfied.

A loop structure essentially contains two parts:


(i) A test condition
(ii) Loop statement(s)
A test condition determines the number of times the loop body is executed. It involves
evaluating a loop control variable(s), whose value has to change within the loop body so that
the loop execution can terminate.

The looping procedure in general takes place in four steps:


(i) Initializing the loop control variable.
(ii) Execution of loop statements.
(iii) Changing the value of the control variable.
(iv) Testing the condition.

Depending upon when the loop condition is tested, loops can be of two types:
(1) Top tested loop (Entry controlled loop)
(2) Bottom tested loop (Exit controlled loop)

Entry controlled loop

In an entry-controlled loop, the condition is evaluated before the loop body is executed.
Example: (1) while loop (2) for loop.Test
Condition
Flow chart for entry controlled loop

Dept of Computer Science Loop body St Aloysius College, Mangalore.


C-Programming 34

False

True

Exit controlled loop

In an exit-controlled loop or bottom-tested loop, the condition is tested or evaluated

after the loop body is executed.

Example: (1) do while loop

Flow chart for exit controlled loop

Loop body

Test True
Condition

False

The test conditions should be carefully stated in order to perform the desired number of loop
executions It is assumed that the test condition will eventually transfer the control out of the
loop. In case due to some reason it does not do so, the control sets up an infinite loop and
body is executed over and over again.

The C language provides three loop structures for use in program:


(1) while statement
(2) do ….. while statement

Dept of Computer Science St Aloysius College, Mangalore.


C-Programming 35

(3) for statement

[1] The while statement


The while loop is the simplest loop structure. It is often used when the number of
times the loop is to be executed is not known in advance but depends on the test condition. It
is an entry controlled loop i.e., the condition is tested before the loop body is executed. The
general format of the while loop is:
while (Test Expression)
{
body of the loop;
}
The test expression is the test conditions and can be any valid C expression.

Body of the loop can be a single statement or compound statement.


while loop works in the following way:

(1) The expression is evaluated and the loop body is executed as long as the expression is
TRUE (non zero).
(2) As soon as the expression evaluates to false, the execution of the loop body is stopped
and control is transferred to the first statement outside the loop body.
(3) Since it is an entry-controlled loop, if the expression evaluates to false the first time
itself, the loop body will not be executed even once.

Flow chart for the while loop

Entry

Test False
Condition

True
Loop body

Example:

#include<stdio.h>

Dept of Computer Science St Aloysius College, Mangalore.


C-Programming 36

main()
{
int even_number = 0;
while (even_number < 50)
{
printf(“%d\n”, even_number);
even_number = even_number + 2;
}
}

Points to remember

(1) The loop control variable (s) must be initialized (i.e., given some value before the
condition is tested).
(2) The loop body must contain a statement to alter the value of the control variable.

Nested while statement

While statement can also be nested. Nesting of loop means a loop that is contained
within another loop. Nesting can be done up to any levels. However the inner loop has to be
completely enclosed in the outer loop. No overlapping of loops is allowed.
Nesting of while loop can take the following form:

while (Expression 1)
{
while (Expression 2)
{
loop body of while (Expression 2);
}
}

[2] do ….. while loop

The while loop is top tested loop i.e., it evaluates the condition before executing any
of the statements in its body. The do ….. while loop on the other hand, is a bottom tested or
exit controlled loop i.e., it evaluates the condition after the execution of statements in its
construct. This means that the statements within the loop are executed at least once.
The syntax of do while statement:
do
{
Body of the loop;
}
while (Expression);

Dept of Computer Science St Aloysius College, Mangalore.


C-Programming 37

The statement (single or compound) is executed as long as the expression is true.


The do …… while statement is executed in the following way:

(1) The body of the loop is executed first.

(2) Expression is evaluated. If it is true, execution returns to step 1. If it is false, execution of


the loop terminates.
do ….. while loop is useful wherever a statement is to be executed at least once.

Flow chart for do ….. while loop

Entry

Loop body

False

Test
Condition
True

#include<stdio.h>
main ()
{
int digit = 0;
clrscr();
do
{
printf(“%d\n”, digit);
digit++;
}
while (digit < = 9);
getch();
}

[3] for loop

Dept of Computer Science St Aloysius College, Mangalore.


C-Programming 38

The for loop is very flexible and most commonly used loop in C. It is useful when the
number of repetitions is known in advance. This is top tested loop similar to the while loop
but the advantage is that it combines the initialization test condition and loop variable
alteration statement in a single statement
The syntax of for loop is:
for (Expression 1; Expression 2; Expression 3)
{
loop body; (a simple or compound statement)
}
Where Expression 1 is the initialization expression
Expression 2 is the test condition
Expression 3 is the update expression
These three expressions have to be separated by semicolon (;)
Execution of for loop
(1) Expression 1 is evaluated first and only once at the beginning. This expression
performs initialization of the loop control variable (Multiple initialization can also be
done.)
(2) Expression 2 is the test expression, which is evaluated before execution of statements
in the loop. The statements inside the for loop is executed only if the test expression is
true. If it is false, the loop execution terminates. There can be only single test
expression.
(3) Expression 3 is the update expression, which alters the value of the loop control
variable.

Different forms of the for loop

(i) for (i = 0; i < 25 ; i++)


statement;

(ii) for (i = 0; i < 25 ; i++)


{
Statement ;

Statement ;
}

(iii) for (i = 0; i < 25 ; i++)


;
OR
for (i = 0; i < 25 ; i++) ;

(iv) for (i = 0 , j = 0 ; i < 25 ; i++ , j++)


statement;
(v) for (; i < 25 ; i++)

(vi) for (; i < 25 ; )

(vii) for (;;)


printf(“Forever\n”);

Dept of Computer Science St Aloysius College, Mangalore.


C-Programming 39

Nesting for statements


One for statement can be written within another for statement. This is called nesting of
for statements. It takes the following form:
for (i = 1 ; i <25; i++)
{
for (j = 1; j <=10; j++)
{
}
}
It is essential that one loop be completely embedded within the other, that means there should
be no overlap. Also each loop must be controlled by a different index.

Jump Statements

(1) The Break statement


Sometimes it is required to exit a loop as soon as a certain condition is met i.e., to
force immediate termination of a loop bypassing the normal loop condition test.
The break statement transfer control to the following the do ….. while(), while () or for (;;)
loop body. When the break statement is encountered inside a loop, the loop is immediately
terminated. Subsequent statements in the loop are skipped and program control resumes at the
next statement following the loop.
Its Syntax : break;

(2) continue statement


The continue statement is somewhat similar to the break statement except that it does
not cause the loop to terminate. It bypasses the remaining statements and it forces the next
iteration of the loop to take place as usual.
Format : continue ;
Example:
do
{
printf(“Enter a number:”);
scanf(“%d”, &n);
if (n < 0)
continue;
sum = sum + n;

} while (n != 999);
This code accepts integers and calculates the sum of only positive numbers. The loop
terminates after the user enters 999.

The goto and labels


The goto statement is an unconditional jump statement. The goto statement is used to
alter the normal sequence of program execution by unconditionally transferring control to
some other part of the program that is marked by label.
The general form of goto statement:
Goto label;
The statement where control has to be transferred is identified by the label.
 A label is a valid C identifier.

Dept of Computer Science St Aloysius College, Mangalore.


C-Programming 40

 A label is followed by a colon.


 The label can be attached to any statement in the same function as the goto.
 The label does not have to be declared like other identifiers.
The format of label (target statement) is:
Label : statement;
Example:
x = 1;
loop : x++;
if (x < 100)
goto loop;
Control cannot be transferred from outside to within a loop using the goto statement.

exit () function

The exit() function causes immediate termination of the entire program. The exit () function

is called with an argument 0 to indicate that termination is normal. Other arguments are used

to indicate some sort of errors.

A common use of exit () function occurs when some mandatory condition for program
execution is not satisfied.

Dept of Computer Science St Aloysius College, Mangalore.

You might also like