lecture note on programming in “c” · ansi c standard emerged in the early 1980s, this book was...
TRANSCRIPT
LECTURE NOTE on
PROGRAMMING IN “C”
COURSE CODE: SNTGC21
BY
M. GUHAPRIYA MCA.,M.PHIL.,B.ED.,
ASSISTANT PROFESSOR,
DEPARTMENT OF COMPUTER SCIENCE,
PARVATHY’S ARTS AND SCIENCE COLLEGE, DINDIGUL.
UNIT - I
HISTORY AND IMPORTANCE OF C
C is a programming language developed at AT & T’s Bell Laboratories of USA in 1972. It was
designed and written by a man named Dennis Ritchie. In the late seventies C began to replace
the more familiar languages of that time like PL/I, ALGOL, etc
ANSI C standard emerged in the early 1980s, this book was split into two titles: The original
was still called Programming in C, and the title that covered ANSI C was called Programming
in ANSI C.
C seems so popular is because it is reliable, simple and easy to use.
BASIC STRUCTURE AND PROGRAMMING STYLE OF C
PROGRAM
Comment line
It indicates the purpose of the program. It is represented as
/* */
Comment line is used for increasing the readability of the program. It is useful in explaining the
program and generally used for documentation. It is enclosed within the decimeters. Comment
line can be single or multiple line but should not be nested. It can be anywhere in the program
except inside string constant & character constant.
Preprocessor Directive:
#include<stdio.h> tells the compiler to include information about the standard input/output
library. It is also used in symbolic constant such as #define PI 3.14(value). The stdio.h (standard
input output header file) contains definition &declaration of system defined function such as
printf( ), scanf( ), pow( ) etc. Generally printf() function used to display and scanf() function
used to read value
Global Declaration:
This is the section where variable are declared globally so that it can be access by all the
functions used in the program. And it is generally declared outside the function .
main()
It is the user defined function and every function has one main() function from where actually program is
started and it is encloses within the pair of curly braces. The main( ) function can be anywhere in the
program but in general practice it is placed in the first position.
/*First c program with return statement*/
#include <stdio.h> int main (void)
{
printf ("welcome to c Programming language.\n"); return 0;
}
Output: welcome to c programming language.
Steps for Compiling and executing the Programs
A compiler is a software program that analyzes a program developed in a particular computer
language and then translates it into a form that is suitable for execution on a particular computer
system.
Documentation Section
Link Section
Definition Section
Global Declaration Section
main() function section
{
Declaration part;
Executable part;
}
Sub program section
function 1
function 2
function 3
(User defined Function)
:
function n
Programming style:
▪ C is a free form language.
▪ C can use only lower case letters.
▪ Uppercase letters can be used only for symbolic constant. Ex:a=b+c.
Constants, Variables & Data types:
Character set:
1. Letters Uppercase A…Z; Lowercase a…z;
2. Digits All decimal digits 0…9;
3. Special Characters . : ; ? “ „ / ~ ` ! @ # $ % ^ & * ( ) { } [ ] –
4. White spaces 1.Blank space, 2.Horizontal tab, 3.Carriage return, 4.Newline, 5. Formfeed.
C Tokens:
1. Keywords – set of predefined words . Ex. Float,while,for.
2. Identifier – function name and variable name. Ex.main(),amount.
3. Constants – Values used as constant.Ex. -15.5, 100.
4. Strings – Ex. “ABC” “year”.
5. Special symbols – Ex. [ ], { }.
6. Operators - +, -, * ,/.
Constants:
Constants are of two types; 1. Numeric &2. Character.
1. Numeric constants are classified into Integer and Real.
2. Character constants are classified into Single Character and String constants.
Integer Constant types are:
i. Decimal integer ------ 0-9 with + or – sign
ii. Octal integer ----- 0-7.
iii. Hexadecimal integer------ 0x or 0X ; A-F or a-f after 0-9.
Real Constant:
Quantities like distance, temperature, prices are represented using real values.
Expression: mantissa e exponent.
Ex: 2.15
Character Constant: Ex: „5‟ , „x‟, „A‟
String Constants : Sequence of characters. Ex: “Hello”, “2+3”, “1990..”.
Variables:
i. It is a data name, used to store a value.
ii. It may be letters, digits & characters.
Ex. John,distance.
Data types:
1. Primary (or) Fundamental data types.
2. Derived data type.
3. User-defined data type.
1.Primary data types
1.1. Integral types -----classified into Integer and Character.
1.1.1. Integer----- classified into signed and unsigned.
1.1.1.1. Signed Integer includes
1. int,
2. short int,
3.long int.
1.1.1.2. Unsigned Integer
1. Unsigned int,
2. Unsigned short int,
3. Unsigned long int.
1.1.2. Character
1. Char 2. Signed char 3.Unsigned char.
1.2. Floating point types
1.Float 2. Double 3. Long double.
1.3. void.
Range of values: 1 byte= 8 bits.
S.No. Datatype Range Size (Bytes)
1. char -128 to 127 1
2. integer -32,768 to 32,767 2
3. float 3.4e -38 to 3.4 e+38 4
4. double 1.7 e-308 to 1.7 e+308 8
Declaration of variables:
• It tells the compiler what the variable name is and what type of data it will hold.
Syntax:
datatype v1,v2,v3,. . . ,vn;
where, v1,v2,v3,. . . ,vn are variable name.
Ex: int count;
Assigning values to Variables:
Ex: value = amount + inrate * amount;
Value is the target
variable. Assignment statement is;
Variablename = constant;
where, = is assignment operator.
Ex: price= 100;
Declaration of storage class:
-----Provides information about their location and visibility.
-----Storage class decides the portion of the program within which the variables are recognized.
0. Auto – Local variables known only to the function.
1. Static – Local variables which retains its value even after the control is transferred.
2. Extern – Global variable known to all function.
3. Register – Local variable which is stored in register.
Reading data from keyboard:
Syntax: scanf(“control string”, &variable1, &variable2,…);
Ex: scanf(“%d”, &number);
Writing data:
Syntax: printf(“control string”, statements);
Ex: printf(“Hello”);
printf(“Value is %”, c);
Defining symbolic constants:
Syntax: #define symbolic_name value_of_constant
Ex: #define MAX 100
Overflow & Underflow of Data:
Data over flow occurs when the value of a variable is either too big or too small.
An underflow results in zero.
Ex: Simple program
#include<stdio.h>
#include <conio.h>
void main()
{
int a,b,c;
clrscr();
printf(“\n Enter values for a & b:”);
scanf(“%d%d,&a,&b);
c=a + b;
printf(“\nValue of c is: %d”,c);
getch();
}
OPERATORS AND EXPRESSIONS
• An operator is a symbol that tells the computer to perform certain mathematical
(or) logical manipulations.
• Operators are used in the programs to manipulate data and variables.
• Ex. 10 + 5 =15. Where, 10, 5 are operands & + is operator.
Types of operators:
1. Arithmetic operators.
2. Relational operators.
3. Logical operators.
4. Assignment operator.
5. Increment and Decrement operators.
6. Conditional operators.
7. Bitwise operators.
8. Special operators.
ARITHMETIC OPERATORS:
i. + - Addition (or) Unary plus.
ii. - - Subtraction (or) Unary minus.
iii. * - Multiplication.
iv. / - Division.
v. % -Modulo division.
• Unary minus (-), multiplies its operand by -1.
• Ex. a+b, a-b,a*b;
• Integer arithmetic - a+b;
• Real arithmetic x=6.0 / 7.0;
• Mixed mode arithmetic - Both integer and real arithmetic.
RELATIONAL OPERATORS:
• Comparisons can be done.
• Value of a relational expression is either 1 or 0 [1-true and 0- false].
• Ex: 10 < 20 is true.
20 < 10 is false.
OPERATOR MEANING
i. < - is less than.
ii. > - is greater than.
iii. <= - is less than or equal to.
iv. >= - is greater than or equal to.
v. == - is equal to.
vi. != - is not equal to.
Logical Operators
Following table shows all the logical operators supported by C language. Assume variable A holds 1 and variable B holds 0, then –
Operator Description Example
&& Called Logical AND operator. If both the operands are
non-zero, then the condition becomes true. (A && B) is false.
|| Called Logical OR Operator. If any of the two operands
is non-zero, then the condition becomes true. (A || B) is true.
! Called Logical NOT Operator. It is used to reverse the
logical state of its operand. If a condition is true, then !(A && B) is true.
Logical NOT operator will make it false.
Assignment Operators
The following table lists the assignment operators supported by the C language −
Operator Description Example
= Simple assignment operator. Assigns values from
right side operands to left side operand
C = A + B will assign the value
of A + B to C
+=
Add AND assignment operator. It adds the right
operand to the left operand and assign the result to
the left operand.
C += A is equivalent to C = C +
A
-=
Subtract AND assignment operator. It subtracts the
right operand from the left operand and assigns the
result to the left operand.
C -= A is equivalent to C = C - A
*=
Multiply AND assignment operator. It multiplies the
right operand with the left operand and assigns the
result to the left operand.
C *= A is equivalent to C = C *
A
/=
Divide AND assignment operator. It divides the left
operand with the right operand and assigns the result
to the left operand.
C /= A is equivalent to C = C / A
%=
Modulus AND assignment operator. It takes
modulus using two operands and assigns the result
to the left operand.
C %= A is equivalent to C = C %
A
<<= Left shift AND assignment operator. C <<= 2 is same as C = C << 2
>>= Right shift AND assignment operator. C >>= 2 is same as C = C >> 2
&= Bitwise AND assignment operator. C &= 2 is same as C = C & 2
^= Bitwise exclusive OR and assignment operator. C ^= 2 is same as C = C ^ 2
|= Bitwise inclusive OR and assignment operator. C |= 2 is same as C = C | 2
sizeof & ternary
Besides the operators discussed above, there are a few other important operators including sizeof
and ? : supported by the C Language.
Operator Description Example
sizeof() Returns the size of a variable. sizeof(a), where a is integer, will return 4.
& Returns the address of a variable. &a; returns the actual address of the
variable.
* Pointer to a variable. *a;
? : Conditional Expression.
If Condition is true ? then value X :
otherwise value Y
INCREMENT AND DECREMENT OPERATORS:
* Increment operator is ++; it adds 1 to the operand.
* Decrement operator is - -; it subtracts 1 to the operand.
Ex: ++m; (or) m++;
--m; (or) m--;
++m – prefix operator adds 1 first, then result is assigned.
m++ - postfix operator assigned the value to the variable and then adds 1 to it.
Conditional Operators / Ternary Operator:
“ ? : “ – these are the symbols used for conditional operators.
Syntax: Exp1 ? Exp2 :Exp3;
Ex:a=10,b=5; x = (a>b) ? a : b;
Operators Precedence in C
Operator precedence determines the grouping of terms in an expression and decides how an expression is
evaluated. Certain operators have higher precedence than others; for example, the multiplication operator
has a higher precedence than the addition operator.
Category Operator Associativity
Postfix () [] -> . ++ - - Left to right
Unary + - ! ~ ++ - - (type)* & sizeof Right to left
Multiplicative * / % Left to right
Additive + - Left to right
Shift << >> Left to right
Relational < <= > >= Left to right
Equality == != Left to right
Bitwise AND & Left to right
Bitwise XOR ^ Left to right
Bitwise OR | Left to right
Logical AND && Left to right
Logical OR || Left to right
Conditional ?: Right to left
Assignment = += -= *= /= %=>>= <<= &= ^= |= Right to left
Comma , Left to right
UNIT – II
MANAGING INPUT OUTPUT OPERATIONS
All input and output operations are carried out through function calls such as “printf and
scanf”.
i. Reading a Character:
- Reading a single character can be done by using “getchar function”.
- Format is; variablename =getchar();
- char name;
- name =getchar();
C supports some character functions, that are present in “ctype.h” file, it must be included in the
program. #include<ctype.h>.
- printf function is used for printing results.
- printf(“control string”, arg1,arg2,…,argn);
- format is; %w.p typespecifier.
- where, w - an integer for fieldwidth
- p – an integer specifier, specifies no. of digits to the decimal point.
ii. Writing a Character:
- For printing a character one at a time, putchar() function is used.
- putchar(variable_name);
- where, variable_name is a char type variable.
- Ex: answer = „y‟.
- putchar(answer);
iii. Formatted Input:
- It refers input data has been arranged in a particular format.
- scanf(“control string”,arg1,arg2,…);
- For integer -- %d, %5d;
- For Real numbers -- %f, %lf;
- For Character strings-- %wc, %ws;
iv. Formatted Output:
- printf function is used for printing results.
- printf(“control string”, arg1,arg2,…,argn);
- format is; %w.p typespecifier.
- where, w - an integer for fieldwidth
- p – an integer specifier, specifies no. of digits to the decimal point.
DECISION MAKING AND BRANCHING
C language possesses decision making capabilities. Such as,
i. If statement.
ii. Switch statement.
iii. Conditional operator statement.
iv. Goto statement.
These statements are known as decision making statements and they control the flow of execution
called as control statements.
IF STATEMENT:
It is a two way decision making.
Format is, if(test expression)
Different forms of if statement;
➢ Simple if statement.
➢ If… else statement.
➢ Nested if… else statement.
➢ Else if ladder.
1. Simple If Statement:
General form of a simple if statement is; if
(test expression)
{
Statement – block;
}
Statement – X;
2. If … Else Statement:
General form is;
if(test expression)
{
True block statement;
}
else
{
False block statement;
}
Statement x;
3. Nesting of If… Else Statement:
When a series of decisions involved, nesting of if…else is used.
if (test condition1)
{
if (test condition 2)
{
Statement 1;
}
else
{
Statement 2;
}
}
else
{
if (test condition 3)
{
Statement 3;
}
else
{
Statement 4;
}
}
4. Else … If Ladder:
When multiple decisions are involved, chain of if statement associated with each else. This construct
is known as else… if ladder.
General format is;
if(condition 1)
statement1;
else if (condition2)
statement 2;
else if (condition 3)
statement 3;
else if (condition n)
statement n;
else
statement x;
SWITCH STATEMENT:
It is used for built-in multi way selection.
Tests the value of a given variable (or expression) against list of case value.
When a match found, a block statements associated with that case is executed.
General form is;
switch (expression)
{
case value 1:
block1;
break;
case value 2:
block 2;
break;
……………..
default :
default- block;
break;
} statement x;
The conditional operator:
Format is;
Conditional expression ? expression 1 : expression 2;
Goto statement:
This statement is used to branch unconditionally from point to another in the program.
Goto requires a label in order to identify the place where branch is to be made.
General form is;
goto label;
………...
………..
Label:
DECISION MAKING AND LOOPING:
Looping:
Sequences of statements are executed until some conditions for termination of loop are
satisfied.
A program loop consists of two segments.
i. Body of the loop, ii. Control statement.
Depending on the position of control statement in loop, it classified as,
i. Entry controlled loop, ii. Exit controlled loop.
Four steps of a looping process:
1. Setting and initialization of a condition variable.
2. Executions of the statements are in the loop.
3. Test for a specified value of the condition variable for execution of the loop.
4. Incrementing (or) updating the condition variable.
Three constructs of looping operations are;
While statement Do… while statement For statement
Basic format is; General format is; General form is;
while (test condition) do for(initialization; test
{ { condition; iteration)
Body of the loop Body of the loop {
} } Body of the loop
while(test condition); }
Jumps in loops:
Jumping from one statement to another statement.
An early exit of the loop accomplished by “break” or “goto” statement.
while (….)
{
………..
………..
if(condition)
break; (exit from loop)
…………
}
UNIT – III
ARRAY
Array is the collection of similar data types or collection of similar entity stored in contiguous
memory location. Array of character is a string. Each data item of an array is called an element. And
each element is unique and located in separated memory location. Each of elements of an array share
a variable but each element having different index no. known as subscript.
An array can be a single dimensional or multi-dimensional and number of subscripts determines its
dimension. And number of subscript is always starts with zero. One dimensional array is known as
vector and two dimensional arrays are known as matrix.
ADVANTAGES: array variable can store more than one value at a time where other variable can
store one value at a time.
Example:
int arr[100];
int mark[100];
DECLARATION OF AN ARRAY :
Its syntax is :
Data type array name [size];
int arr[100];
int mark[100];
int a[5]={10,20,30,100,5}
The declaration of an array tells the compiler that, the data type, name of the array, size of the array
and for each element it occupies memory space. Like for int data type, it occupies 2 bytes for each
element and for float it occupies 4 byte for each element etc. The size of the array operates the
number of elements that can be stored in an array and it may be a int constant or constant int
expression.
We can represent individual array as :
int ar[5];
ar[0], ar[1], ar[2], ar[3], ar[4];
Symbolic constant can also be used to specify the size of the array as:
#define SIZE 10;
One dimensional array:
- A list of items given with one variable name called as single subscripted variable. - =1 →
Declaration:
General form is;
data type variable name[size];
Ex: int group[10];
For character strings;
char name[20] = “welldone”;
Initialization:
i. Compile time Initialization:
Syntax: data type arrayname[size] = {list of values};
Ex: int number[3] = {0,0,0};
ii. Run-time Initialization:
Ex:int n[3]; scanf(“%d%d%d”,&n[0],&n[1],&n[2]);
Two Dimensional Arrays:
C provides an option to define a table of items such as “two dimensional array”.
Declaration:
data type arrayname [row size] [column size];
Initialization:
It can be written as,
Ex: int table [2] [3] = {0, 0, 0, 1, 1, 1};
Multi dimensional array:
C allows three or more dimensions in arrays.
General form of a multi dimensional array is;
data type array name [s1] [s2]…….[sn];
Ex:
int survey [3] [4] [5];
Dynamic arrays:
Dynamic memory allocation functions are calloc, malloc, realloc.
<stdlib.h> header file is used for these functions.
Applications of arrays:
❖ Using pointers for accessing arrays.
❖ Passing arrays as function parameters.
❖ Arrays as members of structures.
❖ Using structure type data as array elements.
❖ Arrays as dynamic data structures.
❖ Manipulating character arrays and strings.
CHARACTER ARRAYS AND STRINGS:
String
is a sequence of characters treated as a single data item.
group of characters defined between double quotes.
Ex: “WELCOME”.
Common operations on strings:
i. Reading and Writing strings.
ii. Combining strings together.
iii. Copying one string to another.
iv. Comparing strings for equality.
v. Extracting a position of a string.
Declaration:
Declaration of a string variable is;
Syntax: char stringname[size];
Ex: char name[20];
char city[30];
Initialization:
char city [10] =”NEWYORK”;
char city [20] = {„N‟,‟E‟,‟W‟,‟Y‟,‟O‟,‟R‟,‟K‟,‟\0‟};
Reading Strings From Terminal:
scanf function is used to read an input string from terminal.
Ex: char address[10];
scanf(“%s”, address);
We want to read more than one word; we have to declare separate arrays for every word.
Ex: char addr[10],city[20];
scanf(“%s%s”, addr,city);
Writing strings to terminal:
printf function is used.
Ex: printf(“%s”, name);
Getchar and Gets Function:
i. getchar – to read a single character from the terminal.
char ch;
ch=getchar();
ii. gets – it reads sequence of characters called string from terminal.
gets(str)
Ex: char line[20];
gets(line);
printf(“%s”,line);
Putchar And Puts Function:
i. putchar – to display a single character.
char ch=‟A‟;
putchar(ch);
printf(“%c”,ch);
ii. puts – prints the string.
puts(str);
Ex: char line[40];
gets(line); puts(line);
Arithmetic operations on characters:
To write a character in its integer representation, ASCII value are used.
For example;
x = „A‟;
printf(“%d”,x);
output is: x=65.
C library supports a function that converts a string into integer value.
x= atoi(string);
String Handling Functions:
1. strcat() – concatenates two strings.
2. strcmp() – compares two strings.
3. strcpy() – copies one string over another.
4. strlen() – find the length of a string.
5. strrev() – reverses the given string.
i. strcat() function:
- it concatenates two strings.
Syntax: strcat( string1, string2);
Ex: strcat(“wel”,”come”);
ii. strcmp() function:
- it compares two strings and gives the answer as both are equal or not.
Syntax: strcmp( string1, string2);
Ex: strcmp( “hello”,”hai”);
iii. strcpy() function:
--- it copies one string over another. It means the second string copies over first string.
Syntax: strcpy( string1, string2);
Ex: strcpy( “ram”, “ravi”);
iv. strlen() function:
- it finds the length of the given string.
Syntax: n=strlen(string);
Ex: n=strlen(“hello”);
v. strrev() function:
- it reverses the given string.
Syntax: strrev(string);
Ex: strrev(“hai”);
Output: iah.
Other String Functions:
i. strnccat();
ii. strncmp();
iii. strncpy();
iv. strstr();
Features Of Strings:
1. Manipulating strings using pointers.
2. Using string as function parameters.
3. Declaring and defining strings as member of structure.
UNIT IV
FUNCTIONS
Function –Meaning:
The program is divided into functional parts then each part may be independently coded and
combined into a single unit. These independently coded programs are called subprograms and these
are referred to as Functions.
Two major categories:
i. Binary functions
ii. User defined functions
Elements of user defined functions:
1. Function declaration.
2. Function definition.
3. Function call.
Function Declaration:
General form is;
functiontype functionname(argument list)
Ex: void sum(int a,int b);
int age();
Definition of a function:
Elements are;
1. Function name;
2. Function type;
3. List of parameters;
4. Local variable declarations;
5. Function statements &
6. A return statement.
General form is;
functiontype functionname(parameter list)
{
local variable declaration;
executable statement1;
executable statement2;
…………..
………….
return statement;
}
Ex:
float mul(float x,float y)
{
float result;
result= x* y;
return ( result);
}
Categories of Functions:
I. Functions with no arguments and no return values.
II. Functions with arguments and no return values.
III. Functions with arguments and one return value.
IV. Functions with no arguments and return value.
V. Functions that return multiple values.
A function depending an whether the arguments are present or not and whether a value is returned or
not, may belong to one of following categories
1. Function with no return values, no arguments
2. Functions with arguments, no return values
3. Functions with arguments and return values
4. Functions with no arguments and return values.
1.).In this category, the function has no arguments. It does not receive any data from the calling
function. Similarly, it doesn’t return any value. The calling function doesn’t receive any data from
the called function. So, there is no communication between calling and called functions
2.)In this category, function has some arguments . it receives data from the calling function, but it
doesn’t return a value to the calling function. The calling function doesn’t receive any data from the
called function. So, it is one way data communication between called and calling functions
3.)In this category, functions has some arguments and it receives data from the calling function.
Simillarly, it returns a value to the calling function. The calling function receives data from the
called function. So, it is two-way data communication between calling and called functions.
4.In this category, the functions has no arguments and it doesn’t receive any data from the calling
function, but it returns a value to the calling function. The calling function receives data from the
called function. So, it is one way data communication between calling and called functions.
Rules for pass by Pointers: (Function call by address or reference)
i. The types of actual and formal parameters must be same.
ii. The actual arguments (function call) must be addresses of variables that are local to the
calling function.
iii. The formal arguments in the function header must be prefixed by indirection operator
(*).
iv. In the prototype the arguments must be prefixed by the symbol (*).
v. To access the value of an actual argument in the called function we must use the
corresponding formal argument prefix with the indirection operator (*).
Nesting of functions:
A function calls another function.
Recursion (or) Recursive Function:
A function calls itself.
Ex:
main()
{
printf(“Recursion”);
main();
}
Program to find factorial of a given number:
#include<stdio.h>
#include<conio.h>
int factorial(int n);
void main()
{
int m;
clrscr();
printf(“\n Enter a number:”);
scanf(“%d”,&m);
f=factorial(m);
printf(“%d”,f);
getch();
}
int factorial(int n)
{ int fact;
if(n==1)
return(1);
else
fact=n*factorial(n-1);
return(fact);
}
Passing array to function:
One Dimensional Array: To pass an one dimensional array to a called function, specify the name of
the array without any subscript and size of the array.
For Ex:
largest(a,n);
Declaration of function will be;
float largest(float array[],int size);
Passing Strings to functions:
Strings are treated as character arrays.
Function Definition:
void display(char itemname[])
{
………………
………………
}
Function Prototype:
void display(char str[]);
Function Call:
display(names);
Scope, Visibility and Lifetime of Variables:
A variable retains its value throughout the program.
Storage classes:
1. Automatic variables.
2. External variables.
3. Static variables.
4. Register variables.
Automatic Variables:
Declared inside a function. Also referred as local (or) internal variables. Keyword is
“auto”.
Ex:
main()
{ auto int number;
……………….
……………….
}
External Variables:
Variables alive throughout the program. Also known as global variables. These are declared
outside of the function.
Ex:
int count;
main()
{
count=100;
}
Static Variables:
Value of this variable persist until end of the program. Keyword is “static”.
static int x;
Ex:
void stat(void);
main()
{
………………….
………………….
}
void stat(void)
{
static int x=0;
x=x+1;
}
Register Variables:
A variable should be kept in machine‟s register instead of keeping in memory.
Ex:
register int count;
STRUCTURES AND UNIONS:
C supports a constructed data type known as structures.
It means a mechanism for packing data of different types.
Structure is a convenient tool for handling a group of logically related data items.
Ex:
Time: Hours, Minutes, Seconds.
Book: Title, Author, Price, Year.
Defining a structure:
struct book
{
char title[20];
char author[20]; int
year;
float price;
};
Declaring Structure Variable:
struct book book1,book2;
It can also written as,
struct book
{
char title[20];
char author[20];
int year;
float price;
};
struct book book1,book2;
Structure Initialization:
A structure variable can be initialized at compile time.
Another method is to initialize a structure variable outside the function.
Compile time initialization must have the following elements:
i. Keyword struct.
ii. Structure tag name.
iii. Name of the variable to be declared.
iv. Assignment operator “=”
v. Set of values for the members of the structure variable, separated by commas and
enclosed in braces.
vi. A terminating semicolon.
Accessing Structure Members:
The link between a member and a variable is established using “Member Operator” or
“Dot/ Period operator”.
For Ex; book1.price;
Runtime Initialization:
Giving values through keyboard.
For ex;
scanf(“%s”,book1.title);
scanf(“%d”,&book1.year);
Copying and comparing structure variables:
Two variables of the same structure type can be copied.
Ex: person1=person2;
C does not permit logical operations on structures.
Arrays of Structure:
- An array of structures may be declared as, struct class student[20];
- This declares the student as an array of three elements as student[0],
student[1],student[2]…..
- Ex: struct marks student[3] = { { 50,60,70}.{70,80,90},{65,75,85}};
Structures within structures:
It means nesting of structures.
Ex:
struct salary
{
char name[20];
char dept[15];
struct
{
int da;
int hra;
int cca;
} allowance;
}employee;
- This members in the inner structure can be referred as,
employee.allowance.da; employee.allowance.hra;
Structures and Functions:
The general format of sending a copy of a structure to the called function is;
<function name(structure variable name);>
Called function takes the following form,
< data type function name(struct.type struct.name)
{
………….
………….
return(expression);
} >
UNIONS:
It is likely to be structure.
The major distinction between them in terms of storage.
In structure each member has its own storage location, where as all the members of a union
use the same location.
Ex:union item
{
int m;
float x;
char c;
}code;
Size of structures:
sizeof(struct x);
- The unary operator sizeof is used to tell the size of a structure or any variable.
Bit Fields:
- C permits us to use small bit fields to hold data items and thereby to pack several data items in a
word of memory.
- A bit field is a set of adjacent bits whose size can be from 1-16 bits in length.
- A word can be divided in to a number of bit field.
- The name and size of bit fields are defined using a structure.
- Ex: struct tagname
{
data type name1: bit length;
………….
data type nameN:bit length;
}
- The bit length is decided by the range of value to be stored.
- Largest value that can be stored is [2n-1], n is bit length.
Layout of bit length field;
15 14 13 12 11 10 9 8 7 6 5 4 3 2 1 0
UNIT V
POINTERS
Pointers:
➢ A pointer is a directed data type.
➢ Pointers contain memory addresses as their values.
➢ Pointers can be used to access and manipulate data stored in the memory.
Definition:
A Pointer variable is a variable that contains an address of another variable.
Declaration:
data type *ptname;
The asterisk ( * ) tells the variable ptname is a pointer variable.
ptname needs memory location.
ptname points to a variable of that data type.
Benefits of Pointers:
✓ Pointers are more efficient in handling arrays and data tables.
✓ Pointers can be used to return multiple values from a function via function
arguments.
✓ Pointers permit reference to functions and thereby facilitating passing of
functions as arguments to other functions.
✓ The use of pointer arrays two character strings result in saving of data space in
memory.
✓ Pointers allow C to support dynamic memory management.
✓ Pointers reduce length and complexity of programs.
✓ They also increase the execution speed.
Initialization of Pointers:
The process of assigning address of a variable is known as initialization.
Ex: int quantity;
int *p;
p=&quantity;
it can also be written as,
int *p=&quantity;
Pointer Flexibility:
A pointer can point more than one variable.
int x,y,z,*p;
And also, different pointers point to single variable.
int x;
int *p1= &x;
int *p2=&x;
int *p3=&x;
Accessing a variable through its Pointer:
To access the value of the variable, use unary operator ( * ).
It usually known as indirection operator.
Ex: int quantity,*p,n;
quantity= 150;
p=&quantity;
n=*p;
Chain of pointers:
It is possible to make a pointer to point to another pointer, creating chain of pointers.
Address2
Address1
Value
This is known as multiple indirections.
Ex: int **p2;
main()
{
int x,*p1,**p2;
x=100;
p1=&x;
p2=&p1;
printf(“%d”,**p2);
}
Pointer Expression:
Pointer can be used in expressions.
If p1 & p2 are pointers.
y = *p1 * *p2;
sum=sum+ *p1;
Relational operators are possible in two pointer variables.
Pointer increments and scale factor
p1=p2+2; p1++;
Pointers and Arrays:
When an array is declared, the compiler allocates a base address and sufficient amount of
storage to contain all the elements of the array in contiguous memory location
➢ Elements
x[0] x[1] x[2] x[3] x[4]
➢ Value
1 2 3 4 5
➢ Base Address
1000 1002 1004 1006 1008
➢ int *p;
p=x; is equivalent to p=&x[0];
Pointers and Character Arrays:
❖ char str[5]= “good”;
The compiler automatically inserts the null character „\0‟ at the end.
❖ char *str= ”good”;
This stores the address in the pointer variable.
g o o d „\0‟
str
Runtime Assignment for a string pointer:
char *string1;
string1= “good”;
printf(“%s”, string1);
puts(string1);
Array of Pointers:
➢ One important use of pointers is in handling of a table of strings.
➢ Ex: char name[3] [25];
➢ This means, the name is a table containing 3 names,each wit maximum length of 25
characters.
➢ Instead of making each row a fixed number of characters, we can make a pointer to
point it.
➢ Char *name[3] = { “India”, “ Australia”, “New Zealand”}; declares name to be an
array of 3 pointers to characters.
Pointers As Function Arguments:
The process of calling a function using pointers to pass the addresses of variables is
known as “Call by Reference”.
Ex: main()
{
int x;
x=20;
change(&x);
printf(“%d”, x);
}
change( int *p)
{
*p= *p + 10;
}
Functions returning Pointers:
A function can return a single (or) multiple values through pointer parameters.
Ex: int *larger(int *, int *);
main()
{
int a=10;
int b=20;
int *p;
p=larger ( &a, &b);
printf(“%d”, *p);
}
int *larger(int *x,int *y)
{
if ( *x > *y)
return (x);
else
return (y);
}
Pointers to Functions:
A pointer to a function is declared as follows;
type ( *fptr) ( );
- fptr is a pointer to a function that returns „type‟ value.
Pointers and Structures:
struct inventory
{
char name[20];
int number;
float price;
} product[2], *ptr;
ptr= product;
These assignment assigns the address of zeroth
element of product to ptr.
That is., pointer ptr will point to product[0].
Members can be addressed as, ptr
name;
ptr
number;
The arrow operator is known as member selection operator.
Troubles with pointers:
Assigning values to uninitialized pointers. int
*p, m=100;
*p=m; /*Error*/
Assigning value to a pointer variable. int
*p, m=100;
p=m; /*Error*/
Not dereferencing a pointer when required. int
*p, x=100;
p= &x;
printf(“%d”, p); /* Error */
Assigning the address of an uninitialized variable. int
m, *p;
p= &m; /* Error */
Comparing pointers that point to different objects. char
name1[20], name2[20];
char *p1= name1;
char *p2= name2;
if( p1 > p2) /* Error */
FILE MANAGEMENT
A file is a place on disk where group of data is stored.
Basic File Operation:
i. Naming a file.
ii. Opening a file.
iii. Reading data from a file.
iv. Writing data to a file.
v. Closing a file.
High Level I/O Functions:
1. fopen() – Creates a new file, opens an existing file.
2. fclose() – Closes a file which has been opened.
3. getc() – Reads a character from a file.
4. putc() – Writes a character to a file.
5. fprintf() – Writes s set of data values to a file.
6. fscanf() – Reads a set of data values from a file.
7. getw() – Reads an integer from a file.
8. putw() – Writes an integer to a file.
9. fseek() – Sets the position to a desired point in a file.
10. ftell() – Gives the current position in the file.
11. rewind() – Sets the position to the beginning of a file.
Defining and Opening a File:
General Format:
FILE *fp;
fp= fopen(“filename”, “mode”);
Ex:
FILE *fp;
fp = fopen(“fact”,”r”);
To define a file, we must specify; i) FILE NAME, ii) Data Structure, iii) Purpose.
Modes:
1. r – Open a file for reading only.
2. w – Open a file for writing only.
3. a – Open a file for appending.
Additional modes:
1. r+ -- existing file is open to the beginning for both reading and writing.
2. w+ -- same as w except both for reading and writing.
3. a+ -- same as a except both for reading and writing.
Closing a File:
General format: fclose(filepointer);
Ex: fclose(fp);
Input /Output Operations on Files:
i) getc & putc functions.
ii) getw & putw functions.
iii) fprintf and fscanf functions.
1. getc & putc functions:
getc
c=getc (fp1);
putc
putc(c,fp2);
2. getw & putw functions:
getw
getw(fp1);
putw
putw (integer, fp1);
3. fprintf & fscanf functions:
fprintf(fp, “control string”,list);
fscanf(fp, “control string”, list);
Ex: fprintf(f1, “%s%d”, name,age);
fscanf(f1, “%s%d”, name, &age);
Error Handling during I/O Operations:
1. Trying to read beyond the EOF mark.
2. Device overflow.
3. Trying to use a file that has not been opened.
4. Trying to perform an operation on a file when the file is opened for another type of
operation.
5. Opening a file with an invalid filename.
6. Attempting to write to a write-protected file.
Random Access to Files:
i) ftell()
it takes a file pointer & return a number that corresponds to current
position.
It takes the following form;
n=ftell(fp);
ii) rewind()
it takes a file pointer and resets the position to the start of the file.
iii) fseek()
it is used to move the file position to a desired location within the file.
It is of the form;
fseek(filepointer, offset, position);
filepointer – is a pointer to the file concerned.
offset – is an integer number.
position – is an integer number.
Position can take three values; 0- Beginning, 1- Current position, 2- End of File.
Command Line Arguments:
It is a parameter supplied to a program when the program is invoked. In C, main can take two
arguments called ‘argc’ and ‘argv’ and the information contained in the command line is passed
onto the program, through these arguments when the main is called.
Format is;
main(int argc, char argv[])
{
……………………..
……………………..
……………………..
}
argc – it is an argument counter that counts the number of arguments in the command line.
argv – it is a vector that represents an array of character pointers that point to command
line arguments.