You are on page 1of 42

1

PROGRAMMING IN C.
C CHARACTER SET
Alphabets: a z, A Z, Numerals : 0,1,2,.. 9
Special Characters
, Comma & Ampersand
. Period ^ Caret
; Semicolon + Plus sign
: Colon - Minus sign
Apostrophe (or) single quote * Asterisk
Double quote / Slash ( division sign)
! Exclamation mark < Opening angled bracket (less than
sign)
| Vertical bar > Closing angled bracket (Greater than
sign)
\ Backslash ( Opening parantheses
~ Tilde ) Closing parantheses
_ Underscore [ Left Bracket
$ Dollar sign ] Right Bracket
= Equal sign { Opening Brace
% Percent sign } Closing brace
# Number sign Blank space
@ Alias sign
C TOKENS
In C program the smallest individual units are known as C tokens. C has six types of tokens.
They are Keywords, constants, String, Operators, Identifiers, Special Characters.
C TOKENS

Keywords Constants Strings Operators

Ex : float, do Ex : 12.56, 15 Ex : sbcp, welcome Ex : * + - / < >

Identifiers Special
Characters
Ex : count, name
Keywords and Identifiers. Ex : [ ] { } $

Every C word is classified as a keyword or identifier.


Keywords
C contains rich set of functions and keywords. Keywords are words which has special
meaning in C that cannot be changed. There are 32 keywords in C. They are
auto const double float int short struct unsigned
break continue else for long signed switch void
case default enum goto register sizeof typedef volatile
char do extern if return static union while
2

IDENTIFIERS
Identifiers refer to the names of variables, functions, arrays. These are user-defined
names.
Rules for naming identifiers
1. They must begins with alphabets or underscore and can have sequence of letters and
digits.
2. Both uppercase and lowercase letters are permitted but are significant. i.e. the identifier
Total is not as TOTAL or total
3. It cannot have any special characters other than underscore.
4. C keywords cannot be used as identifiers, because they have special meaning in C
5. The maximum length of the C identifier is 31 characters.
6. Blank space is not allowed

CONSTANTS
Constants are referred to fixed values that do not change during the execution of the
program. C constants are broadly classified into two types Numeric constants and Non
numeric constants or Character constants.
Numeric Constants
Numeric constants are divided into two types. They are Integer constants and Real
constants.
Integer Constants
An Integer Constant refers to a sequence of digits. There are three types of integers,
namely, decimal, octal and hexadecimal.
Rules for Decimal Integers
1. Contains any combination of numbers.
2. Special characters are not allowed.
3. To specify sign we can use or +, But only at the starting of the numbers
4. Blank spaces are not allowed
Some valid Decimal numbers are 12, 125, 0, -125, +1568
Invalid integers
Invalid numbers Reason for Invalidity
125.6 Decimal point ( . ) not allowed
25,486 Comma not allowed
(864) Parantheses Not allowed
45 63 Blank spaces not allowed
45*8 * not allowed
Rs. 45 Letters not allowed
$ 25 $ sign not allowed

In C Decimal Integers are further classified into four type as integer, short integer,
unsigned integer and long integer.
3

Octal integer constant consists of any combination of digits from the set 0,1,2,3,4,5,6
and 7 ( 0 to 7 ), with a leading 0 (zero)
Example: 015, 047, 0777, 0546
Hexadecimal Integer constant consists of sequence of digits, and the letters
A,B,C,D,E and F, with a leading 0x or 0X.
Example : 0x56, 0xff, 0x F34
Though C supports octal and hexadecimal integers, we rarely use them in
programming.
REAL CONSTANTS
Real constants are used to represent the approximate numbers or continuous numbers.
Real Numbers are numbers which has one and only decimal point. They are also known as
floating point constants.
Real numbers can be specified using either fractional form or exponent form
Fractional Form
Rules for Real Numbers in Fractional Form
1. Contains any combination of numbers and must contain one and only decimal point.
2. Cannot have any special characters other than + or -.
3. Should not contain blank spaces.
Example : 12.56, -24.65, 5., 8.6000
Exponent form (Floating point form)
Exponential notation is useful for representing numbers that are either very large of very small.
The general form of Exponent form is
Mantissa e exponent Or Mantissa E exponent
Mantissa is either an integer or a real number expressed in fractional form.
The exponent is an integer with an optional + or sign
The letter e or E separates the mantissa and exponent.
Example :
Number in Exponential Notation Meaning
0.65e4 or 0.65E4 6500 or 0.65 x 104
12e-2 or 12E-2 0.12 or 12 x 10 -2
1.5e+5 or 1.5E+5 150000 or 1.5 x105
-1.2e5 or -1.2E5 -120000 or -1.2105
-3.15e-3 or -3.15E-3 -0.00315 or -3.1510-3

Invalid Real numbers


Real numbers Reason for invalidity
-15 No decimal point
15.5e1.5 Exponent must be integer
0.1x5 The alphabet x not allowed
5.6.1 Only one decimal point is allowed
6.5e 10 White space not allowed
4

Non Numeric Constants


Non numeric constants are classified into single character constants and String
constants.
Single character constants
A single character Constant ( simply character constant) contains a single character enclosed
within a pair of single quote marks.
Example : r, 4, X
Each Character constants have their corresponding integer values known as ASCII values.
Character Ascii Character Ascii Character Ascii Character Ascii
Value Value Value Value
1 33 ! 65 A 97 a
2 34 " 66 B 98 b
3 35 # 67 C 99 c
4 36 $ 68 D 100 d
5 37 % 69 E 101 e
6 38 & 70 F 102 f
7 39 ' 71 G 103 G

8 40 ( 72 H 104 h
9 41 ) 73 I 105 i
10 42 * 74 J 106 j
11 43 + 75 K 107 k
12 44 , 76 L 108 l
13 45 - 77 M 109 m

14 46 . 78 N 110 n
15 47 / 79 O 111 o
16 48 0 80 P 112 p
17 49 1 81 Q 113 q
18 50 2 82 R 114 r
19 51 3 83 S 115 s
20 52 4 84 T 116 t
21 53 5 85 U 117 u
22 54 6 86 V 118 v
23 55 7 87 W 119 w
24 56 8 88 X 120 x
25 57 9 89 Y 121 y
26 58 : 90 Z 122 z
27 59 ; 91 [ 123 {
28 60 < 92 \ 124 |
29 61 = 93 ] 125 }
30 - 62 > 94 ^ 126 ~
31 63 ? 95 _ 127
32 64 @ 96 ` 128
ASCII TABLE
Constant Reason for Invalidity Constant Reason for Invalidity
e Missing closing single quote 1 Not enclosed in single quote
exam More than one character

String Constant
A string constant is a sequence of characters enclosed in double quotes (). The
characters maybe letters, numbers, special characters and blank spaces.
Examples : Hello, 167 9, Programming in C, 5 + 3 = 8
/ +++ ?...
Note : Single character String constant does not have an equivalent integer value while a
single character constant has an integer value. i.e. X is Single character String
constant and is not equal to X which Single character constant.
5

Backslash character constants or Escape sequences


Backslash constants are constants consist of a backslash followed by a character. It is also
known as Escape sequence. They are used in output functions. A list of backslash constants are
given in the table below.

Escape Sequence Meaning Escape Sequence Meaning


\a Bell sound \v Vertical tab Space
\b Back space \ Double quote
\f Form feed \ Single quote
\n New line \? Question mark
\r Carriage Return \\ Back slash
\t Horizontal Tab Space \0 null

C CONSTANTS

Numeric Constant Non Numeric Constant

Integer Constant Real constant Character Constant String constant

Fractional Form Exponent Form

VARIABLES
A variable is a data name that may be used to store data value. In other words variable is the
name of the memory location that can hold only one data at a time. Unlike constants, that remain
unchanged during the execution of the program, a variable may take different values at different
times during execution.
Rules for naming variables
1. They must begin with alphabets or underscore and can have sequence of letters and digits.
2. Both uppercase and lowercase letters are permitted but are significant. i.e. the variable
Total is not as TOTAL or total
3. It cannot have any special characters other than underscore.
4. C keywords cannot be used as variables, because they have special meaning in C
5. The maximum length of the C variable is 31 characters. If more than 31 characters or
used then only first 31 characters will be taken as variable names the remaining
characters will be ignored.
6. Blank space is not allowed
Examples of valid variables:
name, count, No_of_boys, sum_of_digits, mark, distance, _sum
Note A variable name can be chosen by the programmer in a meaningful way so as to reflect
the function or nature of variable in that program.
6

Invalid Variable names


Variable Reason for invalidity
char char is a keyword.
Group one Blank space is not permitted
Price$ $ not allowed
5c4 Must begin with alphabet or underscore
DATA TYPES
C language is rich in its data types. The variety of data types available allows the programmer to
select the type appropriate to the needs of the application as well as machine.
ANSI C supports four classes of data types.
1. Primary or Fundamental Data type
2. Derived Data type
3. User defined data type
4. Empty data set
Primary Data Type
All C compilers support four fundamental data types, namely int, char, float and double.
Integer data type is also classified into four types. They are
Integer
Unsigned integer
Short integer
Long integer
The following table shows the data type, corresponding keywords, size and range on a 16 bit
machine.
Data type Keyword Size Range
(Bits) From To
Character char 8 -127 128
Unsigned Character unsigned char 8 0 255
Short integer short int 8 -127 128
Unsigned short unsigned short int 8 0 255
integer
Integer int 16 -32768 32767
Unsigned integer unsigned int 16 0 65535
Long integer long int 32 -2,14,74,83,648 2,14,74,83,647
Unsigned Long unsigned long int 32 0 4,29,49,67,295
Integer
Floating point float 32 3.4E-38 3.4E38
-38
(3.4x10 ) (3.4x1038)
Floating point double 64 1.7E-308 1.7E308
-308
double precision (1.7x10 ) (1.7x10308)
Extended double long double 80 3.4E-4932 1.1E+4932
precision Floating
(1.1x10-4932) (1.1x104932)
point
7

DECLARATION OF VARIABLES
After designing a suitable variable names and data types, we must declare them to the compiler.
Declaration does the two things
1. It tells the compiler what the variable name is.
2. It specifies what type of data the variable will hold.
Declaring one variable
The syntax ( general format) of declaring one variable is
datatype Variablename;
Where
datatype Any valid data type
variablename Any valid variable name
A declaration statement must end with a semicolon ( ; ).
Example:
int a;
float x;
char ch;
long int count;
Declaring More than one variable
The syntax ( general format) of declaring more than one variable using single statement is
datatype v1, v2, v3, , vn;
Where
datatype Any valid data type
v1, v2, v3, , vn Variable names
The variables are separated by comma(,)
Example :
int a,b,c;
double pi, alpha;
unsigned int x,y;
Initializing variable while declaration
The syntax ( general format) is
datatype v1 = c1, v2 = c2, vn = cn;
Where
datatype Any valid data type
v1, v2, v3, , vn Variable names
c1, c2,,cn constants assigned to variables v1,v2,,vn respectively.
Example:
Declaration Meaning
int i = 10, j=20; Variables i and j are declared as integers. The initial
value of i is 10 and of j is 20
char gender = M; Variable gender is declared as character data type and
its initial value is M
float x = 5.0; Variable x is declared as float and its initial value is 5.0
8

OPERATORS
C supports rich set of operators. Operators are used to manipulate data and variables.
C operators can be classified into number of categories. They are
1. Arithmetic Operators
2. Relational Operators
3. Logical Operators
4. Assignment Operators
5. Unary Operators
6. Conditional Operators
7. Bitwise Operators
ARITHMETIC OPERATORS
The operators +, - , *, / , and % area called as arithmetic operators. Their meaning is
given the table below
Operator Meaning Example Result
+ (Plus) Addition (or ) Unary Plus A+B
i.e. plus sign 5+6 11
5.3 + 6.7 12.0
- (Minus) Subtraction (or) unary CD
minus i.e. mines sign 67 -11
-5 + 7 2
* (Asterisk) Multiplication A*B
15 * 3 45
-5.2 * 3 -15.6
/ (slash) Division X/Y
8/4 2
4/8 0
4.0/8.0 0.5
1.0/3.0 0.333333
% Modulo division A%B
( Remainder after integer 5%4 1
Division) 6%3 0
-5 % 2 -1
5 % -2 1

ARITHMETIC EXPRESSIONS
Variables, arithmetic operators and paranthesis can be used to form the arithmetic
expressions.
Rules for writing arithmetic expressions
1. Each operation should be specified by its corresponding operator explicitly.
2. No two operators can be written successively.
9

Examples:
Algebraic Expressions C Expressions
AB + C A*B+C
(m+n)(x+y) (m+n) * (x+y)
ab (a * b) / c (or) a * b / c
c
ax2 + bx + c a*x*x+b*x+c
x+y x/y+c
c
r2h pi * r * r * h
+ ( alpha + beta ) / (A + B )
A+B
ab+d ab/c+d
c

RELATIONAL OPERATORS
The relational operators are used to compare two variables or expressions or values.
This will results either true or false. If the result is true it will return the value 1. If the result is
true it will return the value 0. The following tables show the relational operators and its uses.
Operator Meaning
< Less than
<= Less than or equal to
> Greater than
>= Greater than or equal to
== Equal
Relational Expressions can be formed by variable, numbers and relational operators.
The general form of relational expression is
Arithmetic expression relational operator Arithmetic expression
Examples of relational expressions are given in the following table.
a = 10, b = 25, sales = 2000, x = -15, y = 10
Relational expression Result
Logic Value
a>b False 0
a <= b True 1
sales == 2000 True 1
(x+y) > a False 0
b >= x True 1
x>y False 0

LOGICAL OPERATORS
Logical operators are used to test more than one condition and make decisions. An expression
which combines two or more relational expressions is termed as a logical expressions or
compound relational expression. Like simple relational expression this will also yields 0 or 1
according to true or false.
C provides three logical operators namely AND (&&), OR( ) and NOT ( ! ).
10

OPERATOR MEANING
& AND
OR
&& AND (SHORT CIRCUIT)
OR (SHORT CIRCUIT)
! NOT
LOGICAL OPERATORS
AND operator yields true ( 1 ) only when both the operands are true. For all other values AND
operator will yields false ( 0 ). OR operator yields false only when both the operands are false
( 0 ). For all other values OR operator will yields true ( 1 ). The following table shows the
TRUTH TABLE for AND, OR operators
A B RESULT
(First operand) ( Second Operand) A&B AB
TRUE (1) TRUE (1) TRUE (1) TRUE (1)
TRUE (1) FALSE ( 0 ) FALSE ( 0 ) TRUE (1)
FALSE ( 0 ) TRUE (1) FALSE ( 0 ) TRUE (1)
FALSE ( 0 ) FALSE ( 0 ) FALSE ( 0 ) FALSE ( 0 )
Relational and Logical expressions are used in decision statements such as, if, while to decide
the course of the action of a program.
UNARY OPERATORS
C provides two Unary operators called increment and decrement operators ++ and --.
The + + operator adds1 to the operand while -- subtracts 1. These operators can be used with
prefix or postfix to the operand.
Postfix and prefix unary increment operators mean the same when they form independent
statement. But if they are used in expressions on the right hand side of an assignment statement
they behave differently.
Example :
Operator Used as independent statement Used in expressions
Increment Postfix Example: Example:
a++ ; b = a++;
(++)
Meaning: Meaning:
a = a + 1; b=a;
a = a+1;
Prefix Example: Example:
++ a ; b = ++a;
Meaning: Meaning:
a = a + 1; a = a+1;
b = a;
Decrement Postfix Example: Example:
a-- ; b = a--;
( -- )
Meaning: Meaning:
a = a - 1; b=a;
a = a-1;
Prefix Example: Example:
-- a ; b = --a;
Meaning: Meaning:
a = a - 1; a = a - 1;
b = a;
11

Conditional operator
The ternary operator pair ?: is used to construct conditional expressions. The general form of
Conditional expression is
Exp1? Exp2: Exp3 ;
Where
Exp1 Relational or logical expression
Exp2, Exp3 Arithmetic expression, or value, or variable
Working of Conditional operator
Exp1 will be evaluated first. If Exp1 is true i.e. 1 then Exp2 will be executed other wise Exp3
will be evaluated.
Example:
Let a = 5 and b = 10;
1. a<b ? a++ : b ++;
Result:
The expression a>b is true, therefore a++ will be evaluated. i.e. after
evaluating this statement a = 6 and b = 10
2. x = a<b? a: b;
Result :
a<b is true, therefore x = a. i.e. x = 5.
Bitwise operators
Bitwise operators are used to manipulate data at bit level. These operators are used for testing
the bits or shifting them right or left. Bitwise operators can only be used with integer data types.
It cannot be applied to float or double.
There are three types of bitwise operators used in C language they are
1. Bitwise logical operators
2. Bitwise shift operators
3. Ones complement operator
Bitwise logical operators
Operator Meaning Example
Expression Result
& Bitwise AND 2&6 2
3&5 1
Bitwise OR 26 6
35 7
^ Bitwise Exclusive OR 2^6 4
3^6 6
Bitwise shift operators
Right shift operator >> causes all the bits in the operand ( op) to be shifted to the right by n
position. The general format of right shift operator is op >> n,
Where op operator and n number of bits
Left shift operator << causes all the bits in the operand ( op) to be shifted to the Left by n
position.
The general format of Left shift operator is op << n,
Here op operator and n number of bits
12

Operator Meaning Example


Expression Result
>> Right Shift 24 >> 2 6
24 >> 3 3
<< Left Shift 24 << 2 96
24 << 3 192

Assignment operator (=)


Assignment operator (=) is used to assign value to the left hand side variables. The general
format is
variable = expression;
where variable any valid variable name
expression any valid expression
Here right hand side expression will be evaluated first and is assigned to the left hand side
variable
Example
Example Meaning
a = 10; Constant 10 is assigned to the variable a
x = a + b; The sum of a and b will be stored in the variable x
a = b = 10; 10 is assigned to b in turns b is assigned to a. i.e. here 10 will
be stored in the variables a and b.
Arithmetic and assignment operators
Arithmetic operators immediately followed by the assignment operators are known as
arithmetic and assignment operators. The following are the arithmetic and assignment
operators
Operator Meaning Example
Expression Meaning
+= Plus equal to a += 1; a = a + 1;
-= minus equal to a -= b; a = a b;
*= Asterisk and equal to x *= 12; x = x + 12;
/= slash equal to m /= n; m = m/n;
%= percentage equal to d %= 2; d = d % 2;
SYMBOLIC CONSTANTS
Symbolic constants are used to define certain unique constants in a program. The general format
of defining symbolic constant is
#define symbolic_name Constant
Where define is a keyword,
symbolic_name any valid variable name
constant any valid constant
Symbolic names are sometimes called as constant identifiers. Since symbolic names are
constants (not variables ), they do not appear in declarations.
13

The following rules apply to a #define statement which define a symbolic constant.
1. Symbolic names have the same form as variable names. ( Symbolic names are written in
CAPITALS to visually distinguish them from the normal variables which are normally
written in lowercase letters. This is only a convention, not a rule )
2. There should not be any blank space between the pound sign # sign and the keyword
define
3. # must be the first character in the line.
4. A blank space is required between #define and symbolic name and between symbolic
name and the constant.
5. #define statement must not end with a semicolon
6. After definition, the symbolic name should not be assigned to any other value within the
program by using an assignment statement. For example, STRENGTH = 200 is invalid.
7. Symbolic names are NOT declared for data types. Its data type depends on the type of
constant.
8. #define statements may appear anywhere in the program but before it is referenced in the
program ( The usual practice is to place them in the beginning of the program)
#define statement is a preprocessor compiler directive and is much more powerful.
Valid Examples :
#define STRENGTH 100
#define PASS_MARK 50
#define MAX 200
#define PI 3.14159
Examples of invalid #define statements
Statement Validity Remarks
#define X = 2.5 Invalid = sign is not allowed
# define MAX 50 Invalid Space between # and define is not allowed
#define N 20; Invalid Semicolon no allowed
#define A 10, B 20 Invalid A statement can define only one name
#Define ARRAY 11 Invalid define should be in lowercase letters
#define PRIN$ 100 Invalid PRIN$ is not a valid variable

ORDER OF EVALUATION
If all the operators are used in an expression then C uses some rules to evaluate the expressions
by giving priorities to the operators called hierarchy of operators or order of evaluation. The
rule is
1. All the expressions will be evaluated from left to right.
2. If it contains any paranthesis then the expression within the paranthesis will be evaluated.
3. Then Unary + and unary (sign) operators will be evaluated
4. Unary increment(++) and decrement (--)operators will be evaluated
5. Then arithmetic operators * / and % will be evaluated. These three operators have the
same priority.
6. Then addition and subtraction will be evaluated.
14

7. Then bitwise shift operators will be evaluated.


8. Then <, >, <= and >= operators will be evaluated.
9. Then Equality (==) and non equality operators (!=) will be evaluated.
10. Then bitwise AND (& ) operator will be evaluated
11. Then bitwise XOR ( ^ ) operator will be evaluated
12. Then bitwise OR ( ) operator will be evaluated
13. Then Logical AND (&&) operator will be evaluated
14. Then Logical OR ( ) operator will be evaluated
15. Then Conditional Operator (?:) will be evaluated.( Right to left)
16. Then Assignment operators will be evaluated. (Right to left )
17. And then Comma operator will be evaluated.
Sections in C PROGRAM
Every C program contains three sections.
1. Header Section
2. Type declaration section
3. Instruction Section
Header Section
This section contains header file declaration statements and preprocessor statements. C
language provides so many functions which are already defined and grouped under some header
files.
Some of the header files are
Header files Use
stdio.h Standard input/output functions
math.h Mathematical functions
ctype.h Character testing and conversion functions
string.h String manipulation functions
stdlib.h Utility functions such as string conversion routines,
memory allocation routines, random number generator etc.
time.h Time manipulation functions.
The general format of declaring header files is
#include<headerfile>
Examples
#include<stdio.h>
#include<math.h>
Note : Header files declaration should not terminated with semicolon.
Type declaration section
In C language all the variables used in a program must be declared in the beginning of the
program. This section is called as Type declaration section. We already discussed how to declare
variables.
Instruction section
The Statements which describes the logic of the program will be written in this section. Basically
there are three types of instruction statements. They are
15

1. Input statements
2. Processing Statements
3. Output statements
Input Statements
Input statements are used to get the data from the user for processing. scanf function is
the widely used input statement in a C language. It is used to read a character, string and numeric
values into variables.
The general format of scanf statement is
scanf(control string, &v1, &v2,, &vn);
where
scanf is the keyword which specifies the name of the functions
Control string specifies the field format in which the data is to be entered. It may include
Field (or format) specifications, consisting of the conversion character %, a data
type character(or type specifier), and an optional number specifying the field
width
Blanks, tabs or new lines
v1, v2, vn specifies the address of the locations i.e. variable names where the data is to be
stored. All the variable names, other than arrays and string, must be preceded
with & (ampersand) symbol.
Commonly used scanf format codes are given the table below
Format Code Used to Read
%c Single character
%d Decimal integer
%e, %f, %g Floating point value
%h Short integer
%o Octal integer
%x Hexadecimal integer
%u Unsigned integer
%i Decimal, hexadecimal, or octal integer
%s String
%[..] String of word(s)
scanf format codes
Examples
1. scanf(%d, &a);
Here a is an integer variable. The user must enter an integer constant, and that value will
be stored in the address a.
2. scanf(%c, &ch);
Here the variable ch is a character variable. The user must enter one character, and that
value will be stored in the variable ch.
3. scanf(%f %d, &no, &n);
This statement is used to read a floating point constant to the variable no and one integer
constant to the variable n.
16

Entering Input
Here we must enter one float value and then one integer value. In the format string we
give space between %f and %d therefore we can enter float value and integer value
separated by a space or tab space or a new line. The following types of entering data are
correct
( I ) 5.7 10
( II ) 5.7 10
( III ) 5.7
10
In all the three cases above 5.7 will be stored in the variable no and 10 will be stored in
the variable n.
4. scanf(%s,str);
Here str is the string variable and is an array. So there is no ampersand (&) before str.
5. scanf(%4d,&x);
Here we specify %4d instead of %d .It means the size of the integer. i.e. the maximum
size length of an integer is 4 digits
Entering Input
I. 1235
The value stored in the variable x is 1235
II. 65432
The value stored in the variable x is 6543
III. 12.56
The value stored in the variable x is 12
6. scnaf(%d,%d,%d, &a,&b,&c);
Here the format strings are separated by comma(,) so the input values must also be
entered by using comma (,) as a separator
Entering Input
I. 12,23,34
Here a =12, b = 23, c = 34 will be stored
II. 12 23 34
Since we are not using comma (,) as a separator only 12 will be stored in the
variable a and the remaining variables will have garbage values
7. scanf(%d5%d,%d, &a,&b,&c);
Here we use 5 as a separator between the first and second control string and comma(,)
as a separator between second and third control string. The values must also be entered
in this way.
Entering the input
I. 23522,35
This input is correct so here a = 23 b = 22, c = 35

II. 23,34,45
Here comma(,) is used as a separator between the first and second control string
so that is wrong, because it expects the character 5. Because of that it will
17

terminate the input session so only 23will be stored in the variable a, and the
variables b and c will have the garbage values
III. 23534 40
Here 5 is used as a separator between the first and second control string so that is
correct. But we give a space between second and third values instead of
comma(,), it will terminate the input session . So a = 23 and b = 34 will be stored
and c will have the garbage value.
Reading a character
getch( ) and getchar( ) functions are the simplest functions used to read a character from the user.
The general format of using these functions are
variable = getch( );
or
variable = getchar( );
here variable must be a character variable
Example
1. ch = getch( );
Reads a character to the variable ch.
2. gender = getchar( )
Reads a character to the variable gender.
OUTPUT STATEMENTS
Output statements are used to give data to the user. The processed informations can be
printed using the printf function. printf function is the widely used output statement in a C
language. It is used to print a character, string and numeric values and a combination of all these.
The general format of printf statement is
printf(control string, v1, v2,, vn);
where
printf is the keyword which specifies the name of the functions
Control string specifies how many arguments follow and what their types are. It consists of
three types of items
Character that will be printed on the screen as they appear.
Field (or format) specifications, that define the output format for display of each
item.
Escape sequence characters such as \n, \t and \b
v1, v2, vn specifies the address of the locations i.e. variable names where the data is stored.

Commonly used printf format codes are given the table below
Format Code Print
%c A Single character
%d A Decimal integer
%e Floating point value in exponent form
%f Floating point value without exponent
%g Floating point value with or without
18

exponent without leading zeros


%i Signed decimal integer
%o Octal integer without leading zero
%x Hexadecimal integer
%u Unsigned integer
%s String
%x Integer without leading zero
printf format codes
Examples
1. let a = 12
printf(%d, &a);
The result is
12
2. printf(%f ,5.3);
The result is
5.300000
3. let a = 10, b = -12.5
printf(%d %f,a,b)
The result is
10 -12.500000
4. let sum = 1234.2345
printf(%g,sum);
The result is
1235.2345
5. let a = 5, b = 25
printf(The difference is = %d, a b );
The result is
The difference is = -20
6. Let a =12.34, b = 23.45, c = 34.56
printf(A = %g\tB = %f\nC = %g,a,b,c);
A = 12.34 B = 23.450000
C = 34.56
7. let a = 12, b = 25
printf(Sum of %d and %d is %d,a,b, a+b);
Sum of 12 and 25 is 27
Note : In printf and scanf functions the number of variables and format strings must be one to
one correspondence and the type should also be matched.
19

Steps Involved in writing C program


There are 4 steps involved in executing C programs. they are
1. Creating a Source code
2. Compiling the source code
3. Linking the source code
4. Executing the program
Creating Source code
The program itself is called as a source code. First we have to type the program in high level
language. The extension of the source code is .C
Compiling the source code
The process of converting the program written is high level language into Machine language is
called as compilation. In compilation process C compiler looks for errors in the program, if any
errors occurred, it displays the errors in the program. After correcting the errors it creates the
object file. Object file is created with the same name of the file but the extension is .obj
Linking and executing the program
If there is no error in your program then you can run your program. This will create .exe file,
means executable file. This will create links to the header files. And produce the output of the
program.
Working in Turbo C IDE
Type tc in the command prompt to open Turbo C IDE (Integrated Development
Environment).
Choose File -> save to save the file (or) Press F2 key
Choose File -> open to open the existing file (or) Press F3 key
Choose File -> new to open the new file
Press F10 to select the menu
Choose File -> open to open the existing file (or) Press F3 key
Choose Compile -> Compile to obj to compile the program (or) Press Alt + F9 key
Choose Run -> Run command to Run the program (or ) Press ctrl + F9 key
Choose Run -> User Screen to view the user Screen (or ) Press Alt + F5 Key
Choose File -> Quit to close the turbo C IDE (Or) Press Alt + X
STRUCTURE OF THE PROGRAM
The following is the structure of the simple C program.

header section
main( )
{
declaration statements;
Instruction section
-----
---
}
20

Some common rules in writing C programs


1. Proper header file must be included.
2. The program must contain one and only main function.
3. All the statements of main function must be enclosed within braces i.e. { }. And the
number of { (opening brace )must be equal to the number of }( closing brace)
4. All the C statements must be terminated with the ; ( semi colon ) which excludes main
functions, Header declaration, control structures, function calling and labels.
5. All the variables to be used in the program must be declared at the declaration section.
6. All the keywords must be written in lowercase letters.
Simple C Programs
Prog . 1 Write a program to convert the temperature given in centigrade to Fahrenheit.
Formula
F = 1.8 C + 32
Where F Temperature in Fahrenheit
C Temperature in Centigrade
Program

#include<stdio.h>
main()
{
float c,f;
clrscr( );
printf("\nEnter the temperature in c = ");
scanf("%f",&c);
f = 1.8 * c +32;
printf("%g C = %g F",c,f);
getch( );
}

Expected Output
Enter the temperature in c = 42
42 C = 107.6 F

Prog 2. Write a program to find the addition of two numbers


Program
#include<stdio.h>
main()
{
int a,b,c;
clrscr( );
printf("\nEnter the values of a and b : ");
scanf("%d %d ",&a, &b);
c = a + b;
printf("The sum of %d and %d is = %d", a, b, c);
getch( );
}

Expected Output
Enter the values of a and b : 5 6
The sum of 5 and 6 is = 11
21

prog 3 : Write a program to find the area using the formula area = r2 + 2rh
Program
#include<stdio.h>
main()
{
float r,h,area,pi = 22.0/7.0;
clrscr( );
printf("Enter the value of r : ");
scanf("%f",&r);
printf("Enter the value of h : ");
scanf("%f",&h);
area = pi * r * r + 2 * pi * r * h;
printf("Area = %g",area);
getch();
}

Expected Output
Enter the value of r : 2
Enter the value of h : 3
Area = 50.2857
Prog 4: Write a program to interchange the values of two variables a and b
Program
#include<stdio.h>
main()
{
int a,b,t;
clrscr( );
printf("\nEnter the values of a and b : ");
scanf("%d %d ",&a, &b);
printf(Before Interchanging \n);
printf(a = %d\t b = %d\n, a, b);
t = a;
a = b;
b = t;
printf(After Interchanging \n);
printf(a = %d\t b = %d, a, b);
getch( );
}

Expected Output
Enter the values of a and b : 15 25
Before Interchanging
a = 15 b = 25
After Interchanging
a = 25 b = 15
22

CONTROL STRUCTURES
Decision making and branching
C Program is a set of statements which are normally executed sequentially in the order in the
order in which they appear. But in practice, we have number of situations where we have to
change the order of execution of statements based on certain conditions, or repeat a group of
statements until a certain specific conditions are met. This involves decision making.
C language also has such decision making statements. They are
if statement
if else statement
nested if else statement
goto statement
switch statement
if statement
The general form of if statement is
if( condition )
{
s1;
s2;
--
--
sn;
}
next statement;
Where
condition : A relational expression or logical expression which gives either
zero ( false ) of non zero (true) values
s1, s2 sn : Any valid C statements
next statement : Statement after if statement
Working of if statement
First the condition will be checked, if the condition is true then the statements s1,s2
sn will be evaluated, and goes to the next statement. If the condition is false then the control
goes to the next statement.
Entry

is Yes
condition?

S1, S2 . Sn

No

Next statement

Flow chart of simple if statement


Example : Consider the following segment of a program that is written for processing of marks
obtained in an entrance examination.
if( category == SPORTS)
{
marks = marks + bonus;
}
printf(%f,marks);
It checks whether category is SPORTS or not. If it is, then bonus marks will be added to marks
before they are printed. For others, bonus will not be added to the marks
Note : If more than one statements are used, then it is necessary to enclose the statements
inside the braces { }. If the block contain only one statement there is no need to enclose the
statement within the braces.
23

Example Program : Write a program to read four values a, b, c and d. Evaluate the ratio of
( a+ b ) to (c d ) and print the result, if c d is not equal to zero

Program

#include<stdio.h>
main( )
{
float a,b,c,d,e;
clrscr( );
printf("Enter the values of a, b, c and d : ");
scanf("%f %f %f %f", &a, &b, &c, &d);
if( (c-d) != 0)
{
e = ( a+ b ) / ( c - d );
printf("ratio = %g", e );
}
getch( );
}

Expected output

Enter the values of a, b, c and d : 1.2 2.5 3.5 4.2


ratio = -5.28572

if else statement
The general form of if else
if( condition )
{
True block statements
}
else
{
False block statements
}
next statement;
Where
condition : A relational expression or logical expression which gives either
zero ( false ) of non zero (true) values
true block statements : Any valid C statements
false block statements : Any valid C statements
next statement : Statement after if statement
Working of if else statement
First the condition will be checked, if the condition is true then true block statements
will be evaluated, and goes to the next statement. If the condition is false then false block
statements will be evaluated, the control goes to the next statement.
Entry

No
is Yes
condition?

False block True block


statements statements

next statement

Flow chart of if else statement


Let us consider an example of counting the number of boys and girls in a class. We use code 1
for boy and 2 for girl. The program segment for this is
24

---
---
if(code == 1)
boy++;
else
girl++;
The previous program can also be changed as follows
if( (c-d) != 0)
{
e = ( a+ b ) / ( c - d );
printf("ratio = %g", e );
}
else
printf(c d is zero \n);
Example Programs using if else statement

1. Question : Write a program to determine whether a number is odd or even and print the
message NUMBER IS EVEN (or ) NUMBER IS ODD

PROGRAM

/* program to determine whether the given number is odd or even */


#include<stdio.h>
main( )
{
int number;
clrscr( );
printf("Enter the number : ");
scanf("%d", &number);
if(number % 2 == 0)
printf("NUMBER IS EVEN\n");
else
printf("NUMBER IS ODD\n");
getch( );
}

Expected Output:

Enter the number : 12


NUMBER IS EVEN

Enter the number : 245


NUMBER IS ODD
2. A set of linear equations with two unknowns x1 and x2 is given bellow
ax1 + bx2 = m
cx1 + dx2 = n
md bn na mc
A set has a unique solution x1 = , x1 = provided the denominator
ad bc ad bc
ad bc is not equal to zero. Write a program that will read the values of constants a, b, c, d, m, n
and compute the values of x1 and x2. An appropriate message should be printed if ad bc =
0.

PROGRAM

main( )
{
float a,b,c,d,m,n,x1,x2,den;
clrscr( );
printf("Enter the values of a, b, and m : ");
scanf("%f %f %f", &a, &b, &m);
printf("Enter the values of c, d, and n : ");
scanf("%f %f %f", &c, &d, &n);
den = a * d - c * b;
25

if( den != 0)
{
x1 = (m * d - b * n) / den;
x2 = (n * a - m * c ) / den;
printf("x1 = %g\tx2 = %g",x1,x2);
}
else
printf(" a * d - c * b is zero ");
getch( );
}

Expected Output
Enter the values of a, b and m : 5 6 9
Enter the values of c, d and n : 4 5 3
x1 = 27 x2 = -21
Enter the values of a, b and m : 7 5 9
Enter the values of c, d and n : 7 5 12
a * d b * c is zero
Nested if else statements
When a series of decisions are involved, we may have to use if else structure within
another if else structure. This is called nested if else statement. The general format of if else
structure is

if( test condition1)


{
if(test condition 2)
{
statement 1;
}
else
{
statement 2;
}
}
else
{
if( test condition 3)
{
statement 3;
}
else
{
statement 4;
}
}
next statement;

Working of if else structure described above

1. If the test condition 1 is true, then it checks test condition 2. If test condition 2 is true
then it evaluates statement 1 and goes to next statement. Otherwise it evaluates
statement 2 and goes to next statement.
2. If the test condition 1 is false, then it checks test condition 3. If test condition 3 is true
then it evaluates statement 3 and goes to next statement. Otherwise it evaluates
statement 4 and goes to next statement.
26

Example Program
Question : Write a C program to find the biggest of three numbers.

#include<stdio.h>
main( )
{
float a, b, c;
clrscr( );
printf("Enter the values for a, b and c : ");
scanf("%f %f %f", &a, &b, &c);
if(a > b && a > c)
printf("Biggest value is %g\n",a);
else
if( b > a && b > c )
printf("Biggest value is %g\n",b);
else
if(c > a && c > b )
printf("Biggest value is %g\n",c);
else
printf(" A, B and C are equal\n");
getch( );
}
Expected Output

Enter the values for a, b and c : 15 68 57


Biggest value is 68

Enter the values for a, b and c : 155 8 7


Biggest value is 155
Enter the values for a, b and c : 10 10 10
A, B and C are equal
else if ladder
else statement can also be replaced with else if, if more conditions are to be checked. The
difference between else and else if ladder is that, in else if ladder we can check another condition,
whereas in else we cannot.
The previous program of finding the biggest of three numbers can be replaced by the
following using else if ladder

#include<stdio.h>
main( )
{
float a, b, c;
clrscr( );
printf("Enter the values for a, b and c : ");
scanf("%f %f %f", &a, &b, &c);
if(a > b && a > c)
printf("Biggest value is %g\n",a);
else if( b > a && b > c )
printf("Biggest value is %g\n",b);
else if(c > a && c > b )
printf("Biggest value is %g\n",c);
else
printf(" A, B and C are equal\n");
getch( );
}
The goto Statement
goto statement is used to transfer control form one point to another point in the program
unconditionally. Therefore it is also called as unconditional goto statement. The goto
statement requires a label in order to identify the place where the branch is to be made. goto
statement can transfer the control in forward or backward direction
The general form of goto statement is
goto label; label:
--- ---
-- forward jump --- backward jump
label: goto label;
--- -----
27

Example Program
Write a program to find the square root of a given number using the sqrt( ) function
program
#include<stdio.h>
#include<math.h>
main( )
{
long float x, y;
clrscr();
start:
printf(Enter the value of x : );
scanf("%lf", &x);
if(x<0)
{
printf(Enter positive number\n);
goto start;
}
y=sqrt(x);
printf("sqrt(%g) = %g", x, y);
getch( );
}
Expected output
Enter the value of x : -25
Enter the positive number
Enter the value of x : 25
sqrt(25) = 5

Question : Write a program to solve the quadratic equation ax2 + bx + c = 0.


Solutions:
-b + b2 - 4ac
x= , if b2 - 4ac < 0 then the roots are imaginary,
2a
if b2 - 4ac > 0 then the roots are real and unequal, b2 - 4ac = 0 then the roots are real and equal.
Program
#include<stdio.h>
#include<math.h>
main( )
{
float a,b,c,x,x1,x2,d;
clrscr();
printf("Enter the values of a, b and c : ");
scanf("%f %f %f", &a, &b, &c);
if(a == 0)
{
printf("Not a quadratic equation ");
goto stop;
}
d = b * b - 4 * a * c;
if(d < 0 )
printf("roots are imaginary ");
else if(d == 0)
{
printf("Roots are real and equal\n");
x = - b / (2 * a);
printf("x = %g",x);
}
else
{
printf("Roots are real and unequal\n");
x1 = (-b + sqrt(d))/(2 * a);
x2 = (-b - sqrt(d))/(2 * a);
printf("x1 = %g\tx2 = %g",x1,x2);
}
stop:
getch( );
}
Expected Output
28

1.
Enter the values a, b and c : 1 2 3
roots are imaginary
2.
Enter the values a, b and c : 1 2 1
Roots are real and equal
x = -1
3.
Enter the values a, b and c : 1 5 6
roots are real and unequal
4.
Enter the values a, b and c : 0 23 6
Not a quadratic equation
Question : An electricity power distribution company charges its domestic consumers as follows
Consumption units Rate of charge
0 200 Rs. 0.50 per unit
201 400 Rs. 100 plus Rs. 0.65 per unit excess of 200
401 600 Rs. 230 plus Rs. 0.80 per unit excess of 400
600 and above Rs. 390 plus Rs. 1.00 per unit excess of 600
Write a program that reads the customer number and power consumed and prints the amounts to
be paid by the customer.

Program

#include<stdio.h>
main( )
{
int units,customerno;
float rate;
clrscr( );
start:
printf("\n\nEnter the customer no and units consumed : ");
scanf("%d %d",&customerno,&units);
if(units < 0)
{
printf("Enter the correct unit value : \n");
goto start;
}
if(units > 600)
rate = 390 + (units - 600);
else if(units > 400)
rate = 230 + 0.8 * (units - 400);
else if(units > 200)
rate = 100 + 0.65 * (units - 200);
else
rate = 0.5 * units;
printf("\nCUSTOMER NO = %d\t, customerno);
printf(Amount = Rs. %.2g\n",,rate);
getch( );
}

Expected output
Enter the customer no and units consumed : 1000 -500
Enter the correct unit value :
Enter the customer no and units consumed : 1000 500

CUSTOMER NO = 1000 Amount = Rs. 310


29

switch statement
switch is a multi-way decision statement. The switch statement tests the value of a given variable
or expression against a list of case values and when a match is found, a block statements
associated with that case will be executed. The general form of the switch statements is
switch(expression)
{
case value -1:
block 1
break;
case value -2:
block 2
break;
case value _ 3:
-----
-----
case value -n:
block n
break;
default:
block 1
}
where
expression is an integer expression or characters
Value -1, Value -2, Value n are constants known as case labels. Each of these
values should be unique within a switch statement.
block 1, block -2 block-3 are statement lists that may contain zero or more
statements. There is no need to put braces around these blocks.
case statements ends with a colon(:)
Execution of switch statement
When the switch is executed, the value of the expression is successively compared
against the values Value -1, Value -2, Value n. If a case is found whose value matches with
the current value of the expression, then the block of statements that follow the case are
executed. If no case is matched then the statements in a default block will be executed.
The break statement at the end of each block signals the end of a particular case and
causes an exit from the switch statement.
Flow chart representing the process of switch statement

No
is
expression?

Value 1
block 1 break

Value 2
block 2 break

Value n
block n break

default Next statement

Example
30

---
ch = getch( );
switch(ch)
{
case A :
case a :
printf(Air service );
break;
case B :
case b :
printf(Bus service );
break;
case T :
case t :
printf(Train service );
break;
default :
printf( No Choice);
}
--- -
It is possible to nest the switch statements. i.e. a switch may be a part of a case block. ANSI C
allows 15 levels of nesting and as many as 257 case labels
Program
Question : In an institution, grading the students done according to the following rules:
Average Marks Grade
80 to 100 Honours
60 to 79 First Division
50 to 59 Second Division
40 to 49 Third Division
0 to 39 Fail
Write a Program to read the marks of the student if 5 subject, and calculate the average marks
and print the student grade.
Program

#include<stdio.h>
main( )
{
int m1,m2,m3,m4,m5,ave,index;
clrscr( );
printf("Enter the marks of the student in 5 subject : ");
scanf("%d %d %d %d %d",&m1, &m2, &m3, &m4, &m5);
ave = (m1 + m2 + m3 + m4 + m5 )/5;
printf("Average = %d\n",ave);
index = ave / 10;
switch(index)
{
case 10:
case 9:
case 8:
printf("Grade : Honours");
break;
case 7:
case 6:
printf("Grade : First Division");
break;
case 5:
printf("Grade : Second Division");
break;
case 4:
printf("Grade : Third Division");
break;
default:
printf("Grade : Fail");
}
getch( );
}
Expected Output:
31

Enter the marks of the student in 5 subject : 99 98 95 86 97


Average = 95
Grade : Honours

Enter the marks of the student in 5 subject : 99 98 95 86 97


Average = 95
Grade : Honours

Enter the marks of the student in 5 subject : 54 23 24 25 26


Average = 30
Grade : Fail
Loop Structure
Introduction
Executing a set of statements repeatedly until some condition reached is called as
looping. In looping, a set of statements are executed until some conditions for termination of the
loop are satisfied. So, a program loop consists of two segments, body of the loop and control
statement. The control statement tests certain conditions and then directs the repeated execution
of statements contained in the body of the loop.
Depending upon the position of the control structure in the loop, a loop structure
can be classified as entry controlled loop or exit controlled loop. In entry controlled loop, the
control statement will be evaluated first, If the condition is true then only the body of the loop
will be evaluated. Whereas in exit controlled loop, the body of the loop will be evaluated first
and then the condition is checked, therefore the body of the loop is executed unconditionally for
the first time.
A looping process, in general, would include the following steps:
1. Setting and initialization of a counter
2. Execution of the statements in the loop
3. Incrementing the counter
4. Test for a specified condition

Entry controlled 1 4 2 3 4 2 3
Exit Controlled 1 2 3 4 2 3 4
C language provides three loop constructs. They are
while loop structure Entry controlled
do - while loop structure Exit Controlled
for loop structure Entry Controlled
while loop structure
This is the simplest of loop structures in C. The while loop is an entry controlled loop.
The general format of the while loop is
while( test condition )
{
body of the loop
}
next statement;
where
test condition is any valid logical expression
body of the loop consists of any valid C statements, control structures etc
Working of while loop
The test condition is evaluated first and if it is true, then the body of the loop will be
executed. After the execution of the body, the test condition is once again checked, if it is true
the body is executed once again. This process continues as long as the test condition is true. If it
becomes false the control is transferred out of the loop i.e. to the next statement.

No
is
test condition?

Yes
Body of the loop
Next Statement
32

Example
i = 1;
while(i < 10)
{
printf(%d , i * i );
i = i--;
}
Here i is the counter variable. The body of the loop will be evaluated for the values of i=1, 2, 3,
4, 5, 6, 7, 8, and 9. So the loop will be evaluated for 9 times. This loop will print 1 4 9 16 25 36
49 64 81.
Example Program
Question : Write a program to find the factorial of n. i.e. n!.
Program
main( )
{
long fact=1;
int n,i=1;
clrscr( );
read:
printf("Enter the value for n : ");
scanf("%d",&n);
if(n<=0)
{
printf("Enter the positive value for n : \n");
goto read;
}
while(i<=n)
{
fact = fact * i;
i++;
}
printf(" %d! = %ld", n, fact);
getch( );
}
Expected Output

Enter the value for n : -6


Enter the positive value for n : 5
Enter the value for n : 5! = 120

Question : Write a program to print 1 2 4 8 16 32 64 128 up to N numbers

#include<stdio.h>
main( )
{
int N,i=1;
long int sum = 1;
clrscr( );
printf("Enter the value for N :" );
scanf("%d", &N);
printf("The series is :\n%ld\t", sum);
while( i < N)
{
sum *= 2;
printf("%ld\t", sum);
i++;
}
getch( );
}
33

Expected output
Enter the value for N : 6
The series is :
1 2 4 8 16 32

do while loop structure


do while loop structure is similar to while loop structure, but the main difference is, in do
while loop structure the condition is checked at the end of the loop. i.e. while loop structure is
entry controlled loop whereas do while loop structure is exit controlled loop. So, in do while
loop structure ,there is guarantee that the body of the loop will be executed for at least one time,
even if the test condition is false at the beginning of the loop.
The general format of do while loop structure is
do
{
body of the loop
} while(test condition);
next statement
Here the do while structure is terminated with semicolon ( ; ). while loop structure
should not be terminated with semicolon.
Working of do while loop
The body of the loop will be evaluated first, then the test condition will be checked. If the
test condition is true, then again the body of the loop will be executed. If the test condition is
false it goes to the next statement immediately after the do while loop.
Flow chart

Body of the loop

Is True
test condition?

False

Next statement

flow chart for do while loop


Example Program
Question : Write a program to find the value of y = xn.
Program

#include<stdio.h>
main( )
{
long y=1;
int x,n,i = 1;
clrscr( );
printf("Enter the value for x : ");
scanf("%d",&x);
printf("Enter the value for n : ");
scanf("%d",&n);
do
{
y = y * x;
}while(++i<=n);
printf(" %d power %d = %ld", x, n, y);
34

getch( );
}

Expected output
Enter the value for x : 5
Enter the value for n : 3
5 power 3 = 125

Question : Write a program to find the sum of the digits in an integer number. For Ex if the
number is 12345, the its sum of the digits is 1 + 2 + 3 + 4 + 5 = 15
Program
#include<stdio.h>
main( )
{
int n, digit, r, q,sum = 0;
clrscr( );
start: printf("Enter the number for n between 0 and 32767 : ");
scanf("%d",&n);
if( n < 0 )
{
printf("enter the number between 0 and 32767 : ");
goto start;
}
q = n;
do
{
r = q % 10;
sum += r;
q = q/10;

} while(q != 0);
printf("the number is = %d\n",n);
printf("sum of digits = %d", sum);
getch( );
}
Expected output
Enter the number for n between 0 and 32767 : 5684
the number is = 5684
sum of digits = 23

for loop structure


for loop is the counter style loop in a C language. It is also the entry controlled loop.
The general form is
for(initialization; test condition; increment)
{
body of the loop
}
next statement;
where
initialization initial value of Counter variable is assigned
test condition logical expression results either true of false
increment Counter variable is altered
Working of for loop
1. Initial value of Counter variable is assigned first
2. Then test condition will be checked. If it is true, then the body of the loop will be
evaluated. If it is false the control will be transfer to the next statement immediately
after the for loop
3. After executing the statements in the body of the loop, counter variable will be altered
by executing the statement in increment section
35

Flow chart

Initialization

Increament

True
Is Body of the
test condition ? loop

No

Next statement

Example
for( n = 1; n <10; n ++)
printf(%d\t, n * n);
The above loop will be evaluated for the values of n = 1, 2, 3 9. i.e. the body of the loop will
be executed for 9 times. This loop contains only one statement. The loop will print the following
1 4 9 16 25 36 49 64 81

Example Program
Question : Write a C program to print the first N Fibonacci numbers. i.e 1 1 2 3 5 8 13
Program
#include<stdio.h>
main( )
{
int first = 0,second = 1,third,n,count ;
clrscr( );
printf("Enter the number of elements : ");
scanf("%d",&n);
printf("Fibonacci Series\n %d\t%d\t", first, second);
for(count = 2; count < n; count++ )
{
third = first + second;
printf("%d\t",third);
first = second;
second = third;
}
getch( );
}
Expected output
Enter the number of elements : 10
Fibonacci Series
0 1 1 2 3 5 8 13 21 34
Skipping the loops
Some times we need to skip the loops before the completion of the loops. C provides two
statements for this task. They are break and continue statements.
break statement
break statement is used to skip the loop completely. If break statement is executed, the
remaining iteration of the loop will be skipped. Let us consider the following loop
for(i = 0; i < 10; i++)
{
scanf(%d,&n)
if (n <0)
break;
36

}
in the above example, it is expected that , the loop to be evaluated for 10 times. But if you enter
negative value for n it will terminate the loop.

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


{
printf(%d, i)
if (i == 5)
break;
}
This loop will be executed for only 6 times.
continue statement
continue statement is used to skip the part of the loop. it transfer the controls to the next
iteration loop.
Example
n = 0;
while(n<10)
{
if(n %2 == 0)
continue;
printf(%d\t, n);
}
This program segment will print
1 3 5 7 9
because when n % 2 = 0, continue statement will be executed. it skips the print
statement
37

String Handling Functions


Strings can be manipulated in three different ways. They are
string comparison : Used to compare two strings
string copying : Used to copy one string to a string variable
string concatenation : Used to add two strings
In C language all the string manipulation functions are stored under the header file string.h.
STRING CONCATENATION
There are two string concatenation functions are available in C language. They are strcat( ),
strncat( ).
strcat ( ) function
The general format of strcat ( ) function is
strcat(str1,str2);
Where
strcat is the name of the function
str1, str2 are string variables
strcat( str1, str2) function is used to add the content of str1 and str2. The result will be stored
in the variable str1. The second argument str2 need not be a string variable rather can be a
string constant.
Example :
char str1[100] = welcome to;
char str2[100] = SBCP;
strcat(str1,str2);
Result : Now welcome to SBCP will be stored in the variable str1. str2 value will not be
changed.
strncat( )
The general format of strncat ( ) function is
strncat(str1,str2,n);
Where
strcat is the name of the function
str1, str2 are string variables
n is the integer number or variable
strcat( str1, str2,n) function is used to add n characters of str2 to the variable str1 The result
will be stored in the variable str1. The second argument str2 need not be a string variable rather
can be a string constant.
Example
char str1[100] = welcome to;
char str2[100] = SBCP;
strncat(str1,str2,2);
Result : Now welcome to SB will be stored in the variable str1, i.e. only first two characters SB
from str2 is added to the string str2. str2 value will not be changed.
String copying.
strcpy( ) and strncpy( ) are the two functions used to copy the string.
strcpy( ) function
The general form of strcpy( ) is
strcpy(str1,str2);
Where
strcpy is the name of the function
str1, str2 are string variables
strcpy(str1,str2) function is used to copy str2 into str1. In other words the contents of str1 will
be completely replaced by the contents of str2. The previous value of str1 will be replaced by
the value of str2. The second argument str2 need not be a string variable rather can be a string
constant.
Example
char str1[100] = Computer;
char str2[100] = Graphics;
strcpy(str1,str2);
Result : Now in Graphics will be stored in str1. str2 value will not be changed
strncpy( ) function
The general form of strncpy( ) is
strncpy(str1,str2,n);
Where
strcpy is the name of the function
38

str1, str2 are string variables


n is and integer constant or variable
strncpy(str1,str2,n) function is used to copy first n characters of str2 into the first n characters
of str1, the remaining characters of str1 will not be changed. In other words first n characters
of the contents of str1 will be replaced by the first n characters of str2. str2 value will not be
changed. The second argument str2 need not be a string variable rather can be a string
constant.
Example
char str1[100] = Computer;
char str2[100] = Simple;
strncpy(str1,str2,2);
Result : The first two letters of str1 i.e. Co will be replaced by the first two character of str2 i.e.
Si . So now Simputer will be stored in str1. str2 value will not be changed.
Suppose if you use the following statement
strncpy(str2,str1,2);

Result : The first two letters of str2 i.e. Si will be replaced by the first two character of str1 i.e.
Co . So now Comple will be stored in str2. str1 value will not be changed.
String Comparison
There are four String comparison functions are available in C. They are strcmp( ), stricmp( ),
strncmp ( ) and strnicmp ( ).
strcmp( ) function
The general form of this function is
strcmp(str1, str2);
Where
str1, str2 are string variables or constants
strcmp(str1,str2) function compare the two strings str1 and str2 and returns an integer number.
The ASCII VALUE difference between the first non matching character in the strings str1 and
str2 will be the integer number. The integer number will be
0 if str1 and str2 are same
negative number if str1 < str2
positive number if str1 > str2.

If the difference is negative means that the first string is alphabetically above the second
string. strcmp( ) function is case sensitive, i.e. lowercase letters are different from uppercase
letters.
Example
1. n = strcmp(Welcome, Hello)
The first non matching character of Welcome and Hello is W and H. The ASCII
value of W is 87and of H is 72 , therefore the difference is 87 72 i.e. 15. So 15 will be
assigned to the variable n
2. n = strcmp(Hello, Welcome)
The first non matching character of Hello and Welcome is H and W. The ASCII
value of H is 72 and of W is 87 , therefore the difference is 72 87 i.e. -15. So -15 will
be assigned to the variable n
3. printf(%d,strcmp(Welcome,Welcome))
The strings are equal so it will print 0.
4. char str1[100] = C Programming;
char str2[100] = c programming
printf(%d,strcmp(str1,str2);

This will print -32, because the ASCII value of C is 67 and of c is 99.
stricmp( )function
stricmp( ) function is similar to the strcmp( ) function. But the only difference is it is non case
sensitive. The letter i in stricmp indicates ignore case. The general format of stricmp function is
stricmp(str1, str2);
Example
char str1[100] = C Programming;
char str2[100] = c programming
printf(%d,stricmp(str1,str2);

This will print 0, because in stricmp( ) function uppercase letters and lowercase letters are
treated as same characters.
39

strncmp( ) function
The general form of this function is
strncmp(str1, str2,n);
Where
n integer variable or constatnt
str1, str2 are string variables or constants
strncmp(str1,str2,n) is similar to strcmp(str1,str2), but it compares only first n characters of
str1 and str2.
Example
char str1[100] = company;
char str2[100] = computer
printf(%d,strncmp(str1,str2,4);
Result
This will print 0, because the function strncmp(str1,str2,4) compares the first 4
characters of str1 and str2. Both str1 and str2 has comp as first 4 characters. So there is
no non matching characters are in these strings.
But
printf(%d,strncmp(str1,str2,5);
will results -20. The reason is, though the first 4 characters are same in str1 and str2, the
fifth character in str1 is a and of str2 is u.
strnicmp( ) function
The general form of this function is
strnicmp(str1, str2,n);
Where
n integer variable or constatnt
str1, str2 are string variables or constants
strnicmp(str1,str2,n) is similar to strncmp(str1,str2,n). But the only difference is it is non case
sensitive.
char str1[100] = COMPUTER;
char str2[100] = computer
printf(%d,strnicmp(str1,str2,4);
Result
This will print 0,
strlen( ) function
strlen( ) function is used to find the length of the string, i.e. it returns the total number of
characters in the specified string. The syntax of this function is
strlen(str);
where
str is the string variable or constant
strupr( ) function
strupr( ) function converts all lowercase letters into uppercase letters. The general
format of this function is
strupr(str);
Example
char str[100] = Tamil nadu;
strupr(str);
printf(%s,str);
Result
This will print TAMIL NADU
strlwr( ) function
strlwr( ) function converts all uppercase letters into lowercase letters. The general
format of this function is
strlwr(str);
Example
char str[100] = Tamil nadu;
strlwr(str);
printf(%s,str);
Result
This will print tamil nadu
40

Example Program

Question : Write a C program


1. to read the two strings str1 and strt2
2. find the length of the strings
3. copy str1 into another string str3
4. add str1 and str2
5. compare str1 and str2
6. convert all the lowercase letters of str3 into uppercase letters
7. convert all the uppercase letters of str2 into lowercase letters
Program

main( )
{
char str1[100],str2[100], str3[100];
clrscr( );
printf("Enter First String : ");
gets(str1);
printf("Enter second String : ");
gets(str2);
printf("string 1 = %s\nString2 = %s\n",str1,str2);
printf("Length of str1 = %d\n",strlen(str1));
printf("Length of str2 = %d\n",strlen(str2));
strcpy(str3,str1);
printf("String 3 after copying = %s\n",str3);
strcat(str1,str2);
printf("str1 after String Addition = %s\n",str1);
printf("upper case of str3 = %s\n",strupr(str3));
printf("lower case of str2 = %s\n", strlwr(str2));
getch( );
}

Expected Output
Enter First String : sbcp
Enter second String : Computer Lab
string 1 = sbcp
String2 = Computer Lab
Length of str1 = 4
Length of str2 = 12
String 3 after copying = sbcp
str1 after String Addition = sbcpComputer Lab
upper case of str3 = SBCP
lower case of str2 = computer lab
41

FUNCTIONS
INTRODUCTION
A program can be used for solving a simple problem or large and complex problem.
Programs solving simple problems are easier to understand and identify mistakes. If the program
is large, it is difficult to understand the steps involved in it. Hence it is subdivided into a number
of smaller problems. Error in a program is called bug. Correcting the error is known as
debugging.
Advantages of functions
1. Debugging is easier
2. It is easier to understand the logic of the program
3. Testing is easier
4. Functions are helpful in generalizing the program
Defining functions
The general format of function definition is

returntype functionname(type v1, type v2, type v3, type vn)


{
Local Variables Declaration Body of the
statements function
return(expression);
}
Where
returntype - Any valid data type like int, float, long int, char etc.
If a function returns an integer value, then there is no need
to specify the returntype.
If a function returns values other than integer value, then
you must specify the returntype.

functionname - It is the name of the function. The rules for naming function
are same as the rules for naming variables.

Local Variables - Local variables are variables, which are declared within the
body of the function. They have no meaning outside the
function in which it is declared.

V1, V2, V3Vn - These are parameters or arguments on which the function
operates. They are also called as dummy variables. Each
argument must be declared separately. If more than one
parameters are there then they must be separated with
comma (,).

Statements - Any Valid C statements like input, output , branching,


looping or function calling.

return(expression) - If a function returns any value then it must contain a return


statement. Here return is a key word.
return statement is used to return the value to the calling
function.
If a function returns a value, Then it will return only one
value to the calling functions.
The general format of return statement is
return(expression or constant or variable);
Example
mul( int a, int b)
{
int c;
c = a * b;
return (c);
}
42

Here
mul is the function name
a , b are arguments or dummy variables of integer data type.
c - is the local variable
This function returns multiplication of a and b. It returns an integer value. So there is no need to
specify the return type.

Array
Group of variables of similar type
Arrayname[subscript]

Array name variable name


Subscript any positive integer

Ex a[0], a[10] alpha[25] x[56]

Array with one subscript one dimensional array

Array with two subscripts two dimensional array a[10][10]

Declaration of One dimensional array

datatype arrayname[size];

size any positive integer number of elements in an array

1. int x[10];

Members of this array x[0] x[1] x[2] x[3] x[4] x[5] . X[


X 0 1 2 3 4 5 6 7 8 9

READING VALUES FOR ARRAYS

Using loop for loop

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


{
scanf(%d, x [ i ] );
}

1+2+3+4+5+6+7++n