Professional Documents
Culture Documents
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
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.
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)
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
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
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
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
(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.
Backslash Character Constants: c suppoets some special backslash character constants that are
used in output functions. These characters combinations are known as escape sequences
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.
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.
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
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
(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
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:
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 ! (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;
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);
Operator Meaning
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
Arithmetic Expressions
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.
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.
(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
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
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
Other functions
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.
WRITING A CHARACTER
Function putchar is used for writing characters one at a time to the terminal.
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.
Putchar (answer);
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:
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:
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.
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.
Scanf reads real numbers using the simple specification % f for both the notations
decimal point and exponential.
If the number to be read is of double type, then the specification should be %lf. A number
may be skipped using %*f specification.
% ws or % wc
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.
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.
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.
%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.
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.
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.
The format specifications should match the variables in number, order and type.
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.
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.
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)
Test
Expressio
n
False
true
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;
}
}
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.
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 )
(b) if (Expression 1)
if (Expression 2)
Statement 1;
else
if (Expression 3)
statement 2;
(c) if (Expression 1)
if (Expression 2)
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
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);
else
if (ispunct (ch))
printf (“%c is a punctuation mark.”, ch);
else
printf (“%c is a special character.”, ch);
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;
Example:
x = 1;
loop : x++;
if (x < 100)
goto loop;
Control cannot be transferred from outside to within a loop using the goto statement.
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.
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)
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
False
True
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.
(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.
Entry
Test False
Condition
True
Loop body
Example:
#include<stdio.h>
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.
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);
}
}
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);
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();
}
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.
Statement ;
}
Jump Statements
} while (n != 999);
This code accepts integers and calculates the sum of only positive numbers. The loop
terminates after the user enters 999.
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
A common use of exit () function occurs when some mandatory condition for program
execution is not satisfied.