Академический Документы
Профессиональный Документы
Культура Документы
htm
l
Fundamentals of Programming
(FOP)
2610001
10/11/2012
5. Pointers:
Need of pointer, Types and uses of pointer, Array and Pointers, Pointers and
strings,
Pointer to Pointer, Pointers and functions, other aspect of pointers.
8 Lect.
6. User Defined Data Types:
Introduction to structures, usage of structure, nested structures, Union and its
usage,
Enumeration types, bit fields.
6 Lect.
7. Files:
Types of files, working with files, usage of file management functions.
8 Lect.
8. Linked List:
Introduction to dynamic memory allocation, singly link list, operations on singly
link list.
6 Lect.
9. Other features of C:
Bitwise operators and its usage, C Preprocessor statements.
3 Lect.
10/11/2012
Books
Text Book:
1. Programming in C, by Pradip Dey & Manas Ghosh, Publisher Oxford
Reference Books:
1. Programming in ANSI C, by Balagurusamy, Publisher - Tata McGraw Hill.
2. Computer Science: A Structured Programming Approach Using C, by
Behrouz A. Forouzan & Richard F. Gilberg, Publisher Thomson
Education.
3. Programming with ANSI and Turbo C, by Ashok N Kamthane, Publisher
Pearson Education.
4. Mastering C, by Venugopal & Prasad, Publisher Tata McGraw Hill.
5. C: The Complete Reference, by Herbert Schildt, Publisher Tata McGraw
Hill.
6. Let us C, by Yashwant Kanitkar, Publisher BPB Publication
7. Schaum's Outline of Programming with C, By: Byron Gottfried, Publisher
Shaum Series.
10/11/2012
10/11/2012
Computer
Software
Application
Software
10/11/2012
10/11/2012
1.
2.
3.
4.
5.
6.
10
11
12
Machine Language
Example 1:
Machine Code
0011
1100
0000
0111
0000
0110
0000
1010
1000
0000
10/11/2012
Comments
Load A register with value 7
13
Mnemonics
LD A,7
LD B,10
ADD A,B
10/11/2012
Comments
Load register A with 7
Load register B with 10
A=A+B
Prepared By:Swaminarayan Priya, ISTAR
14
Assembly Language
10/11/2012
15
10/11/2012
16
Interpreter
10/11/2012
17
10/11/2012
18
10/11/2012
19
It is non-procedural language that allows the user to specify what the output
should be without describing how data should be processed to produce the result.
It requires less instructions to accomplish a particular task than a third generation
language.
The programmer should be able to write a program faster in 4GL than 3GL.
The 3GL languages are procedural languages but 4GL languages are nonprocedural languages.
Major 4GLs are used to get information from files and databases.
DBMS Package
Screen Painter
MS Publisher (Used for designing)
Dreamweaver
FrontPage
10/11/2012
22
For e.g.
Step1: Get a record from the EMP file.
Step2: If this is the record for MANAS, display the address.
Step3: If this is not the record for MANAS, go to step 1, until end-of-file.
Advantages of 4GLs:
Programming productivity is increased. One line of a 4GL code is equivalent
to several lines of a 3GL code.
System development is faster.
Program maintenance is faster.
End users can often develop their own applications.
Programs developed in 4GLs are more portable than those developed in
other generation languages.
Documentation is of improved order because most 4GLs are selfdocumenting.
10/11/2012
23
Code may be difficult to read, understand, Code is easy to understand and maintain.
and maintain by the user.
Difficult to debug.
10/11/2012
24
25
Non-procedural
1)Algorithmic
1) Functional
(COBOL, FORTRAN, C)
(LISP, ML)
2) Object-Oriented
2) Logic Based
(C++, JAVA, SMALLTALK) (PROLOG)
3) Scripting
(VB, PERL)
10/11/2012
Problem-oriented
Low-level Language
Machine
Assembly
1) Numeric
(MATLAB)
2) Symbolic
(MATHEMATICA)
3) Publishing
(LATEX)
26
1.
2.
1.
2.
3.
10/11/2012
27
Top-Down Analysis
The basic steps to top-down analysis are as follows:
10/11/2012
28
Modular Programming
Modular programming is a program that is divided into logically
independent smaller sections, which can be written separately.
Characteristics of Modular programming are as follows:
A module consists of a series of program instructions.
A module is clearly terminated by some special marker. For eg. Return
statement in C language.
A module has a unique name.
A module has only one entry point and only one exit point from where the
control is returned to the calling module.
10/11/2012
29
Algorithms
Algorithm: It is an effective procedure for solving a problem in a finite
number of steps.
1.
2.
3.
4.
5.
6.
10/11/2012
30
10/11/2012
While proposition
Begin
process1
process2
.
.
process N
end
Process1
Process2
.
.
Process N
If proposition
goto process1
31
10/11/2012
32
1.
2.
3.
4.
5.
6.
7.
8.
9.
10.
In an academic institute, grades have to be printed for students who appeared in the
final exam. The criteria for allocating the grades against the percentage of total marks
obtained are as follows.
Marks
Grade
Marks
Grade
91-100
O
61-70
B
81-90
E
51-60
C
71-80
A
<= 50
F
The percentage of total marks obtained by each student in the final exam is to be given
as input to get a printout of the grade the student is awarded.
START
PRINT ENTER THE OBTAINED PERCENTAGE MARKS
INPUT N
IF N > 0 AND N <= 50 THEN PRINT F
IF N > 50 AND N <= 60 THEN PRINT C
IF N > 60 AND N <= 70 THEN PRINT B
IF N > 70 AND N <= 80 THEN PRINT A
IF N > 80 AND N <= 90 THEN PRINT E
IF N > 90 AND N <= 100 THEN PRINT O
STOP
10/11/2012
33
34
10/11/2012
1. START
2. PRINT ENTER THE NUMBER
3. INPUT N
4. F = 1
5. C = 1
6. While C <= N
7. BEGIN
8. F = F * C
9. C = C + 1
10. END
11. PRINT F
12. STOP
35
36
Flowchart
It is a pictorial representation of the sequence of operations in a
computer program.
Standards for flowchart:
Flowcharts must be drawn on white, unlined paper, on one side
only.
Flowcharts start on the top of the page and the flow down and to
the right.
Only standard flowcharting symbols should be used.
English should be used in flowcharts, not programming language.
The flowchart for each subroutine, if any, must appear on a
separate page. Each subroutine begins with a terminal symbol with
the subroutine name and a terminal symbol labeled return at the
end.
Draw arrows between symbols with a straight edge and use
arrowheads to indicate the direction of the logic flow.
10/11/2012
37
Flowchart Symbols
10/11/2012
38
STOP
10/11/2012
39
40
10/11/2012
41
10/11/2012
42
10/11/2012
43
Draw a flowchart for calculating the simple interest using the formula SI = (P * R
* N)/100, where P denotes the principal, T time and R rate of interest. Also
write an algorithm for the same.
10/11/2012
44
The XYZ construction company plans to give a 5% year-end bonus to each of its
employees earning Rs. 5,000 or more per year, and a fixed bonus of Rs. 250 to all
other employees. Draw a flowchart and write the step-form algorithm for printing
the bonus of any employee.
10/11/2012
45
Prepare a flowchart to read the marks of a student and classify them into different grades. If the
marks secured are greater than or equal to 90, the student is awarded Grade A; if they are
greater than or equal to 80, but less than 90, Grade B is awarded; if they are greater than or
equal to 65 but less than 80, Grade C is awarded; otherwise Grade D is awarded.
10/11/2012
46
10/11/2012
47
Draw a flowchart for printing the sum of even terms contained within
the numbers 0 to 20.
10/11/2012
48
10/11/2012
49
10/11/2012
50
Chapter 2 : Basics of C
10/11/2012
51
History of C Language
C is a structured, high-level, machine independent language.
The root of all modern languages is ALGOL, introduced in the
early 1960s.
ALGOL was the first computer language to use a block
structure.
In 1967, Martin Richards developed a language called BCPL
(Basic Combined Programming Language).
In 1970, Ken Thompson created a language using many
features of BCPL and called it B language.
10/11/2012
53
54
10/11/2012
55
Documentation Section
Preprocessor Directive Block
Definition Section
Global Declaration Section
main() Function Section
{
Declaration Part
Executable Part
}
Subprogram Section
Function 1
Function 2
.
.
Function n
10/11/2012
(User-defined Functions)
56
10/11/2012
Code
Meaning
\a
\?
Question Mark
\b
Backspace
\r
Carriage return
\f
Form feed
\t
Horizontal tab
\v
Vertical tab
\0
\\
Backslash
Double quote
Single quote
\n
New line
\o
Octal
\x
Hexadecimal constant
Prepared By:Swaminarayan Priya, ISTAR
59
Character Set
The characters that can be used to form words, numbers and
expressions depend upon the computer on which the program is
run.
The characters in C are grouped into the following categories:
Letters
Digits
Special Characters
White space
Note: The compiler ignores white spaces unless they are a part of a
string constant.
White spaces may be used to separate words, but are prohibited
between the characters of keywords and identifiers.
10/11/2012
60
C Token
In a passage of text, individuals words and punctuation marks are called
tokens.
Identifiers:
An identifier is a sequence of characters invented by the programmer to
identify a specific object.
Rules for writing an identifier:
It is case sensitive. Ie NUMBER, Number and number are different
identifiers.
The underscore should not be used as the first character of a variable
name.
A numeric digit should not be used as the first character of identifier.
Identifier name should not be a keywords of C.
Identifiers may be of any reasonable length; generally 8 to 10 characters
should be suffice.
10/11/2012
61
Keywords
10/11/2012
auto
double
int
struct
break
else
long
switch
case
enum
char
Register
union
return
extern
Typedef
const
float
short
Unsigned
continue
for
signed
void
default
goto
sizeof
Volatile
do
if
static
while
62
Data Types of C
Data Type
Primitive/Ba
sic Data Type
1. Character
2. Int
3. Float
4. double
10/11/2012
Derives Data
Type
1. Array
2. Function
3. pointer
User-defined
Data Type
1. Structure
2. Union
3. enumerated
Valueless
Data Type
1. void
Data type
Size (bits)
Range
Char
8 (1 B)
-128 to 127
Int
16 (2 Bytes)
-32768 to 32767
Float
32 ( 4 Bs)
3.4E-38 to 3.4E+38
Double
64 (8 Bs)
1.7E-308 to 1.7E+308
valueless
Void
63
Data type
Format
Specifier
Size (bits)
Range
Char
%c
8 (1 B)
-128 to 127
unsigned char
%c
8 (1 B)
0 to 255
signed char
%c
8 (1 B)
-128 to 127
int
%d
16 (2 Bytes)
-32768 to 32767
Unsigned int
%u
16 (2 Bytes)
0 to 65535
Signed int
%d
16 (2 Bytes)
-32768 to 32767
Short int
%hd or %hi
16 (2 Bytes)
-32768 to 32767
%u
16 (2 Bytes)
0 to 65535
%hd
16 (2 Bytes)
-32768 to 32767
long int
%ld
32 (4 Bytes)
-2147483648 to 2147483647
%lu
32 (4 Bytes)
0 to 4294967295
%ld
32 (4 Bytes)
-2147483648 to 2147483647
Float
%f
32 ( 4 Bs)
3.4E-38 to 3.4E+38
Double
%lf
64 (8 Bs)
1.7E-308 to 1.7E+308
Long double
%Lf
80 (10 Bs)
3.4E-4932 to 1.1E+4932
10/11/2012
64
Constant
It is a memory location whose value does not change during
the program execution.
EX:- PI=3.14
Constants are defined inside the program by the programmer
whereas the value of variable is read at the execution time
and give by the user.
How to declare constant?
#define PI 3.14
Or
const float PI = 3.14;
10/11/2012
65
Operator
Arithmetic
Assignment
Equality
Relational
Logical
Bitwise
10/11/2012
66
Assignment Operator
In C, the assignment operator is the equal sign =
and is used to give a variable the value of an
expression.
For example:
i=0;
x=34.8;
sum=a+b;
slope=tan(rise/run);
midinit='J';
j=j+3;
10/11/2012
67
Sizeof() operator
sizeof can be applied to types and objects; when used with an object, brackets are not
needed.
sizeof(char) is always 1.
Syntax is:
int i;
i = sizeof(int);
i will be set to 2, assuming a 16 bit system.
The result of sizeof is the amount of data used for an object in multiples of char.
void main()
{
printf(char size = %d bytes\n,sizeof(char));
printf(short size = %d bytes\n,sizeof(short));
Char size = 1 bytes
printf(int size = %d bytes\n,sizeof(int));
Short size = 2 bytes
printf(long size = %d bytes\n,sizeof(long));
Int size = 2 bytes
printf(float size = %d bytes\n,sizeof(float));
Long size = 4 bytes
printf(double size = %d bytes\n,sizeof(double));
Float size = 4 bytes
printf(1.55 size = %d bytes\n,sizeof(1.55));
printf(1.55L size = %d bytes\n,sizeof(1.55L));
Double size = 8 bytes
printf(Hello size = %d bytes\n,sizeof(Hello));
1.55 size = 8 bytes
}
1.55L size = 10 bytes
68
Arithmetic Operators
*
/
%
+
-
multiplication
division
remainder after division (modulo arithmetic)
addition
subtraction and unary
int main()
{
float a;
a = 1 / 3;
printf("%f\n", a);
return 0;
}
0.3333333
would print 0.000000 as integer division was performed even though a is of type
float.
The / operator is used for two different operations: integer and floating point
division.
If both operands of the divide operator are of integral (char, int and its derivatives)
type then integer division is performed.
If either operand is float ,double or long double then real division is undertaken.
10/11/2012
69
Arithmetic operator :
+,-,*,/,%(modules)
% (Modules) operator is used to find the reminder after division.
EX : 20%8 will generate result 4(reminder).
The sign of result will be the same as sign of first operand (data).
Only integer values can be given with % operator, float and double type
data can not be supported.
Operator
Name
Example
Addition
12 + 4.9 = 16.9
Subtraction
3.98 4 = -0.02
Multiplication
2 * 3.4 = 6.8
Division
9 / 2.0 = 4.5
Remainder
13 % 3 = 1
9/2=4
-9/2 = -4
10/11/2012
printf((%d\n,-5%-2);
printf((%d\n,-5%2);
printf((%d\n,5%-2);
printf((%d\n,5%2);
-1
-1
1
1
70
10/11/2012
71
Comma Operator
Syntax:
expressionM = (expression1, exp2, .. , exp n);
The comma operator can be used to link the related expressions together.
A comma-linked list of expressions are evaluated left to right and value of
the right-most expression is the value of the combined expression.
For e.g.
value = ( x = 10, y = 5, x+y);
for ( n = 1, m = 10, n <= m, n++, m++)
int i = 0;
int j;
J = (i += 1, i +=2; i +3);
Answer: j = 6
10/11/2012
int m = 1;
int n;
n = (m = m + 3, m%3);
Answer: N = 1
int a = 2, b = 3, c;
c = a, a=b, b = c;
printf(a=%d b =%d,a,b);
Answer: a = 3 b = 2
72
Relational Operator
10/11/2012
Operator
Action
Example
==
Equal
5 == 5 ( result
1)
!=
Not equal
5 != 5 ( result 0)
<
Less than
<=
5 <= 5 ( result
1)
>
Greater than
>=
Greater than
equal
73
Logical Operator
Operator
Action
Example
Result
Logical Negation
! ( 5 == 5)
&&
Logical AND
||
Logical OR
5 < 6 || 6 <5
C doesn't have a built-in Boolean type. It is compulsory to use the type int for this
purpose.
For eg.
int sorted = 0; // false
Int balanced = 1; // true
10/11/2012
74
Conditional Operator
It is ternary operator.
It has the general form:
Expression1 ? Expression2 : expression3
First expression1 is evaluated; if the result is non-zero, then expression2 is
evaluated and its value is the final result. Otherwise, expression3 is
evaluated and its value is the final result.
For example,
If ( m < n) min=m; else min = n;
Min = (m <n ? m, n);
Write a program to find minimum number among three numbers using
conditional operator.
Int m=1, n=2, p = 3, min;
min = ( m<n ? (m<p?m:p) : (n<p?n:p));
10/11/2012
75
void main()
{
int a=5,b=3;
printf(%d, ++(a*b+2));
}
Compiler error Lvalue required
10/11/2012
void main()
{
printf(%d, ++2);
}
76
Bitwise Operator
Generally character, integer, float etc operate with a byte. But if we want to interact
directly with the computer hardware then we must have to work at bit level. This is
possible only through Bitwise Operators.
One of the powerful feature is a set of bit manipulation operators. Those permit user to
access and manipulate individual bits within a piece of data.
Operator
Action
Bitwise Negation
&
Bitwise AND
Bitwise OR
Bitwise Exclusive OR
<<
>>
These operators can operate upon int or char but not on float and double.
10/11/2012
77
1s Complement Operator:
Here all 1s present in the number are changed to 0s and all 0s are
changed to 1s.
Eg. A = 1010 then ~A = 0101
This operator is effectively useful in development of encryption facility.
Right Shift Operator:
Here >> operator shifts each bit in the operand to the right. The number
of places the bits are shifted depends on the number following the
operand.
E.g. 1101 0111 >> 3
0 110 1011 - 1 time
00 11 0101 - 2 time
000 1 1010 - 3 time
10/11/2012
78
10/11/2012
79
10/11/2012
80
81
82
Operator
Associativity
Primary Expression
Operators
left-to-right
Unary Operators
right-to-left
Binary Operators
Ternary Operator
Assignment Operators
Comma
10/11/2012
*/%
+>> <<
< > <= >=
== !=
&
^
|
&&
||
?:
= += -= *= /= %= >>= <<=
&= ^= |=
,
left-to-right
right-to-left
right-to-left
left-to-right
83
X = 7 * 6 % (15 / 9);
X = 2 * 3 + 4 * 5;
Answer : X = 26
X = 2 * ( 3 + 4 ) * 5;
Answer: X = 70
X = 7*6 % 15/9;
Answer: X = 1
X = 7 * ( 6 % 15) / 9;
Answer: X = 4
10/11/2012
84
10/11/2012
85
Type Conversion in C
When a C expression is evaluated, the resulting value has a particular data
type. If all the variables in the expression are of the same type, the
resulting type is of the same type as well.
For eg.,if x and y are both of int type, the expression x + y is of int type as
well.
The smallest to the largest data types with respect to size are given as
follows:
Char -> int -> long -> float -> double
1 byte -> 2 B -> 4 B -> 4 B -> 8 B
Thus, an expression containing an int and a char evaluates to type int.
An expression containing a float and a long evaluates to type float.
10/11/2012
86
Unsigned int
int
short
Char
10/11/2012
87
Conversion by Assignment
Promotion also occur with the assignment operator. The expression on the
right side of an assignment statement is always promoted to the type of
the data object on the left side of the assignment operator.
For eg.
Char c;
Int j;
Float f;
Double d, r;
R = (c * j) + (f / j) ( f + d);
R = ( char * int ) + ( float / int ) ( float + double)
R = double
10/11/2012
88
Type Casting
The opposite of promotion, truncation moves a value from a
particular type to a smaller type.
In this case, the compiler just drops the extra bits. It may or may
not generate a compile time warning for the loss of the
information.
For example,
(double) I
will force i to be of type double.
The general syntax is
(type) expression
Some examples,
x = (float) 77;
(double) k * 57
10/11/2012
89
Char ch;
Int I;
I = 321;
Ch = I; /* truncation of an int value to fit in a char */
Content of i
0000 0001
Content of ch after ch = I
statement is executed
Double pi;
Int I ;
Pi = 3.14159;
I = pi;
printf(d,i);
10/11/2012
0100 0001
0100 0001
Binary equivalent of 65
90
Answer: 65
0.500000
91
92
Answer: 0
9 What will be the output:
a) Int main()
{
printf(\nab);
printf(\bsi);
printf(\rha);
return(0);
}
\n newline
\b backspace
\r - linefeed
10/11/2012
Answer = 1
Answer: 6 6 6
10 What will be the output:
a) Int main()
{
int i = 5;
printf(%d%d%d, i++,i,i++);
return(0);
}
6 6 5
93
7
10/11/2012
94
2
10/11/2012
95
10/11/2012
96
Chapter 3
Input and Output
10/11/2012
97
10/11/2012
98
10/11/2012
99
10/11/2012
100
Void main()
{
char ch;
ch = getch();
putch(ch);
}
Output: a
10/11/2012
Void main()
{
char ch;
ch = getche();
putch(ch);
}
Output: aa
Prepared By:Swaminarayan Priya, ISTAR
101
10/11/2012
102
void main()
{
int ch;
ch = getchar();
ch++;
putchar(ch);
ch++;
putchar(ch);
}
Prepared By:Swaminarayan Priya, ISTAR
putchar(ch);
putchar(ch);
103
void main()
{
char ch;
ch = getchar();
ch = ch - 32;
putchar(ch);
}
10/11/2012
void main()
{
char ch1, ch2;
clrscr();
ch1 = getchar();
ch2 = getchar();
ch1 == ch2 ? printf("Equal") : printf("Not Equal");
}
104
10/11/2012
105
10/11/2012
106
Specifier Type
%c character
%d decimal integer
%o octal integer (leading 0)
%x hexadecimal integer (leading 0x)
%u unsigned decimal integer
%ld long int
%f
floating point
%lf double or long double
%e exponential floating point
%s character string
10/11/2012
108
Precision
size
ConversionCode
Here, % sign and conversion code are required but the other modifiers
such as width and precision are optional.
The width modifier specifies the total no. of characters used to display the
value.
The precision indicates the no. of characters used after the decimal
points. But it is used only with the floats and strings.
When it is used with float, the precision indicates how many digits should
be printed after the decimal point.
If the precision is not specified, the default value of 6 is assumed.
10/11/2012
109
1 0
printf(number=%3d\n,10);
printf(number=%2d\n,10); 1 0
printf(number=%1d\n,10); 110 0
5 . 4 3
printf(number=%7.2f\n,5.4321);
. 4 4
printf(number=%.2f\n,5.4391); 55.44
printf(number=%.9f\n,5.4321);5 . 4 3 2 1 0 0 0 0
printf(number=%f\n,5.4321); 5 . 4 3 2 1 0 0
10/11/2012
110
Flag
Meaning
Space
printf(number=%06.1f\n,5.5);
printf(number=%-+6.1f\n,5.5);
printf(%-6.3f\n,17.23478);
111
Void main()
{
h e
printf(%s,hello);
printf(%3s,hello); h e
printf(%10s,hello);
printf(%-10s,hello); H E
printf(%10.3s,hello);
}
10/11/2012
o
H E L
H E L
112
Flag with
format
specifier
Action
%#0
%#g or G
int x = 20;
printf(Octal value of %d = %o,x,x);
printf(Hexa value of %d = %x,x,x);
}
10/11/2012
113
float f=12;
printf(%f,f);
printf(%#f,f);
printf(%e,f);
printf(%g,f);
printf(%#g,f);
f = 122
F = 1223
F = 12345
F = 123456
F = 1234567
10/11/2012
o/p: 12.000000
o/p: 12.000000
o/p: 1.200000e+01
o/p: 12
o/p: 12.0000
printf(%#g,f);
printf(%#g,f);
printf(%#g,f);
printf(%#g,f);
printf(%#g,f);
o/p: 122.000
o/p: 1223.00
o/p: 12345.0
o/p: 123456.
o/p: 1.23457e+06
114
void main()
{
float p = 3.123456,q=1.12,r=123;
clrscr();
printf("%f
%f
%f",p,q,r);
printf("\n%g
%g
%g",p,q,r);
printf("\n%#g
%#g
%#g",p,q,r);
}
Output:
3.123456
3.12346
3.12346
1.120000
1.12
1.12000
123.000000
123
123.000
10/11/2012
115
10/11/2012
116
Control Code
Action
\b
Backspace
\f
Form feed
\n
New line
\r
Line feed
\t
Horizontal tab
Single quote
\0
null
Sample output:
printf(Hello world)
Int i1=2,i2=3; printf(sum is %d,i1+i2);
printf(%3d\n%3d\n%3d\n,5,25,125);
PI = 3.1415926535 Printf(%4.2f,pi);
10/11/2012
117
If the user wants to be able to enter the line this way, the scanf ()
needs to be coded as follows:
10/11/2012
scanf(%d%d%d %c,&a,&b,&c,&x);
Prepared By:Swaminarayan Priya, ISTAR
118
if input is 12345
output is only 12
13
output is 13
10/11/2012
119
Void main()
{
int a,b,c;
int num;
num = scanf(%d%d%d,&a,&b,&c);
printf(I have read %d values \n,num);
}
Suppose Input = 10 20 30
Then O/p = I have read 3 values.
If Input = 10 20 hello
Then O/p = I have read 2 values.
If Input = hello 10 20 30
Then O/p = I have read 0 values.
10/11/2012
120
void main()
{
int x;
scanf(You typed %d\n,x);
}
10/11/2012
121
10/11/2012
122
123
}
/Outstanding Program!/
/ Outstanding Program!/
/
Outst/
/Outs
/
10/11/2012
124
Chapter: 4
Control Statements
10/11/2012
126
Control Statement
Statement: A statement is a syntactic construction that performs an action
when a program is executed.
Statement blocks: In C, any sequence of statements can be grouped
together to function as a syntactically equivalent single statement by
enclosing the sequence in braces. These groupings are called statement
blocks.
Categories of statement:
Assignment Statement: here values, sometimes the results of calculations,
are stored in variables.
Input/Output statement: here the data is read in or printed out.
Control Statement: through which the program makes a decision about
what to do next.
C has two types of Control structures: selection (decision) and repetition
(loop).
10/11/2012
127
128
10/11/2012
129
Iteration/Looping
Selection/ Branching
Conditional Type
Unconditional Type
10/11/2012
for
while
Do -while
130
10/11/2012
131
Selection Statements
1.
2.
3.
10/11/2012
132
Customize output
if (grade>=90)
printf("\nCongratulations!");
printf("\nYour grade is "%d",grade);
Nested ifs
if (letter>='A')
if (letter>='Z')
printf("The letter is a capital \n");
10/11/2012
133
10/11/2012
START
PRINT ENTER THREE NUMBERS
INPUT A,B,C
MAX = A
IF B>MAX THEN MAX=B
IF C>MAX THEN MAX=C
PRINT LARGEST NUMBER IS, MAX
STOP
134
min=x;
else
min=y;
if (letter == 'e')
++vowel_count;
else
++other_count;
10/11/2012
135
10/11/2012
START
PRINT ENTER ANY NUMBER
INPUT N
IF N/2 (Integer Division)
PRINT EVEN
ELSE
PRINTF ODD
STOP
136
10/11/2012
Void main()
{
int a=2, b=3;
if ( a=b)
printf(EQUAL);
else
printf(UNEQUAL);
}
137
10/11/2012
138
10/11/2012
139
140
10/11/2012
Void main()
{
int score;
char grade;
printf(enter score);
scanf(%d,&score);
if (score >= 90)
grade = A;
else if (score >= 80)
grade = A;
else if (score >= 70)
grade = A;
else if (score >= 60)
grade = A;
else
grade = F;
}
141
Write a program to find the largest among three numbers using the nested loop.
Void main()
{
int a,b,c;
printf(enter three numbers);
scanf(%d%d%d,&a,&b,&c);
if (a>b)
if (a>c)
printf(%d,a);
else
printf(%d,c);
else
if (b>c)
printf(%d,b);
else
printf(%d,c);
}
10/11/2012
142
10/11/2012
void main()
{
printf(Hi);
if (!1)
printf(Bye);
}
Hi
143
void main()
{
float x =199.9;
if (x<100)
printf(One);
if (x < 200)
printf(Two);
if (x < 300)
printf(Three);
}
Two Three
void main()
{
int a=1,b=2,c=3,d=4;
if (d>c)
if (c>b)
printf(%d %d,d,c);
else if (c>a)
printf(%d %d,c,d);
if (c>a)
if (b<a)
printf(%d %d,c,a);
else if (b<c)
printf(%d %d,b,c);
}
4323
10/11/2012
144
Else
Expression3;
Find our maximum from given four numbers using conditional operator:
Int a,b,c,d,e;
e = a>b ? (a>c?(a>d?a:d):(c>d?c:d)):(b>c?(b>d?b:d):(c>d?c:d));
10/11/2012
145
Switch statement
The switch statement is a better way of writing a program which employs an ifelse ladder.
It is Cs built-in multiple branch decision statement.
The syntax for the switch statement is as follows:
switch (integer expression)
{
case constant1: statement1;
break;
case constant2: statement2;
break;
...
default:
statement;
}
The keyword break should be included at the end of each case statement. In
general, whenever a break statement is encountered in C, it interrupts the normal
flow of control.
In the switch statement, it causes an exit from the switch shunt. The default
clause is optional. The right brace at the end marks the end of switch statement.
10/11/2012
146
10/11/2012
147
Switch (ch)
{
case A: printf(You entered an A);
break;
case B: printf(You entered an B);
break;
default: printf(Illegal entry);
break;
}
Switch (choice)
{
case 1: printf(You entered choice #1);
break;
case 2: printf(You entered choice #2);
break;
default: printf(Illegal entry);
break;
}
10/11/2012
148
Switch (donationLevel)
{
case 1: printf(You donated over Rs. 1000);
break;
case 2: printf(You donated over Rs. 500);
break;
case 3: printf(You donated over R5. 250);
break;
A set of statements to
case 4: printf(You donated over R5. 100);
execute can be grouped
break;
default: printf(Pls be a little more generous);
with more than one value of
break;
the variable as in the
Switch
(number)
}
following example.
{
case 1:
case 3:
case 5:
case 7:
case 9: printf( %d is an odd number., number);
break;
case 2:
case 4:
case 6:
case 8: printf( %d is an odd number., number);
break;
default: printf(%d is a value not between or including 1 and 9,number);
break;
10/11/2012
149
10/11/2012
150
switch (grade)
{
default:
printf("F\n");
break;
case 1:
printf("A\n");
break;
case 2:
printf("B\n");
break;
case 3:
printf("C\n");
break;
case 4:
printf("D\n");
break;
}
10/11/2012
151
10/11/2012
152
153
154
}
Yes/No No/Yes
10/11/2012
Int ch = 3;
Switch (ch)
{
default: printf(Default);
case 1: printf(Choice1);
break;
case 2: printf(Choice2);
break;
}
Default
155
10/11/2012
156
157
Sample Loop:
We can trace the execution of the sample loop as follows
sum = 10;
for (i=0; i<6; ++i)
sum=sum+i;
Iteration
1st
2nd
3rd
4th
5th
6th
7th
10/11/2012
I
0
1
2
3
4
5
6
i<6
TRUE
TRUE
TRUE
TRUE
TRUE
TRUE
FALSE
sum
10
11
13
16
20
25
25
158
10/11/2012
159
10/11/2012
160
161
10/11/2012
162
163
164
input n=3
output
1
1 2
1 2 3
10/11/2012
#include <stdio.h>
#include <conio.h>
void main()
{
int i,j,n;
clrscr();
printf("enterr n");
scanf("%d",&n);
for (i=1;i<=n;i++)
{
for (j=1;j<=i;j++)
printf("%3d",j);
printf("\n");
}
}
Prepared By:Swaminarayan Priya, ISTAR
165
clrscr();
printf("enterr n");
scanf("%d",&n);
for (i=n;i>=1;i--)
{
for (j=1;j<=i;j++)
printf("%3d",k);
k++;
printf("\n");
}
getch();
10/11/2012
166
clrscr();
printf("enterr n");
scanf("%d",&n);
for (i=n;i>=1;i--)
{
k = 1;
for (j=1;j<=i;j++)
printf("%3d",k++);
printf("\n");
}
getch();
10/11/2012
167
Input = 3 then
Output =
A
B C
D E F
Input = 4 then
Output =
z
z y
z y x
z y x w
Input = 3 then
Output =
Input = 4 then
Output =
A
B A
C B A
****
*
*
*
*
****
Input = 3 then
Output =
A
B C
D E F
Input = 3 then
Output =
*
* *
* * *
168
Input = 3 then
Output =
A
B C
D E F
10/11/2012
void main()
{
int i,j,k,n;
char ch='A';
clrscr();
printf("enmter amu n");
scanf("%d",&n);
for (i=1;i<=n;i++)
{
for (j=1;j<=i;j++)
{
printf("%3c",ch);
ch++;
}
printf("\n");
}
getch();
}
Prepared By:Swaminarayan Priya, ISTAR
169
Input = 3 then
Output =
A
B A
C B A
10/11/2012
void main()
{
int i,j,k,n;
char ch='A',ch1;
clrscr();
printf("enmter amu n");
scanf("%d",&n);
for (i=1;i<=n;i++)
{
ch1 = ch;
for (j=1;j<=i;j++)
{
printf("%3c",ch1);
ch1--;
}
ch++;
printf("\n");
}
getch();
}
Prepared By:Swaminarayan Priya, ISTAR
170
Input = 4 then
Output =
z
z y
z y x
z y x w
10/11/2012
void main()
{
int i,j,k,n;
char ch='z',ch1;
clrscr();
printf("enter any number");
scanf("%d",&n);
for (i=1;i<=n;i++)
{
ch = 'z';
for (j=1;j<=i;j++)
{
printf("%3c",ch);
ch--;
}
printf("\n");
}
getch();
} By:Swaminarayan Priya, ISTAR
Prepared
171
1
2
/*
Input = 3 then Output =
1
2 2
3 3 3
*/
10/11/2012
void main()
{
int i,j,k,n,l,sp;
k = 1;
clrscr();
printf("enter any number");
scanf("%d",&n);
sp = n;
for (i=1;i<=n;i++)
{
for (l = 1; l <= sp; l++)
printf(" ");
sp--;
for (j=1;j<=i;j++)
printf("%2d",k);
k++;
printf("\n");
}
getch();
}
Prepared By:Swaminarayan Priya, ISTAR
173
Input = 3 then
Output =
*
* *
* * *
10/11/2012
void main()
{
int i,j,k,n,l,sp;
k = 1;
clrscr();
printf("enmter amu n");
scanf("%d",&n);
sp = n;
for (i=1;i<=n;i++)
{
for (l = 1; l <= sp; l++)
printf(" ");
sp--;
for (j=1;j<=i;j++)
printf(" *");
printf("\n");
}
getch();
} Prepared By:Swaminarayan Priya, ISTAR
174
void main()
{
int i,j,k,n,l,sp;
k = 1;
clrscr();
printf("enmter amu n");
scanf("%d",&n);
sp = n-2;
Input = 4 then
Output =
****
*
*
*
*
****
10/11/2012
175
while Loop
The while loop provides a mechanism for repeating C
statements while a condition is true.
Its format is
while(control expression)
program statement;
The while statement works as follows:
1) Control expression is evaluated (entry condition)
2) If it is FALSE, skip over the loop.
3) If it is TRUE, loop body is executed.
4) Go back to step 1
10/11/2012
176
10/11/2012
177
Write a while loop that accepts input from the keyboard until a
negative number is entered and find average of all entered
numbers.
Void main()
{
int x = 1;
int cnt = 0,sum=0;
float avg=0;
while ( x>= 0)
{
scanf(%d,&x);
cnt = cnt + 1;
sum = sum + x;
}
avg = sum / cnt;
printf(Average value = %f,avg);
}
10/11/2012
178
10/11/2012
179
Void main()
{
while (1)
{
printf(\t ISTAR);
}
}
10/11/2012
Void main()
{
int c = 5;
while (c)
{
printf(\t %d,c);
c = c - 2;
}
}
Void main()
{
while (0)
{
printf(\t ISTAR);
}
}
180
10/11/2012
181
Void main()
{
int c;
for (c=0;++c;++c)
printf(%d,c);
}
Void main()
{
for (;;)
printf(ISTAR");
}
Void main()
{
int c;
for (c=1;c<=5;)
printf(%d,++c);
}
Prepared By:Swaminarayan Priya, ISTAR
182
10/11/2012
183
Void main()
{
int i=9;
for (i--; i--; i--)
printf(%d,i);
}
7531
6 4 2
10/11/2012
184
Void main()
{
for (;printf(C););
}
10/11/2012
Void main()
{
int I;
for (i=5;--i;)
printf(%d,i);
}
4 3 2 1
185
Void main()
{
int I =3;
for (i--; i<7; i=7)
printf(%d,i++)
}
2
10/11/2012
Void main()
{
int I;
for (i=-10;!i; i++)
printf(%d,-i);
}
No output
186
Do While Statement
The do while statement is a variant of the while statement in which the
condition test is performed at the bottom of the loop. This guarantees that
the loop is executed at least once.
The syntax of the do while statement is
do
{
program statement;
} while (control expression);
and it works as follows
1) The body of the loop is executed.
2) The control expression is evaluated (exit condition).
3) If it is TRUE, go back to step 1. If it is FALSE, exit loop.
10/11/2012
187
10/11/2012
188
Void main()
{
int c=5;
while (c<5)
{
printf(Hello);
c++;
}
}
No output
Void main()
{
int c=5;
do
{
printf(Hello);
c++;
} while (c<5);
}
Hello
Note: a do-while loop will execute at least once because its test expression is placed at
the end of the loop.
While statement is pre-test loop and do-while is post-test loop.
10/11/2012
189
Pre-test loop
Post-test loop
Initialization
Once
Once
No. of tests
N+1
Actions executed
Updating executed
Minimum iteration
At least once
10/11/2012
190
10/11/2012
191
10/11/2012
192
The while and for constructs are pre-test loops and the do-while
construct is post-test loop.
The while and do-while loops are event-controlled whereas the for
loop is counter-controlled.
The for loop is appropriate when one knows in advance how many
times the loop will be executed. The while and do-while loops are
used when it is not known in advance when the loop should
terminate.
10/11/2012
193
Goto statement
It is another type of control statement supported by C.
The control is unconditionally transferred to the statement
associated with the label specified in the goto statement.
Syntax: goto Label_name
If an active block is exited using a goto statement, all local variables
are destroyed when control is transferred from that block.
int main()
{
Int n,c;
Long int f =1;
Printf(enter any number);
Scanf(%d,&n);
If (n < 0)
Goto end;
197
198
break
The break statement is used in loop constructs such as for, while and do-while,
and switch statement to terminate execution of the loop or switch statement.
Syntax: break;
After a break statement is executed within a loop or a case in a switch statement
execution proceeds to the statement that follows the loop or switch statement.
Void main()
{
int c=1;
while (c<=5)
{
if (c==3)
break;
printf(\t %dc);
c++;
}
}
1 2 instead of 1 2 3 4 5
10/11/2012
199
Void main()
{
int c=1;
while (1)
{
printf(\t %d,c);
c++;
}
}
1 2 3 4 5
10/11/2012
Void main()
{
int c=1;
while (1)
{
if (c==5)
break;
printf(\t %d,c);
c++;
}
}
1 2 3 4
Prepared By:Swaminarayan Priya, ISTAR
200
10/11/2012
201
continue
The continue statement does not terminate the loop but goes to the test
expression in the while and do-while statements and then goes to the updating
expression in a for statement.
Syntax: continue;
Use to skip an iteration
continue; skips rest of innermost loop body, jumping to loop condition
202
Continue
Syntax: break;
Syntax: continue;
Example
Example
10/11/2012
203
Chapter 5:
Arrays and Strings
10/11/2012
204
205
10/11/2012
206
101
232
id[0]
10/11/2012
id[1]
231
id[2]
207
Declaring Arrays
Arrays may consist of any of the valid data types. Arrays
are declared along with all other variables in the
declaration section of the program and the following
syntax is used
type array_name[n];
where n is the number of elements in the array.
10/11/2012
208
10/11/2012
a[i] = 0;
209
Using Arrays
Array variables and for loops often work hand-in-hand since the for loop offers a
convenient way to successively access array elements and perform some operation
with them.
Basically, the for loop counter can do double duty and act as an index for the array,
as in the following summation example:
int total=0,i;
int grade[4]={93,94,67,78};
for (i=0; i<4; ++i)
total += grade[i];
10/11/2012
210
Int num[10];
Following are the examples
Num [0] = 98;
Num[1] = num[0] 11;
Num[2] = 2 * (num[0] 6)
Num[3] = 79;
Num[4] = (num[2] + num[3] 3) / 2;
Tot = num[0] + num[1]+num[2]+num[3]+num[4]
10/11/2012
211
Note:
Int a[10];
a = 0; // Invalid statement
Int b[10], a[10];
b = a; // Invalid statement
To increment the ith element the given statement can be used:
Ar[i]++;
Ar[i] += 1;
Ar[i] = ar[i] + 1;
To add n to ith element the following statement may be used.
Ar[i] += n;
Ar[i] = ar[i] + n;
To copy the contents of the ith element to the kth element the
following statement may be written.
Ar[k] = ar[i];
10/11/2012
212
213
214
10/11/2012
215
216
Printing Strings:
Char s*+ = Hello World;
H E L L O
W
Printf(%s,s);
_-_-_-_-_Hello World
Printf(%20s,s);
Hello World_-_-_-_-_
Printf(%-20s,s);
Hell
Printf(%.4s,s);
Hell-_-_-_-_-_-_-_-_
Printf(%-20.4s,s);
-_-_-_-_-_-_-_-_Hell
Printf(%20.4s,s);
10/11/2012
O R L D
217
218
10/11/2012
219
220
10/11/2012
221
10/11/2012
222
To find out total no. of vowels, consonants, digits, blank spaces and special characters
Void main()
{
char s[50];
gets(s);
for (i=0; s*i+ != \0; i++)
{
if ((s*i+ == a) || (s*i+ == e) || i o u A E I O U)
vowels++;
else
if ((s*i+ >= 0) &&(s*i+ <= 9))
digits++;
else
if (s*i+ == )
spaces++;
else
if (s*i+ >= a) && s*i+ <= z) || (s*i+ >= A) && s*i+ <= Z) )
consonants++;
else
spChars++;
}
10/11/2012
Prepared By:Swaminarayan Priya, ISTAR
}
223
224
To compare two
strings
Inputs:
Pankaj
Priyank
Output: S1<s2
Inputs:
Pankaj
Pankaj
Output: S1=s2
Inputs:
Priyank
Pragnesh
Output: S1>s2
10/11/2012
void main()
{
char s1[50],s2[50];
int i,j,len=0,k=0,l;
printf("enter two strings");
gets(s1);
gets(s2);
for (i=0;s1[i] != '\0' || s2[i] != '\0'; i++)
{
if (s1[i] == s2[i])
k = 0;
else
{
k = s1[i] - s2[i];
break;
}
}
if (k == 0)
printf("Strings are equal\n");
else
if (k>0)
printf("str1 is graater than str2");
else
printf("str1 < str2");
Prepared By:Swaminarayan
Priya, ISTAR
}
225
10/11/2012
void main()
{
char s1[50],s2[50];
int i,j,len=0,k=0,l;
226
void main()
{
char s[50],t[50];
int i,j,k;
printf("enter any string");
gets(s);
// Convert given string into lower case
for (i=0;s[i] != '\0'; i++)
{
if (s[i] >= 'A' && s[i] <= 'Z')
s[i] = s[i] + 32;
}
puts(s);
10/11/2012
227
10/11/2012
228
10/11/2012
229
Copying Strings
The strcpy function is one of a set of built-in string handling functions
available for the C programmer to use.
To use these functions be sure to include the string.h header file at the
beginning of your program.
The syntax of strcpy is
strcpy(string1,string2);
When this function executes, string2 is copied into string1 at the
beginning of string1. The previous contents of string1 are overwritten.
In the following code, strcpy is used for string initialization:
#include <string.h>
main () {
char job[50];
strcpy(job,"Professor");
printf("You are a %s \n",job);
}
10/11/2012
230
231
if (i==0)
printf("s1 == s2\n");
else
if (i>0)
printf("s1>s2");
else
printf("s1<s2");
}
Output: s1 < s2
10/11/2012
232
Void main()
{
char s1*10+ = PRACHI, s2*10+ = prachi;
i = strcmpi(s1,s2);
if (i==0)
printf("s1 == s2\n");
else
if (i>0)
printf("s1>s2");
else
printf("s1<s2");
}
Output: s1 == s2
10/11/2012
233
Void main()
{
char s1*10+ = Prachi, s2*10+ = Prakash;
i = strncmp(s1,s2,3);
if (i==0)
printf("s1 == s2\n");
else
if (i>0)
printf("s1>s2");
else
printf("s1<s2");
}
Output: s1 == s2
Strnicmp it compares first n characters of one string with first n characters of
another string. it also ignores case.
10/11/2012
234
235
}
The character r is at position 12
10/11/2012
236
Strrchr:
Void main()
{
char string[15];
char *ptr, c = 'r';
strcpy(string, "This is a string");
puts(string);
ptr = strrchr(string, c);
if (ptr)
printf("The character %c is at position: %d\n", c, ptr-string);
else
printf("The character was not found\n");
}
The character r is at position 12
10/11/2012
237
238
239
10/11/2012
240
241
242
243
10/11/2012
244
245
void main()
{
int cnt=0,i,j,k,n;
char s[40];
printf("enter character string\n");
gets(s);
for (i=0;s[i] != '\0'; i++)
{
char t = s[i];
cnt = 0;
if (s[i] != '$')
{
for (j = i; s[j] != '\0'; j++)
{
if (t == s[j])
{
Find out
frequency of
each letter in a
string.
cnt++;
s[j] = '$';
}
}
printf("frequency of %c = %d\n",t,cnt);
}
}
puts(s);
10/11/2012
}
Input:Pankaj Purvi
Output:
Frequency of P = 2
Frequency of a = 2
Frequency of n = 1
Frequency of k = 1
Frequency of j = 1
Frequency of = 1
Frequency of u = 1
Frequency of r = 1
Frequency of v = 1
Frequency of 1 = 1
246
void main()
{
char s[50],sub[50];
Enter two strings, check whether
int i,j,k,cnt;
the 2nd string is substring of 1st
printf("enter string and substring\n");
string or not? If yes then return
gets(s);
its position.
gets(sub);
for (i=0; s[i] != '\0'; i++)
{
if (s[i] == sub[0])
{
j = i;
Input:Pankaj vidhi purvi ansh
for (k = 0; sub[k] != '\0'; k++)
Substing = vidhi
{
Output: 2nd sting is found in 1st
if (s[i] == sub[k])
string and its position is 7
{
i++;
cnt=0;
}
else
{
cnt = 1;
break;
}
}
if (cnt == 0)
break;
}
}
if (cnt == 0)
and itsBy:Swaminarayan
position is %d",j);Priya, ISTAR
10/11/2012printf("2nd string is found in 1st string
Prepared
247
}
Multi-Dimensional Arrays
Multi-dimensional arrays have two or more index
values which are used to specify a particular element in
the array. For this 2D array element, image[i][j]
the first index value i specifies a row index, while j
specifies a column index.
Declaring multi-dimensional arrays is similar to the 1D
case:
int a[10]; /* declare 1D array */
float b[3][5]; /* declare 2D array */
double c[6][4][2]; /* declare 3D array */
Note that it is quite easy to allocate a large chunk of
consecutive memory with multi-dimensional arrays.
Array c contains 6x4x2=48 doubles.
10/11/2012
248
10/11/2012
249
Using Scanset
The scanset conversion facility provided by scanf() is a useful string input
method.
This conversion facility allows the programmer to specify the set of
characters that are (or are not) acceptable as part of the string.
A scanset conversion consists of a list of acceptable characters enclosed
within square brackets.
A range of characters may be specified using notations such as a-z,
meaning all characters within this range.
If an actual - is required in the scanset, it must be the first or last
character in the set.
If the first character after the * is a ^ character, then the rest of the
scanset specifies unacceptable characters rather than acceptable
characters.
10/11/2012
250
main)()
{
char s[50];
printf(enter a string in lower case\n);
scanf(%*a-z+,s);
printf(The string was : %s,s);
}
Input: hello world
Output: hello world
Input: hello, world
Output: hello
Input: hello1234
Output: hello
10/11/2012
251
10/11/2012
252
10/11/2012
254
255
\0
\0
\0
\0
\0
256
Input:
Ravi
Yagnesh
Payal
Pankaj
Viraj
Output:
Ravi
Yagnesh
Payal
Pankaj
Viraj
257
10/11/2012
258
Output
Mr.Prakash
MS.PRIYANKA
Mr.Yagnseh
MS.PAYAL
MS.NEELAM
void main()
{
char s[5][50];
char t[50];
int i,j,k,n;
clrscr();
printf("enter name");
for (i=0;i<5;i++)
gets(s[i]);
10/11/2012
259
10/11/2012
260
Multiple-choice questions:
1. Arrays declared as static contain an initial value which is (A) 10 (B) 1 (C) 0
(D) None of these
2. An integer array of 10 elements occupies (a) 10 bytes (b) 20 bytes (c) 40
bytes (d) none of these
3. A string is a character array terminated by (a) z (b) zero (c) NULL
character (d) none of these
4. The subscript of an array in C language starts from (a) -1 (b) 1 (c) 0 (d)
user defined
5. Arrays, by default, contain (a) -1 (b) garbage value (c) zero (d) none of
these
10/11/2012
261
262
10/11/2012
Printf(%c,city[i++]);
Prepared By:Swaminarayan Priya, ISTAR
263
Chapter 6:
Functions
10/11/2012
264
Functions
A function in C is a small sub-program that performs a particular
task, and supports the concept of modular programming design
techniques.
In modular programming the various tasks that your overall
program must accomplish are assigned to individual functions and
the main program basically calls these functions in a certain order.
C language supports two types of functions: Library functions and
user defined function.
Library Function: They are written by system. And they are used to
carry out a no. of commonly used operations or calculations.
For eg. String functions
Maths Functions
File handling functions
10/11/2012
265
Characteristics of functions
Any C program contains at least one function.
If a program contains only one function, it must be main() function.
If a program contains more than one function, then one function
must be main() function because execution of program always start
from main() function.
There is no limit on no. of functions in a program.
Nested function is also allowed.
A same function can be any no. of times.
A function call to itself , which is known as Recursion.
Any function can be called from any other function. Even main()
function can be called from other function.
A function can be called from other function but a function can not
be defined in another function.
10/11/2012
266
Advantages of Functions
Code reuse: It avoids repetitive works.
Easy to debug. Get one function working well then move on to the
others.
Easy to modify and expand. Just add more functions to extend program
capability
Function portability: useful functions can be used in a number of
programs.
Data Protection: Functions can be used to protect data. This is related
to with the concept of local data. Local data is the data described
within a function. They are available only within a function when the
function is being executed.
Programmer can also build a customized library of frequently used
functions.
10/11/2012
267
10/11/2012
268
Function Definition
The function definition is the C code that implements what the
function does.
Function definitions have the following syntax
return_type function name (data type variable name list)
{
local declarations;
function statements;
}
where the return_type in the header tells the type of the value
returned by the function (default is int)
Where the data type variable name list tells what arguments the
function needs when it is called (and what their types are).
where local declarations in the function body are local constants
and variables the function needs for its calculations.
10/11/2012
269
270
10/11/2012
271
return Statement
A function returns a value to the calling program with the use of the
keyword return, followed by a data variable or constant value. The
return statement can even contain an expression. Some examples
return 3;
return n;
return ++a;
return (a*b);
When a return is encountered the following events occur:
1 execution of the function is terminated and control is passed back to
the calling program, and
2 the function call evaluates to the value of the return expression.
If there is no return statement control is passed back when the
closing brace of the function is encountered (falling off the end).
10/11/2012
272
10/11/2012
273
Using Functions
How we can invoke the function?
This is the easiest part! To invoke a function, just type its name in your
program and be sure to supply arguments (if necessary). A statement
using our factorial program would look like
number=factorial(3);
To invoke our write_header function, use this statement write_header();
When your program encounters a function invocation, control passes to
the function. When the function is completed, control passes back to the
main program.
In addition, if a value was returned, the function call takes on that return
value. In the above example, upon return from the factorial function the
statement
factorial(3) 6 and that integer is assigned to the variable number.
10/11/2012
275
10/11/2012
276
Function prototype
277
Function Prototype
Function Definition
It is ended by semicolon
Definition
Definition
Eg.
Eg.
10/11/2012
278
279
280
Call By Reference
Void main()
{
int a=10,b=20;
printf(a=%d b=%d,a,b);
swap(&a,&b);
printf(a=%d b=%d,a,b);
}
Swap (int *m, int *n)
{
int t;
t = *m;
*m = *n;
*n = t;
}
Output: a=10 b = 20
a = 20 b = 10
10/11/2012
Call By Value
Void main()
{
int a=10,b=20;
printf(a=%d b=%d,a,b);
swap(a,b);
printf(a=%d b=%d,a,b);
}
Swap (int m, int n)
{
int t;
t = m;
m = n;
n = t;
}
Output: a=10 b = 20
a = 10 b = 20
281
282
10/11/2012
283
10/11/2012
284
10/11/2012
285
#include <stdio.h>
#include <conio.h>
void read(int x[3][3]);
void print(int x[3][3]);
void add1(int p[3][3],int q[3][3],int r[3][3]);
void main()
{
int a[3][3],b[3][3],c[3][3];
clrscr();
printf("enter value for Matrix A");
read(a);
printf("enter value for Matrix B");
read(b);
add1(a,b,c);
printf("Resultant Matrix\n");
print(c);
getch();
}
10/11/2012
286
287
10/11/2012
288
289
1.
Recursion:
Calling a procedure or function to itself is recursion.
e.g. proc f(x)
{
f(x);
}
Recursion is not available in all languages like COBOL, BASIC,
and FORTRAN. So for that, there is one procedure which is
useful to convert the recursion procedure to non-recursion
procedure.
In PASCAL, C, ALGOL-60 recursion is available.
Main characteristics of recursion.
1. Call itself
2. Stopping criteria
Prepared By:Swaminarayan
Priya, ISTAR
290
10/11/2012
Prepared By:Swaminarayan
Priya, ISTAR
291
10/11/2012
Prepared By:Swaminarayan
Priya, ISTAR
292
10/11/2012
#include <stdio.h>
#include <conio.h>
int fact(int n)
{
int t=1;
if (n == 0)
return 1;
else
return(n*fact(n-1));
}
void main()
{
int no;
clrscr();
printf("enter no\n");
scanf("%d",&no);
printf("Fact = %d",fact(no));
getch();
}
10/11/2012
N=3
Fact(3)
3 * fact(2)
3 * 2 * fact(1)
3 * 2 * 1 * fact(0)
3*2*1*1
3*2*1
3*2
6
293
#include <stdio.h>
#include <conio.h>
int fib(int val)
Fibonacci sequence for 6
{
terms is 1 1 2 3 5 8
if (val <= 2)
return 1;
else
return(fib(val - 1) + fib(val -2));
}
void main()
{
int n;
clrscr();
printf("enter number\n");
scanf("%d",&n);
printf("Fibonacci sequence for %d term is",n);
for (int j =1; j<=n; ++j)
printf(" %d",fib(j));
getch();
10/11/2012
Prepared By:Swaminarayan Priya, ISTAR
}
295
42 23 74 11 65 58 94 36 99 87
Key
QUICK SORT
It divides array into two parts, apply the same procedure on both parts of
array
10/11/2012
296
void main()
{
int a[10];
printf("enter array elements");
for (int i = 0; i < 10; i++)
scanf("%d",&a[i]);
quick_sort(a,0,9);
for ( i = 0; i < 10; i++)
printf("% d\n",a[i]);
}
297
Chapter 7
Pointers in C
10/11/2012
298
Pointers in C
All the computers have primary memory, also known as RAM. For eg. A
computer may have 16,32,64,128,256 or 512 MB of RAM installed.
RAM holds the programs that the computer is currently running along
with the data they are currently manipulating (their variables and data
structures).
All the variables used in a program reside in the memory when the
program is executed.
There are three areas of memory that have special capabilities assigned by
the compiler and linker.
1. Stack: It is a ordered list of data in which insertion and deletion possible
only from the one end known as top of the stack.
2. Heap: It is a fixed size and used by the system as needed in a random
fashion. Dynamic memory handling functions - alloc() and realloc()
functions fetch free block from heap and free() function returns free
block to heap.
3. Global Memory: This is all the memory on the machine that is not
assigned to the stack or the heap. Generally variables are stored in global
memory. bles
10/11/2012
299
Chapter 8
User-defined Data Types
and Variables: Structure,
Union, Enumerations, and
Bitfield
10/11/2012
300
Chapter 9
Files in C
10/11/2012
301
Chapter 10
Linked Lists
10/11/2012
302
Chapter 11
Advanced C
10/11/2012
303