Brief Introduction To The C Programming Language
Brief Introduction To The C Programming Language
to the
C Programming Language
HISTORY
• The C programming language was designed by Dennis Ritchie at
Bell Laboratories in the early 1970s
• Influenced by
– ALGOL 60 (ALGOrithmic Language)
(1960),
– CPL (Combined Programming Language)
(Cambridge, 1963),
– BCPL (Basic Combined Programming Language)
(Martin Richard, 1967),
– B (This was derived from BCPL)
(Ken Thompson, 1970)
– C (This was derived from B) (Dennis Ritchie, 1972)
2
Standards of C
• Standardized in 1989 by American National Standards Institute
known as ANSI C
3
Classification Of Language
Low Level :
4
Translators
Translators : It is a computer program that performs the translation of a
program written in a given programming language into a functionally
equivalent program in a different computer language,
5
C language
C is a middle level language, It has the
power of both high level and low level
programming. This is an excellent, efficient and
general purpose language. It is used for most of
such as mathematics, scientific, business and
system software and embedded applications.
6
Elements of a C Program
• A C development environment includes
7
Compilation and Execution
Source Code
Preprocessor
Expanded Code
Compiler
Assembly Code
Assembler
Object Code
Executable Code
(Object Code)
8
RULES OF C
9
RULES OF C
C KEYWORDS – TOTAL OF 32
10
RULES OF C
CHARACTER SET :
11
RULES OF C
ESCAPE SEQUENCE
12
RULES OF C
All words that we will use in C programs will be either keywords or identifiers.
Identifiers : Identifiers are user defined words and are used for naming
entities like variables, arrays, functions, structures etc. Rules for naming
identifiers are as follows.
(i) First Character should start with only either lower, upper
case or underscore.
(ii) The name can be combination of lower, upper case
characters, numerical and underscore.
(iii) The name should not be a keyword.
(iv) C is a case sensitive, to the upper case and lower case
letters are considered different. Eg – CASE, Case, case
are three different identifiers.
13
RULES OF C
Data types : There are 4 basic data
types
14
RULES OF C
Data types : There are 4 basic data
types
char
int
float
double
15
RULES OF C
Data types : There are 4 basic data
types
char
int
float
double
Qualifiers / Modifiers :
16
RULES OF C
Data types : There are 4 basic data
types
char
int
float
double
Qualifiers / Modifiers :
Size qualifier - short.
long.
17
RULES OF C
Data types : There are 4 basic data
types
char
int
float
double
Qualifiers / Modifiers :
Size qualifier - short.
long.
Sign qualifier - signed.
unsigned.
18
RULES OF C
Data types : There are 4 basic data
types
char
int
float
double
Qualifiers / Modifiers :
Size qualifier - short.
long.
Sign qualifier - signed.
unsigned.
Type qualifier - const.
19
RULES OF C
int
– used to declare numeric program variables of integer type, size in
the memory is 2 or 4 bytes.
– whole numbers, positive and negative
– Keyword : int
– Example : int number; number = 12;
char
– equivalent to ‘letters’ in English language
– Example of characters:
• Numeric digits: 0 - 9
• Lowercase/uppercase letters: a - z and A - Z
• Space (blank)
• Special characters: , . ; ? “ / ( ) [ ] { } * & % ^ < > etc
– single character
– Size in the memory is 1 byte
– Keyword : char
– Example : char my_letter; my_letter = 'U';
20
RULES OF C
• float
– fractional parts, positive and negative
– keyword: float, size is of 4 bytes.
float height;
height = 1.72;
• double
– used to declare floating point variable of higher precision
or higher range of numbers
– exponential numbers, positive and negative
– keyword: double, size is of 8 or 10 bytes
double value_big;
value_big = 12E-3;
21
RULES OF C
Basic Data Data Types with Size
Range
Type type qualifiers (bytes)
char signed char 1 -128 to 127
Unsigned char 1 0 to 255
int int or signed int 2 -32768 to +32767
unsigned int 2 0 to 65535
short int or
1 -128 to 127
signed short int
Unsigned short int 1 0 to 255
Long int or
4 -2147483648 to 2147483647
Signed long int
Unsigned long int 4 0 to 4294967295
Float Float 4 3.4E -38 to 3.4E +38
Double Double 8 1.7E -308 to 1.7E +308
Long Double 10 3.4E -4932 to 1.1E +4932
22
RULES OF C
Constants
23
RULES OF C
CONSTANTS
Char Constant : Character is enclosed in single quotes eg ‘a’
This refers to ASCII Character Set which
contains 256 characters
i.e numbered from 0 to 255.
Example : A-Z (65 – 90), a-z (97 - 122)
0-9 (48 - 57)
Numerical Constant
25
RULES OF C
Integer Constant
Dec - Base 10
Oct - Base 8
Hex - Base 16
26
RULES OF C
Expression : a=x+y;
27
RULES OF C
Compound Statement : {
Statement 1;
a=b+c;
;
….
Statement n;
}
28
QUESTIONS
Define
Data-type?
Identifier?
Variable?
Initialization?
Name
Size qualifiers?
Type qualifiers?
Signed qualifiers?
29
SAMPLE PROGRAM
#include<stdio.h>
main(void)
{
int sum = 100;
printf(“Hello World \n”);
printf(“The value of sum is : %d”, sum);
}
30
INPUT AND OUTPUT EXAMPLE
#include<stdio.h>
main(void)
{
int a=0, b=0, c=20;
printf(“INPUT A VALUE : ”);
scanf(“%d”,&b); // & simbol is called address operator
a=b+c;
printf(“The sum of b and c is : %d\n”, a);
}
31
Format Specifier for Printf()
%c - Single Char
%o - unsigned Octal
%s - String
33
Formatted Input and Output
Formatted Integer Input
%wd
Case 1
When input data length is less than or equal to the given field width, the input
values are unaltered and stored in given variables.
Input : 6 394
Output : 6 is stored in a and 394 is stored in b
Case 2
When input data length is more than the given field width, the input values are
altered and stored in the variable as -
Input : 639 456
Output : 63 is stored in a and 9 is stored in b, rest is ignored.
34
Formatted Input and Output
Formatted Integer Output
%wd
Case 1: When the length of variable is less than the width specified
Value of variables are a = 78, b= 9;
Output is a=_ 78, b=_ _ _ 9 ( underscore symbol are spaces).
Case 3: When the length of variable is more then the width specified
Value of variables are a = 7832, b= 987634;
Output is a=7832, b=987634.
35
Formatted Input and Output
Formatted Floating Point Numeric Input
%wf
Case 1 When input data length is less than or equal to the given width, values
are unaltered and stored in the variables
Input : 5_5.92 note : underscore is a space.
Output : 5.0 is stored in a and 5.92 is stored in b.
Case 2 When input data length is more than the given width, the entered
values are altered and stored in the given variables.
Input : 5.93_65.875
Output : 5.9 is stored in a and 3.00 is stored in b.
36
Formatted Input and Output
Formatted Floating Point Numeric Output
%wnf
Eg : printf(“a=%4.1f, b= %7.2f”, a, b);
Here w is the integer number specifying the total width of the input data and n
is the number of digits to be pointed after decimal point. By default 6 digits are
printed after the decimal.
If the total length of the variable is less than the specified width w, then the
value is right justified with leading blanks. If the number of digits after decimal
is more than n, the digits are rounded off.
Value of variables : 8 5.9
Output : a=8.0, b=_ _ _5.90
Value of variables : 25.3 1635.92
Output : a=25.3, b=1635.92
Value of variables : 15.231 65.875948
Output : a=15.2, b=_ _65.88
37
Formatted Input and Output
Formatted string input
%ws
Here w specifies the total number of characters that will be stored in the string.
char str[8];
Scanf(“%3s”,str);
Input : Srivastava
Output : ‘s’,’r’,’i‘,’\0’. The null char ‘\0’ is automatically stored at the end
38
Formatted Input and Output
Formatted string output
%w.ns
Here w specifies field width, Decimal point and n, are optional. If present then n
specifies that only first n characters of the string will be displayed and (wn)
leading blanks are displayed before string.
39
QUESTIONS
What is / Define Name
Keyword
function
main()
printf()
scanf()
40
OPERATORS AND EXPRESSION
An operator specifies an expression to be performed that yields a
value. An operand is a data item on which on operator acts.
Total 9 Operators
1. Arithmetic Operator
2. Assignment Operator
3. Increment and Decrement Operator
4. Relational Operator
5. Logical / Boolean Operator
6. Conditional Operator
7. Comma Operator
8. Size of Operator
9. Bitwise Operator
41
OPERATORS AND EXPRESSION
Arithmetic Operator
+ addition
- subtraction
* multiplication
/ division
% modular (gives the reminder in integer division.
This cannot be applied with floating point operators)
42
OPERATORS AND EXPRESSION
Assignment Operator
Eg : a = 5, a = b + c, a=c
43
OPERATORS AND EXPRESSION
Increment and Decrement Operator
Increment - ++
Decrement - --
Operator will increment / decrement by 1
They can be used with only variables
Eg : a++, b++
Wrong Eg : 5++, (a+b+5)++
There are two types
Prefix Increment (Pre Increment) - ++a
Prefix Decrement(Pre Decrement) - --a
Postfix Increment (Post Increment) - a++
Postfix Decrement(Post Decrement)- a--
Prefix Postfix
y=++a y=a++
y=--a y=a--
44
OPERATORS AND EXPRESSION
Relational Operator
< less than
<= less than equal to
> Greater than
>= Greater than equal to
== Equal to (Compares two expression)
!= Not equal to
Eg : a=9, b=5
Expression Relation Value of Expression
a<b False 0
a<=b False 0
a==b False 0
a!=b True 1
a>b True 1
a>=b True 1
a==0 False 0
b!=0 True 1
a>8 True 1
2>4 False 0
45
OPERATORS AND EXPRESSION
Logical Operator
&& AND (Binary Operator)
|| OR (Binary Operator)
! NOT (Unary Operator)
Truth Table
AND OR NOT
A B C A B C A !A
0 0 0 0 0 0 0 1
0 1 0 0 1 1 1 0
1 0 0 1 0 1
1 1 1 1 1 1
46
OPERATORS AND EXPRESSION
Conditional Operator / Ternary Operator
47
Assignments
2. SUM = (a = 8, b = 7, c = 9, a+b+c)
4. Check if the num is Even or Odd using modular and ternary operator.
48
OPERATORS AND EXPRESSION
Comma Operator
The comma operator is used to permit different expressions to appear
in situations. The expressions are separated by comma operator. The
separated expressions are evaluated from left to right.
Eg int a=5, b=2, c=a+b;
Size of Operator
Size of is an Unary Operator that gives the size of it operator in terms
of bytes. The operand can be a variable, constant or any data type.
Eg : int a
sizeof(a) or sizeof(int);
Generally sizeof() operator is used to make programs as portable.
49
OPERATORS AND EXPRESSION
Bitwise Operator
| Bitwise OR
~ One’s Complement
^ Bitwise XOR
50
OPERATORS AND EXPRESSION
Bitwise Operator
~ One’s Complement
Eg : 76543210 76543210
~0==-1 0 0 0 0 0 0 0 0 1 1 1 1 1 1 1 1
~1==-2 0 0 0 0 0 0 0 1 1 1 1 1 1 1 1 0
~3==-4 0 0 0 0 0 1 1 1 1 1 1 1 1 0 0 0
<< Bitwise Left Shift
Eg : 76543210 76543210
1<<3 0000000100001000
4<<3 0000010000100000
7<<3 0000011100111000
>> Bitwise Right Shift
Eg : 76543210 76543210
1>>3 0000000100000000
4>>1 0000010000000010
7>>1 0000011100000011
7>>3 0000011100000000
51
Advanced
Bitwise
Operator
52
Advanced Bitwise Operation
Four advanced bitwise operation.
(i) To check the status of a particular bit.
53
Advanced Bitwise Operator
(i) To check the status of a bit :
54
Advanced Bitwise Operator
(ii) Setting a particular bit : num = num | (1 << bit_position)
num |=(1<<bit_position)
55
Advanced Bitwise Operator
(iii) Clearing a particular bit : num = num & (~(1 << bit_position))
num &=~(1<<bit_position)
56
Advanced Bitwise Operator
(iv) Toggling a bit : num = num ^ (1<<bit_position)
num ^=(1<<bit_position)
57
Type Conversions
1. Type Conversion in Assignment Implicit Type
Implicit Type
58
Type Conversions
Implicit Type Conversion in Assignment :
59
Type Conversions
Implicit Type Arithmetic Conversion : When a type conversion is
performed automatically by the compiler without programmer intervention, such
type of conversion is known as implicit type conversion or type promotion.
The compiler converts all operands to type of variable on left side of
assignment operator before assigning value to it.
Eg : int a=5
float b = 6.32
char c = 3
a = b+c
b is float = 6.32
c is char which is converted to float i.e c = 3.000000
result is 9.320000
a is int, so the result is converted to int (i.e 0.320000 is truncated)
Final result a = 9.
60
Type Conversions
Explicit Type Conversion – TYPE CASTING : Type casting in c is done
as follows
Eg : {
int x=5, y=3;
float p,q;
p = x/y;
printf(“p = %f\n”, p);
q = (float) x/y;
printf(“q = %f\n”, q);
return0;
}
61
C - PRECEDENCE
Eg : a=8, b=4, c=2, d=1,e=5, f=20;
expression = a + b – (c + d) * 3 % e + f / 9
5th : 12 1st : 3 4th : 2
2nd : 9
3rd : 4
6th : 8
7th : 10
62
CONTROL
STATEMENTS
63
CONTROL STATEMENTS
Selection Statements
(i) if . . . . . else
(ii) switch . . . . case
Iterative Statements
Jump Statements
(i) break
(ii) continue
(iii) goto
64
if . . . . else statement
This is a selection control statement, which is used to take either one or
more than one possible actions.
Syntax for
Only if if . . . . else Nesting if . . . else
if(expression) if(expression) if(expression-1)
statement-1; statement-1; statement-1;
else else if(expression-2)
statement-2; statement-2
next statement; next statement; else if(expression-3)
statement-3
else
statement-4
next statement;
The expression inside the parentheses is evaluated and if it is true (has
a non-zero value), then the statement-1 is executed and if the expression is false
(zero) then statement-2 is executed
65
if . . . . else Assignment
Write a Program
66
switch . . . . case
This is a selection control statement, which is used to take one of the ‘n’
possible actions.
Syntax for
switch (expression)
{
case constant 1 : statement 1; . . . . statement n;
case constant 2 :
.......
case constant n : statement 1 ; . . . . statement n;
default : statement 1 ; . . . . Statement n;
}
The expression inside the parentheses is evaluated and if it is true (has
a non-zero value), then the statement-1 is executed and if the expression is false
(zero) then statement-2 is executed
67
for loop
This is a control flow statement for specifying iteration, which allows
code to be executed repeatedly for specified number of times.
Syntax for
for(init of exp ; conditional expression ; updating expression)
Eg : int i =0;
for (i=0;i<10;i++)
{
statement-1; statement-2;. . . . . statement-n;
}
68
do . . . while loop
This is a control flow statement for specifying iteration, which allows
code to be executed repeatedly for specified number of times.
Syntax for
do
{
statement-1;
.....
statement-2;
} while(expression);
Eg : int i =0;
do
{
statement-1; statement-2;. . . . . statement-n;
i++;
} while(i<10);
69
while loop
This is a control flow statement for specifying iteration, which allows
code to be executed repeatedly for specified number of times.
Syntax for
While(expression)
{
statement-1;
.....
statement-2;
};
Eg : int i =0;
while(i<10)
{
statement-1; statement-2;. . . . . statement-n;
i++;
};
70
nesting loop
Eg : int i =0, j=0;
do
{
statement-1; statement-2;. . . . . statement-n;
do
{
statement-1; statement-2;. . . . . statement-n;
j++;
}while(j<10);
i++;
} while(i<10);
71
nesting loop
Eg : int i =0, j=0;
for(i=0 ; i<10 ; i++)
{
statement-1; statement-2;. . . . . statement-n;
for(j=0 ; j<10 ; j++)
{
statement-1; statement-2;. . . . . statement-n;
}
}
72
break, continue statement
Break statement is used inside the loops and switch statement. Some
time it becomes necessary to come out of the loop even before the loop
condition becomes false. In such situations, break statement is used to
terminate the loop. This statement causes an immediate exit from the loop.
Difference : break terminates the loop, continue will transfer the control to
next iteration bypassing the statements after continue in that particular iteration.
73
Assignment
Write a Program
Using only Switch…. Case
1. To find Even / Odd of an given value.
3. Check the character for vowel and print “The character is vowel” else print
“The character is not a vowel”.
More on Exercise.docx
74
goto statement
Syntax : goto label ;
--------
--------
label : statement-1;
-------
-------
This is called as forward jump. When encountered goto label, control
jumps to label and starts execution of statements after the label. By passing the
statements after goto and before label.
label : statement-1;
--------
--------
goto label ;
--------
--------
This is called as backward jump. When encountered got label, control
jumps to label and starts execution of statements after the label.
goto label will work only in same function
75
FUNCTIONS
76
FUNCTIONS
Functions is self contained subprogram that performs some specific,
well defined task. Any C program consists of one or more functions. If a
program has only one function then it must be the main() function. It is the first
function to be executed when the program starts, all other functions are called
directly or indirectly from main().
main()
{
1.--------
2.--------
3. function_1(); void function_1()
4 -------- {
5.-------- 1.--------
} 2.--------
3. --------
4 --------
5.--------
}
78
LOCAL, GLOBAL AND STATIC VARIABLES
Local Variable : The variables that are defined within the body of a function or a block are local
to that function or block only and are called local variables. These variables are created when function
is entered and are destroyed when the function is exited.
Global Variable : The variables that are defined outside any function are called global variables.
All functions in the programmer can access and modify global variables. It is useful to declare a
variable global if it is to be used by many functions in the program, Global variables are automatically
initialized to 0 at the time of declaration.
79
LOCAL, GLOBAL AND STATIC VARIABLES
Local Variable : The variables that are defined within the body of a function or a block are local
to that function or block only and are called local variables. These variables are created when function
is entered and are destroyed when the function is exited.
Global Variable : The variables that are defined outside any function are called global variables.
All functions in the programmer can access and modify global variables. It is useful to declare a
variable global if it is to be used by many functions in the program, Global variables are automatically
initialized to 0 at the time of declaration.
Static Variable : Static variables are declared by writing keyword static in front of the
declaration. If a static variable is not initialized then it is automatically initialized to 0. The variables
value will not get destroyed even when calling function comes out of the function.
Eg : #include<stdio.h> Here b is a static variable. First time when the function is
void function(void); called b is initialized to 10. Inside the function, value of b
int main(void) becomes 11. This value is retained and when next
time the
{ function is called, value of b is 11 and the initialization is
func(); neglected. Similarly when third time function is called, value
func(); of b is 12. Note that the variable a which is not static is
func(); initialized on each call and its value is not retained.
return 0;
}
void function(void)
{
int a=10;
static int b=10;
printf(“a=%d, b=%d\n”,a,b);
a++, b++;
}
80
FUNCTIONS
Library Functions The library functions are formally not a part of the C
language, but they are supplied with every C compiler. The source code of the library
functions is not given to the user. These functions are precompiled and the user gets only
the object code. This object code is linked to the object code of your program by the
linker.
User-Defined Functions : This functions are defined by Users
In both cases library and user defined , the function definition, declaration and call of
library functions :
(i) Function Declaration – In header file (files with a .h extension)
(ii) Function Definition – Predefined, precompiled and present in the library
(iii) Function Call - By the programmer
81
FUNCTIONS
1. Function Declaration : Function declaration is used to give specific information to
the compiler about the functions so that it can check the functions calls. The calling
function needs information about the called function. If definition of the called is placed
before the calling function, then declaration is not needed.
2. Function Definition : Function definition consists of the whole description and
code of a function. It tells what the function is doing and what is its input and output. A
function definition consists of two parts – a function header and a function body.
Eg : void function(void)
function is nether receiving nor returning the value
int function(int a , int b);
passing parameters to functions and returning a value
3. Function Call : The function definition describes what a function can do,
but to actually use it in the program the function should be called somewhere. A function
is called by simply writing its name followed by the argument list inside the parentheses.
Function name is the called function while the function in which this function call is placed
is known as the calling function. For example in the program main() is the calling function,
sum() is the called function.
82
FUNCTIONS
User-Defined Functions
4. Return statements : The return statement is used for immediate exit (hand over
control) from the called function to the calling function and to return a value to the calling
function. This statement can appear any where inside the body of the function. There are
two ways in which it can be used : return ; (or) return (expression);
Eg : return 0, return 1.
return ++x, return (x+y*z), return (3*sum(a,b)).
83
FUNCTIONS
Function Returns Control to Calling Function Function Returns Control to Calling Function
main() main()
{ {
1.-------- 1.--------
2.-------- 2.--------
3. function_1(); void function_1(void) 3. function_1(); void function_1(void)
4 -------- { 4 -------- {
5.-------- 1.-------- 5.-------- 1.--------
} 2.-------- } 2.--------
3. -------- 3. return
4 -------- 4 --------
5.return 5.return
} }
Function Returns Control with a value Function Returns Control with a processed value
main() main()
{ {
1.-------- 1.--------
2.-------- 2.--------
3. function_1(); void function_1(void) 3. function_1(); void function_1(void)
4 -------- { 4 -------- {
5.-------- 1.-------- 5.-------- 1.int a=100+30;
} 2.-------- } 2.--------
3. return 0 3. return a;
4 -------- 4 --------
5.return 5.return
} }
84
FUNCTIONS
User-Defined Functions
5. Function Parameters and arguments : Parameters are mentioned in the
function definition and they are used to hold the values that are sent by the calling
function. These parameters are like other local variables of the function which are created
when the function call starts and are destroyed when the function ends.
First difference is that parameters are declared inside parentheses while other local
variables are declared at the beginning of the function block.
Second difference is that parameters are automatically initialized with the values of the
corresponding arguments provided in the function call while other local variables are
assigned values through the statements written inside the function body.
Any changes made to the parameters inside the function do not affect the
actual arguments. This mechanism of passing arguments is called call-by-value.
The other mechanism where arguments passed to the called function can
change the original parameters of calling function is called call-by reference(used in
pointers concept).
85
FUNCTIONS
Function Call By Value
Function returns control along with a Value (OR) Processed Value
main()
{
1.int a=5,b=6;
2.--------
3. function_1(a,b); int function_1(int c, int d)
4 -------- {
5.-------- 1.int a;
} 2. a = c + d;
3.return a
}
86
FUNCTIONS
User-Defined Functions
6. Order of evaluation of function arguments : The order of evaluation of arguments and
sub-expressions within the arguments is unspecified. This order of evaluation is not important in
function calls like mul(m,n) or mul(m+n, m-n). But let us take a case where int m=3, k; and k=mul(m,
m++). Here the first value is evaluated first then the value of k is 9, and if second value is evaluated
first then the k will result in 12.The order of evaluation of arguments is unspecified in C and depends
on compiler.
7. main () function: Execution of every C program always begins with the function main(). Each
function is called directly or indirectly in main() and after all functions have done their operations,
control returns back to main(). There can be only one main() function in a program. The main() is a
user defined function but the name, number and type of arguments are predefined in the language.
The operating system calls the main function and main() returns a value of integer type to the
operating system. If the value returned zero, it implies that the function has terminated successfully
and any nonzero return value indicates an error. If no return value is specified in main() then any
garbage value will be returned automatically.
Function Declaration – By the C compiler
Function Definition – By the programmer
Function Call – By the Operating System.
Classification of functions into four types depending on the return value and arguments.
1. Functions with no arguments and no return value Eg : void function(void), function()
2. Functions with no arguments but a return value Eg : int function(void), int function()
3. Functions with arguments and no return value Eg : void function(int a, char b)
4. Functions with arguments and return value Eg : int function (int a, char b)
87
Recursive Functions
Recursive Function is a function that calls itself.
Flow Control in simple function call
main()
{
1.--------
2.--------
3. function_1();
void function_1()
4 --------
{
5.--------
1.--------
}
2.--------
3. function_2(); void function_2()
4 -------- {
5.-------- 1.--------
} 2.--------
3. function_3(); void function_3()
4 -------- {
5.--------- 1.--------
} 2.--------
3.--------
4 --------
5.--------
}
88
Recursive Functions
Recursive Function is a function that calls itself.
Flow Control in Recursive Function i.e function calling itself.
main()
{
1.--------
2.--------
3. function(5); void function(int n)
4 -------- {
5.-------- 1.if(n==1)
} 2. return;
3. function(n-2); void function(int n)
4 -------- {
5.-------- 1.if(n==1)
} Here n is 5 2. return;
3. function(n-2); void function(int n)
4 -------- {
5.-------- 1.if(n==1)
} Here n is 3 2. return;
3.function(n-2);
4 --------
5.--------
} Here n is 0
89
Recursive Functions
Factorial Example : n=3, factorial of n is 3*2*1;
int main(void)
{
-----
f = fact(3); long fact(int n)
----- {
} if(n==0)
return1;
3*2=6 return(n*fact(n-1); long fact(int n)
}n=3 {
if(n==0)
return1;
#include<stdio.h> 2*1=2
return(n*fact(n-1); long fact(int n)
long int fact(int n);
}n=2 {
int main(void)
if(n==0)
{
return1;
int num=3; 1*1=1
return(n*fact(n-1); long fact(int n)
printf(“factorial = %d”, fact(num));
}n=1 {
}
if(n==0)
long int fact(int n) 1
return1;
{
return(n*fact(n-1);
if(n==0)
}n=0
return 1;
return(n*fact(n-1));
}
90
FUNCTIONS ASSIGNMENTS
Write a program for following.
2. Menu driven program using functions and switch-case, Main Menu containing
options, when selected an option, control has to jump to that function, clear
screen, display sub menu with relevant options, With suitable option perform an
action, go back to main menu. Also manage error messages if options are not
with in limit.
91
STORAGE CLASSES
92
STORAGE CLASSES
There are four storage classes in C :
93
STORAGE CLASSES
There are four storage classes in C :
94
Key Place of Life Initial Place of
Scope Linkage Initialize
Word Declaration Time Value Storage
Through Through
auto -Out Side Memory Constant/
out out Zero None
(global) Function block (data area) Variable
Program Program
96
ARRAYS
97
ARRAYS
An array is a collection of similar type of data items and each data item
is called an element of array. The data type of the elements may be any valid
data type like char, int or float. The elements of array share the same variable
name but each element has a different index number known as subscript.
- If your index number is greater than of size of array then it will show a run time
error or it will results in garbage values.
- If you define array size as ‘n’ and you initialize a value to a single array
Element, The rest of the elements holds garbage or zero values.
- If variable declaration is global then the value stored by default is zero.
- If variable declaration is local then the value stored by default is garbage
values
Types of Arrays : Single Dimensional Arrays, Two Dimensional Arrays,
Three Dimensional Arrays.
The processing elements we generally use loops.
The size of array depends on data type declared multiplied by number of
subscripts.
For example char name[10], the size of array is calculated as
1byte x 10 subscripts = 10 bytes.
98
ARRAYS
Syntax : 1D Array - int age[100],
2D Array - char student_name[100][20],
3D Array - char class_student_name [10][50][20]
99
ARRAYS
Array to Functions
1. Passing the whole array to the function. 2. Passing the array element to the function.
#include<stdio.h> #include<stdio.h>
void function(int arr[]); void function(int n);
int main(void) int main(void)
{ {
int arr[5] = {5, 10, 15, 20, 25}; int arr[5] = {5, 10, 15, 20, 25};
function(arr); for(i=0 ; i<5 ; i++)
return 0; function(arr[i]);
} return 0;
void function(int arr[]) }
{ void function(int n)
int i=0; {
for(i=0 ; i<5 ; i++) if(n%2==0)
{ printf(“%d is Even”, n);
if(arr[i]%2==0) else printf(“%d is Odd”, n);
printf(“%d is Even”, arr[i]); }
else printf(“%d is Odd” , arr[i]);
}
}
100
ARRAYS ASSIGNMENTS
Write a program for following.
101
STRINGS
102
STRINGS
Introduction to Strings
Def : String is collection of more than one character.
In c strings are treated as arrays of type char and are terminated by a null
character (‘\0’). This null character has ASCII value zero.
There are two forms of initialization of a string variables.
char str[10] = {‘I’,’N’,’D’,’I’,’A’,’\0’};
char str[10] = “INDIA”;
char str[] = “INDIA”;
103
STRINGS
Introduction to Strings
104
POINTERS
105
POINTERS
Pointer : Pointers are user defined variables which can hold address of
another variable.
106
POINTERS
Single Pointer :
void main(void) a
{ 5
int a = 5; 500
int *p;
p = &a; p
printf(“value of a is %d”, a); 500
printf(“address of a is %d”, &a); 700
printf(“value of p is %d”, p);
printf(“address of p is %d”, &p);
printf(“value of *p is %d”, *p);
}
Output : value of a is 5
address of a is 500
value of p is 500
address of p is 700
value of *p is 5
107
POINTERS
Double Pointer : It is a user defined variables which can hold the address of
another pointer variable (single pointer variable)
Eg : int **p; a
5
Eg : int a = 5; 500
int *p; // single pointer
int **q; // double pointer p
p = &a; 500
q = &p; 700
Printf(“%d\n%d\n”, *p,*q);
q
Ouput: 700
*p = 5; 600
*q = address value of 700 (garbage value)
108
POINTERS
Triple Pointer : It is a user defined variables which can hold the address of
pointer variable (single pointer variable)
Eg : int ***p; a
5
Eg : int a = 5; 500
int *p; // single pointer
int **q; // double pointer p
500
int ***r; // Triple pointer
p = &a; 700
q = &p;
r = &q; q
700
600
r
600
800
109
POINTERS
Pointer Arthmetic
for example we take two pointer variables i.e p1 and p2
110
POINTERS
Example : int a =5, *p1 = &a;
char b = ‘A’, *p2 = &b; a
15
float c = 20.5, *p3 = & c;
500
p1++, p2++, p3++;
b
A
Output :
600
p1++ p1=p1+1 p1 = 500 + (1x4bytes) = 504
p1=p1+2 p1 = 500 + (2x4bytes) = 508 c
(because int is of 4 bytes) 20.5
700
p2++ p2=p2+1 p2 = 600 + (1x1byte) = 601 p1
p2=p2+2 p2 = 600 + (2x1bytes) = 602 500
(because char is of 1 bytes) 800
P2
p3++ p3=p3+1 p3 = 700 + (1x4byte) = 704 600
p3=p3+2 p3 = 700 + (2x4bytes) = 708 900
(because float is of 4 bytes)
P3
700
1000
111
POINTERS
Rule 3 : Relation operator can be used between two pointers.
Eg : int a = 10, b = 10;
int *p1, *p2;
if(*p1>*p2)
printf(“even”);
else printf(“odd”);
Rule 4 : sizeof operator can be used to find out size of a pointer variable.
Here p1, p2 and p3 holds the address of variables, address will be always 4 bytes.
void pointer
Definition : void pointer can hold the address of any data type variable.
Eg :
void main(void)
{
int a = 10;
float b = 10.5;
void *p;
p=&a;
printf(“%p”, (int *)p);
printf(“%p”, *(int *)p);
P=&b;
printf(“%p”, (float *)p);
printf(“%f”, * (float *)p);
}
112
POINTERS AND ARRAYS
#include<stdio.h>
int main(void)
{
int arr[5] = {5,10,15,20,25};
int i;
for(i=0; i<2; i++)
{
printf("arr[%d] = %d\t",i,arr[i]);
printf("&arr[%d] = %p\n",i,&arr[i]);
}
printf("\n\n");
main()
{
1.int a=5,b=6,c;
2.;
3. c= function_1(a,b); int function_1(int c, int d)
4 .printf(“%d”,c); {
5.; 1. ;
} 2. ;
3. ;
4. ;
5. return c+d;
}
115
POINTERS AND FUNCTIONS
In call by value, only the values of arguments are sent to the function and
any changes made to the formal parameters do not effects the actual arguments.
In call by reference, addresses of arguments are sent to the function and
any changes made to the formal parameters will take effect to the actual arguments.
main()
{
1.int a=5,b=6,c;
2.;
3. function_1(&a,&b,&c); void function_1(int *d, int *e, int *f)
4 .printf(“%d%d%d”,a,b,c); {
5.; 1 ;
} 2 ;
3 ;
4 *f = *d + *e;
5. return;
}
116
POINTERS AND FUNCTIONS
Function Returning Pointer
int *function_1(void)
main()
{
1.int *a;
2.;
3. a = function_1(void); int *function_1(void)
4 .printf(“%d - %d”,a,b); {
5.; 1. int a=10;
} 2. int *p=&a;
3. ;
4. ;
5. return p;
}
117
POINTERS TO STRINGS
Syntax : Char *p = “Hello”;
- p is holding base address.
- *p is pointing to first element of declaration.
- p++ is incrementing the value in side the p.
So incrementing base address by one.
Eg : void main(void)
{
char *p = “Hello”;
int i =0;
for(i=0; i<5; i++)
{
printf(“%p \t”, (p+i));
printf(“%c \n”,*(p+i));
}
}
118
STRING
LIBRARY
119
STRING LIBRARY
String Library
Predefined functions
120
STRING LIBRARY
Example for strlen() (Using Predefined Function)
#include<stdio.h>
#include<strlib.h>
void main(void)
{
char str[20] = “Hello”;
int length;
length = strlen(str);
printf(“%d”, length);
}
121
STRING LIBRARY
Example for strlen() (using user defined function with arrays)
#include<stdio.h>
int str_len(char str[]);
void main(void)
{
char str[20] = “hello”;
int length;
length = str_len(str);
printf(“length of string = %d”, length);
}
int str_len(char str[ ])
{
int i=0;
while( str[i] != ‘\0’ )
{
i++;
}
return i;
}
122
STRING LIBRARY
Example for strlen() (using user defined function with pointers)
#include<stdio.h>
Int str_len(char *p);
void main(void)
{
char str[20] = “hello”;
int length;
length = str_len(str);
printf(“length of string = %d”, length);
}
int str_len(char *p)
{
int i=0;
while( *p != ‘\0’ )
{
i++, p++;
}
return i;
}
123
STRING LIBRARY
Example for strcmp() (Using Predefined Function)
#include<stdio.h>
#include<strlib.h>
void main(void)
{
char str_1[20], str_2[20];
printf(“str_one : “);
gets(str1);
printf(“str_two : “);
gets(str2);
if(strcmp(str1, str2) == 0)
printf(“strings are matching”);
else printf(“strings not matching”);
}
124
STRING LIBRARY
Example for strcmp() (using user defined function with arrays)
#include<stdio.h> int str_cmp(char str_1[], char str_2[])
int str_cmp(char str_1[], char str_2[]); {
void main(void) int i = 0;
{ if(str_len(str_1) != str_len(str_2))
char str_1[20], str_2[20]; return 1;
printf("str_one : "); else
gets(str_1); {
printf("str_two : "); while(str_1[i] != '\0‘ && str_2[i] != '\0')
gets(str_2); {
if(str_cmp(str_1, str_2) == 0) if(str_1[i] != str_2[i])
printf("strings are matching"); return 1;
else printf("strings not matching"); i++;
} }
return 0;
}
}
125
STRING LIBRARY
Example for strcmp() (using user defined function with pointers)
#include<stdio.h> int str_cmp(char *str_1, char *str_2)
int str_cmp(char *str_1, char *str_2); {
void main(void) int i = 0;
{ if(str_len(str_1) != str_len(str_2))
char str_1[20], str_2[20]; return 1; // Consider 1 as not matching
printf("str_one : "); else
gets(str_1); {
printf("str_two : "); while(*str_1 != '\0‘ && *str_2 != '\0')
gets(str_2); {
if(str_cmp(str_1, str_2) == 0) if(*str_1 != *str_2)
printf("strings are matching"); return 1;
else printf("strings not matching"); str_1++, str_2++;
} }
return 0; // Consider 0 as matching
}
}
126
STRING LIBRARY
Example for strcpy() (Using Predefined Function)
#include<stdio.h>
#include<stdlib.h>
void main(void)
{
char str_1[20], str_2[20];
printf(“str_one : “);
gets(str_1);
printf(“str_two : “);
gets(str_2);
strcpy(str_1, str_2);
puts(str_1);
puts(str_2);
}
127
STRING LIBRARY
Example for strcpy() (using user defined function with arrays)
#include<stdio.h> int str_cpy(char str_1[], char str_2[])
int str_cpy(char str_1[], char str_2[]); {
void main(void) int i = 0;
{ {
char str_1[20], str_2[20]; while(str_2[i]!='\0’ || str_1[i]!=‘\0’)
printf("str_one : "); {
gets(str_1); str_1[i] = str_2[i];
printf("str_two : ");
gets(str_2); i++;
str_cpy(str_1, str_2); }
puts(str_1); str_1[i] = ‘\0’;
puts(str_2); }
} }
128
STRING LIBRARY
Example for strcmp() (using user defined function with pointers)
#include<stdio.h> int str_cpy(char *str_1, char *str_2)
int str_cpy(char *str_1, char *str_2); {
void main(void) int i = 0;
{ {
char str_1[20], str_2[20]; while(*str_2 != '\0’ || *str_1 != ‘\0’)
printf("str_one : "); {
gets(str_1); *str_1 = *str_2;
printf("str_two : ");
gets(str_2); str_1++, str_2++;
str_cpy(str_1, str_2); }
puts(str_1); *str_1 = ‘\0’;
puts(str_2); }
} }
129
STRING LIBRARY
Example for strcat() (Using Predefined Function)
#include<stdio.h>
#include<strlib.h>
void main(void)
{
char str_1[20], str_2[20];
printf(“str_one : “);
gets(str_1);
printf(“str_two : “);
gets(str_2);
strcat(str_1, str_2);
puts(str_1);
puts(str_2);
}
130
STRING LIBRARY
Example for strcat() (using user defined function with arrays)
int str_cat(char str_1[], char str_2[])
#include<stdio.h>
{
int str_cat(char str_1[], char str_2[])
int i = 0,j = 0;
void main(void)
while(str_1[i]!=‘\0’)
{
i++;
char str_1[20], str_2[20];
str_1[i] = ‘ ‘;
printf(“str_one : “);
i++;
gets(str_1);
printf(“str_two : “);
while(str_2[i]!='\0’)
gets(str_2);
{
str_cat(str_1, str_2);
str_1[i] = str_2[j];
puts(str_1);
puts(str_2);
i++,j++;
}
}
str_1[i] = ‘\0’;
}
131
STRING LIBRARY
Example for strcat() (using user defined function with pointers)
int str_cat(char *str_1, char *str_2)
#include<stdio.h>
{
int str_cat(char *str_1, char *str_2)
int i = 0,j = 0;
void main(void)
while(*str_1!=‘\0’)
{
str_1++;
char str_1[20], str_2[20];
*str_1 = ‘ ‘;
printf(“str_one : “);
str_1++;
gets(str_1);
printf(“str_two : “);
while(*str_2!='\0’)
gets(str_2);
{
str_cat(str_1, str_2);
*str_1 = *str_2;
puts(str_1);
puts(str_2);
str_1++, str_2++;
}
}
*str_1 = ‘\0’;
}
132
STRUCTURES
133
STRUCTURES
Structures : Structure is a collection of different elements with different
datatypes.
Eg : struct student
{
char name[15];
int roll;
float marks;
} stu1;
134
STRUCTURES
Different methods for initialization of members of a structure
1st method : stu1 = { “name”, 123, 80.33};
2nd method : strcpy (stu1.name, “name”);
stu1.roll = 123;
stu1.marks = 80.33;
3rd method : scanf(“%s”, &stu1.name) (or) scanf(“%s”, stu1.name);
scanf(“%d”,&stu1.roll);
Note : (i) By defining a structure, memory is not allocated by the computer. Only after
declaration of structure variable memory is being allotted by the computer.
(ii) Structure can be declared as global or local. If structure is declared as
global then any user defined function can assess the structure. If structure is
declared as local in a particular user defined function then it can be assessed
only by that function.
(iii) Inside the structure definition we cannot initialize the members of
structures.
WRONG WAY OF INITIALIZATION
struct student
{
int roll = 1234;
char name[15] = “name”;
float marks = 45.02;
{
135
STRUCTURES
Types of Structures
136
STRUCTURES
Array of Structures :
#include <stdio.h>
struct student
{
char Name[10];
int rollno;
float marks;
};
int main()
{
int i;
struct student stu[10];
for(i =0;i<10;i++)
{
printf("Enter Name, rollNo, Marks: ");
scanf("%S%d%f",&stu[i].Name, &stu[i].rollno, &stu[i].marks);
}
for(i=0;i<10;i++)
{
printf("%s %d %f\n",stu[i].Name, stu[i].rollno, stu[i].marks);
return 0;
}
}
137
struct student
{
char Name[10];
int rollno;
float marks[2];
};
int main()
{
int i,j;
struct student stu[3];
for(i =0;i<2;i++)
{
printf("Enter the data for student%d\n", i+1);
printf("Enter the name: ");
scanf("%s", stu[i].Name);
printf("Enter rollno :");
scanf("%d", &stu[i].rollno);
for(j=0;j<3;j++)
{
printf("Enter marks for subject %d: ", j+1);
scanf("%d", &stu[i].marks[j]);
for(i=0;i<2;i++)
{
printf("%d", stu[i].marks[j]);
printf("\n");
}
return 0;
138
} }}}
STRUCTURES
Structures To Functions :
struct student struct student
{ {
char name[15]; char name[15];
int roll; int roll;
float marks; float marks;
}; };
void function(char name[ ], int roll, float marks); void function(struct student std2);
void function(char name[ ], int roll, float marks) void function(struct student std2)
{ {
printf(“name %s\n”,name); printf(“name %s\n”,std2.name);
printf(“roll %d\n”, roll); printf(“roll %d\n”, std2.roll);
printf(“marks %f\n”, marks); printf(“marks %f\n”, std2.marks);
} }
139
STRUCTURES
Size of Structure :
By using size of operator we can find out the size of sturcture.
Syntax : sizeof(structure tag); (or) sizeof(structure variable);
Eg : sizeof(structure student) (or) sizeo(std1);
Structure padding :
In gcc compiler structure padding is happening as.
struct student
Internal memory is allocated as given below
{
char a; // 1bytes char – -0-x-x-x-
char name[5]; // 1byte x 5 = 5bytes char – -0-1-2-3-4-x-x-x-
int roll; int – -0-1-2-3-
float marks; Float – -0-1-2-3-
}; In the above structure the data type which holds
more bytes, that is being considered for allocating
the memory for each single variable or element.
140
NESTED STRUCTURES
Nested structures (structures within structures) :
struct tag1
{
member1;
member2;
struct tag2
{
member1;
member2;
------
memeber m;
}var1;
------
member n;
}var2;
141
Example:
struct student
{
char name[10];
int rollno;
struct date
{
int day;
int month;
int year;
}birthdate;
float marks;
}stu1,stu2;
Example:
stu1.birthdate.day
stu2.birthdate.year
142
UNIONS
Syntax : Similar to structure declaration and initialization.
union union_tag
{
data_type member;
.....
data_type member;
};
union union_tag variable_name;
Example :
union student
{
char name[20];
int Roll;
float marks;
};
union student std_1;
143
UNIONS
Example :
void main(void)
{
strcpy(std.name, ”surya”);
printf(“%s”,std.name);
std.roll=65;
printf(“%s”,std.name);
printf(“%d”,std.roll);
}
OUTPUT: surya
A
65
Note :
- Members of unions, internally they are sharing single memory location.
- Compiler allocates highest data_types, bytes in the memory.
- One member can be assessed at a time.
144
struct stag
{
char c;
int i;
float f;
};
union utag
{
char c;
int i;
float f;
};
int main(void)
{
union utag uvar;
struct stag svar;
printf("size of svar = %u\n", sizeof(svar));
printf("Address of svar: %p\t",&svar);
printf("Address of members : %p %p %p\n", &svar.c, &svar.i, &svar.f);
printf("size of uvar = %u\n", sizeof(uvar));
printf("Address of svar: %p\t",&uvar);
printf("Address of members : %p %p %p\n", &uvar.c, &uvar.i, &uvar.f);
}
#pragma pack(value);
Packing and padding
BIT FIELDS
Example :
struct student
{
unsigned int roll : 3;
} std_1;
void main(void)
{
std.roll = 1; printf(“%d \n”, std.roll);
std.roll = 4; printf(“%d\n”, std.roll);
std.roll = 7; printf(“%d\n”,std.roll);
std.roll = 8; printf(“%d\n”,std.roll);
}
OUTPUT: 1 0-0-1
4 1-0-0
7 1-1-1
0 0-0-0
Note : In the example given above, int is of 4 bytes, but by specifying bitfield to compiler as
unsigned int roll : 3, you are specifying compiler that only 3 bits of lower nibble is to be assessed.
146
typedef
typedef : It is a key word. By using typedef, we can replace user defined tags
in the place of data_type keyword.
Eg:
Eg : typedef int integer;
#include<stdio.h>
- int is a keyword which is replaced by integer;
void main(void)
eg : integer a = 5; {
integer roll; typedef int integer;
integer a=6, b=8;
typedef for structures : printf(“%d %d \n”, a,b);
Eg : }
typedef struct student
{
int roll;
char grade[5];
} abcd;
void main(void)
{
// struct student std_1; // need not to declare in this manner
abcd std_1 = {153, “A”};
printf(“%d %s”, std_1.roll, std_1.grade);
}
147
FILES
148
FILES
Files is a collection of data or information that has a name, called the
filename. Almost all information stored in a computer must be in a file. There
are many different types of files: data files, text files , program files,
directory files, and so on.
Operation on Files :
(i) Write Operation
(ii) Read Operation
(iii) Modification (appending)
Steps for file operations in C programming :
- Open a file
- Read data from the file or Write data to the file
- Close the file
Steps for Creating a File :
fopen(); - Opening a file
fwrite(); - writing to the file
fread(); - reading from the file
fclose(); - Closing the file
149
FILES
Text and Binary streams :
In C Input and output stream of data-operation on file is performed with the
help of library functions. File management is done by the execution environment, and
streams are channels through which data can flow from program to environment and
from environment to program. When file is opened, a stream is associated with a file and
when file is closed the same stream is disassociated with the file. There are two types of
stream – text stream and binary streams. Text stream is a stream of characters and
binary stream is a stream of unprocessed bytes.
Buffer :
Buffer is an area in memory where the data is temporarily stored before being
written to the file. When we open a file, a buffer is automatically associated with its file
pointer. Whatever data we send to the file is not immediately written to the file. First it is
sent is sent to the buffer and when the buffer is full, its contents are written to the file.
EOF EOF
150
Types of buffers:
Fully Buffered Stream: The data is transferred only when the buffer is full.
Line Buffered Stream: the data is transferred either when buffer is full or when a
newline character is written to the buffer.
151
FILES
Opening a File :
File must be opened before any I/O operations can be performed on that file.
The process of establishing a connection between the program and file is called opening
the file. When a file is opened, a stream is associated with that file, a buffer is created in
the main memory for transferring data to and from the file.
A structure named FILE is defined in the header file <stdio.h> that contains all
information about the file like name, status(read, write etc), buffer location, current
position in the buffer, end of file status, error status etc.
A file pointer(stream pointer) is a pointer to a structure of type FILE. The
function fopen() is used to open a file. fopen() function takes two strings as arguments,
the first one is the name of the file to be opened and second one is the mode that
decides which operations (read, write, append etc) are to be performed on the file.
Error Handling : On error, fopen() returns NULL and On success, fopen() returns a
pointer of type FILE. The return value of fopen is assigned to a FILE pointer declared
previously.
2. “a” (append) : If the file doesn’t exist then this mode creates a new file, and if the
file already exists then the new data entered is appended at the end of existing dat. In
this mode, the data existing in the file is not erased as in “w” (write) mode.
3. “r” (read) : This mode is used for opening an existing file for reading purpose
only. The file to be opened must exist and the previous data of file is not erased.
153
FILES
Closing a File :
The file which was opened using fopen() function must be closed when no
more operations are to be performed on it. After closing the file, connection between file
pointer and file is broken. Now the file pointer fptr is there to connect some other file. On
closing the file, the buffer associated with it is flushed i.e all the data that is in the buffer
is written to the file and the buffers allocated by the system for the file are freed after the
file is closed, so that these buffers can be available for other files.
Error Handling : On error fclose() returns EOF and On success fclose() returns 0 (EOF
is a constant defined in stdio.h and its value is -1)
Declaration : int fclose(FILE *fptr);
If more than one files are opened, then we can close all the files by calling
fclose() for each file.
fclose(fptr1);
fclose(fptr2);
---------
We can also close multiple files by calling a single function fcloseall(); It closes
all the opened files.
Declaration : int fcloseall(void);
Error Handling : On error, fcloseall() returns EOF and On success it returns the
number of files closed.
154
FILES
End of File :
The file reading functions need to know the end of file so that they can stop
reading. When the end of file reached, the operating system sends an end-of-file signal to
the program. When the program receives the signal, the file reading functions return
EOF, which is a constant defined in the file stdio.h and its value is -1.
Standard streams :
When the program starts executing, the operating system opens three
standard text streams automatically and provides constant file pointers for them.
File pointer Stream Buffering
stdin Standard input Line-buffered
stdout Standard output Line-buffered
stderr Standard error Unbuffered
Functions used for file I/O are :
Read Operation Write Operation
Character I/O : fgetc() fputc()
String I/O: fgets() fputs()
Formatted I/O : fscanf() fprintf()
Record I/O : fread() fwrite()
155
Structure of a File Program
Int main()
{
FILE *fp;
fp = fopen(“filename”, mode);
-----------------------
-----------------------
fclose(fp);
return0;
}
156
fputc()
Declaration: int fputc(int c, FILE *fptr);
fgetc()
Declaration: int fgetc(FILE *fptr);
157
158
FILES
Some of Errors on File Operation :
- If you create a file with write mode but if you try to read the file then it will show error.
- If you create a file with read mode but if you try to write on file then it will show error.
- If you try to access a file without proper permission modes then it will show error.
- If you try to create a file and there is no space in disk, then it will show error.
159
DYNAMIC
MEMORY
ALLOCATION
160
DYNAMIC MEMORY ALLOCATION
DMA : Allocating of memory at the runtime is called Dynamic Memory Allocation.
161
DYNAMIC MEMORY ALLOCATION
There are 4 predefined functions (defined in stdlib.h)
1.malloc(); 2. calloc(); 3. realloc(); 4. free();
163
PRE PROCESSOR DIRECTIVE
164
PRE PROCESSOR DIRECTIVE
Definition : If any statement will start with # symbol, it is called a preprocessor
directive. They are invoked by the compiler to process some programs before
compilation.
Advantages :
(i) Readability of program will becomes easy.
(ii) Debugging & testing of a program becomes easy.
(iii) Execution time is less
(iv) Code density will decrease.
Features:
(i) Preprocessor directive will start with # symbol
(ii) Expression replacement is very easy
(iii) Semicolon (;) will not be used to terminate preprocessor directive statements
(iv) Preprocessor directive is generally is a one line statement, but if you want to
continue with next line, we place a backslash (\)
The function of Preprocessor Directives :
(i) Simple Macro replacement
(ii) Macro with expression replacement
(iii) Conditional Compilation.
165
PRE PROCESSOR DIRECTIVE
(i) Simple Macro replacement :
Example_One Example_Two Example_Two
#include <stdio.h> #include <stdio.h> #include <stdio.h>
#define size 10
void main(void) #define marks 10 #define Hi printf(“Hi”)
{ #define size marks #define scan_i scanf(“%d”,&i);
int arr_one[size];
int arr_two[size-3]; void main(void) void main(void)
} { {
if(size>30) int I;
printf(“Hi”) scan_i;
else printf(“Hello”); printf(“%d”, i);
} Hi;
}
166
PRE PROCESSOR DIRECTIVE
(ii) Conditional Compilation Preprocessor :
Preprocessor Directives :
#define Test 5
# if void main(void)
# else {
# elif - else if printf(“HELLO\n”);
# endif #if Test > 2
# ifdef - if define. printf(“Hi”);
# ifndef - if not define. #endif
# undif - undefine. printf(“Bye”);
}
167
enum - Enumeration Constants
enum is another user-defined data type consisting of a set of
named constants called enumerators.
> Using a keyword enum, it is a set of integer constants represented
by identifiers.
> The values in an enum start with 0, unless specified otherwise, and
are incremented by 1. For example, the following enumeration,
enum days {Mon, Tue, Wed, Thu, Fri, Sat, Sun};
> Creates a new data type, enum days, in which the identifiers are
set automatically to the integers 0 to 6.
> To number the days 1 to 7, use the following enumeration,
enum days {Mon = 1, Tue, Wed, Thu, Fri, Sat, Sun};
168
Command Line Arguments
169
Command Line Arguments
• When executing a program in either C or C++ there is a
way to pass arguments to the program at command
prompt (called as Command Line Arguments).
171
Command Line Arguments
#include <stdio.h> // SAVED AS add
printf("\t\t%d", add);
return 0;
172
C Program as Command
#include <stdio.h> // Saved as LIST
void main(void)
{
system("cls");
system(“dir”);
system(“c:”);
}
173
*****
*******
*************
******************
174