134 16sccit2-16sccca1-16scccs1 2020052409511199
134 16sccit2-16sccca1-16scccs1 2020052409511199
Objective:
To impart basic knowledge of Programming Skills in C language.
Unit I
Introduction to C – Constants, Variables, Data types – Operator and Expressions.
Unit II
Managing Input and Output operations – Decision Making and Branching –
Decision making and Looping.
Unit III
Arrays – Character Arrays and Strings – User defined Functions.
Unit IV
Structures and unions – Pointers – File management in C.
Unit V
Dynamic memory allocation – Linked lists- Preprocessors – Programming Guide
lines.
Text Book:
1. Balagurusamy E .,Programming in ANSI C , Sixth Edition, McGraw-Hill, 2012
Reference Book:
1. R.S.Bichkar, Programming with C, University Press, 2012
*****
UNIT – I
(Introduction to C – Constants, Variables, Datatypes – Operators and Expressions.)
INTRODUCTION TO C
C is one of the most popular computer languages. It is an outgrowth of earlier
languages called ALGOL , BCPL ( Basic Combined programming language) and B. C language was
developed by Dennis Ritchie at Bell Lab in 1972. UNIX operating system was coded almost entirely in C.
IMPORTANCE OF C:
1. It is a Robust language i.e its built -in functions and operators can be used to write any complex
programs.
2. It is well suited for writing both system software and business packages.
3. Programs written in C are efficient and fast because it has variety of data types and powerful
operators.
4. There are only 32 keywords and its strength lies in built-in – functions.
5. C is highly portable. C programs written for one computer can be run on another with little or no
modification.
6. C is well suited for structured programming.
7. C has ability to extend itself.
1
BASIC STRUCTURE OF C PROGRAM:
Documentation Section
Link Section
Definition Section
Global Definition Section
main() function Section
{
Declaration Part
Executable Part
}
Sub – Program Section
Function - 1
:
:
Function - n
Documentation Section: It consists of comment lines giving the name of the program, the author etc.
Link Section: It provides instructions to the compiler to link functions from the systems library.
Eg:- #include <stdio.h> , #include<math.h> , #include<stdlib.h> .
Definition Section: It defines all symbolic constants. Eg:- #define
Global Variable Declaration Section: There are some variables that are used in more than one function.Such
variables are called global variables declared in this section i.e. outside of all functions.
main() function section: Every c program must have one and only one main() section.It consists of two
parts. i)Declaration part: Declares all the variables that are used in the executable part. ii) Executable
part: This contains all the executable statements. These two parts must appear between {}. All statements in
the declaration and executable parts end with a semicolon.
Subprogram Section: It contains all the user defined functions that are called in the main function.
Let us explain the above structure using example.
/* printing a message */
#include<stdio.h>
main()
{
/*….. Printing begins …….*/
printf(“I See”);
/*….. Printing ends …….*/
2
}
main : It is a special function used by C to tell the computer where the program start.Every
program must have exactly one main function
() : the empty pair of parenthesis indicates that the function main has no arguments.
{} : The opening and closing braces marks the beginning and end of the main function. All the
statements between these two braces form the function body. It contains a set of instruction
to perform the given task.
In the above program, function body contains 3 statements. Where,
i) printf is an executable statement. It is predefined i.e it is already written and compiled and
linked with our program at the time of linking.
ii) The printf function causes everything between the starting and the ending quotation marks to
be printed out.
iii) Every statement in C must end with semicolon ( ; ).
/* ….. */ : comment lines. These are not executable. It is for understanding.
Letters (A – Z , a-z )
Digits ( 0…9 )
Special Characters ( , . ; ? ‘ ! “ / \ | ~ _ + = { } [] % >
< & ^)
White Spaces.
C Tokens: In C program the smallest individual units are called tokens. There are 6 tokens.
Keywords (34 ) - float,while,do, case, if, goto…
Identifiers - sum, num, value
C tokens Constants - 100 , 15.5
Strings - “ABC” , “year”
Operators - + % /*-
Special Symbols - {} [] -->
Keywords and Identifiers:
3
All keywords have fixed meaning and these meanings cannot be changed. It serves as the basic
building blocks for program statement. The following words are reserved for use of Keywords. We must
not use them as variables or identifiers.
Eg/- if, for, goto, else, auto, break,while, void, int, double, float, char, const, do …
Identifiers refer to the names of variables, functions and arrays. These are user-defined names.
The rules for identifiers are,
1. First character must be an alphabet.
2. Must consist of only letters, digits or underscore.
3. Cannot use a keyword.
4. Must not contain white space.
CONSTANTS:
Constants in C refer to fixed values that do not change during the execution of a program.
Constants
Numeric Character
constants constants
Single
Integer String
Real constants character
constants Constants
constants
I. Integer Constants: An integer constant refers to a sequence of digits. They do not have decimal
points. There are 3 types of integers.
a. Decimal Integer Constant: It can consist of any combination of digits taken from the set 0
through 9. Spaces, commas and non- digit characters are not permitted between digits.
Eg:- 0 743 -321 +76
b. Octal Integer Constant: It consists of digits taken from 0 through 7. The first digit must be
0. Eg:- 0743 037 0
c. Hexadecimal Integer Constant: It must begin with either 0x or 0X . It can be followed by
combination of digits from 0 through 9 and A through F. Eg:- 0x 0x1
0x7FF 0xabcd
II. Real constants or Floating Point constants: Floating Point constants are decimal notation,
having a whole number followed by a decimal point and the fractional part.
Eg:- 0.008 -0.75
A real number may also be expressed in exponential or Scientific notation.
Eg:- 215.65 may be written as 2.1565e2 in exponential notation. e2 means
multiply by 102 .
The general form is :
mantissa e exponent
The mantissa is either a real number or an integer. The exponent is an integer number.
Eg:- 7500000000 =7.5e9 or 75e8
4
III. Single Character Constants: One character surrounded by single quotes denotes a character
constant. Eg:- ‘A’ ‘5’ ‘x’ ‘;’ ‘?’
Character constants have integer values known as ASCII values.
Eg:- printf(“%d” , ‘a’); = printf(“%d” , ‘97’);
IV. String Constants: A String constant is sequence of characters enclosed in double quotes. The
characters may be letters, numbers,special characters and blank space.
Eg:- “Hello” “1979” “well done” “ ?....!” “x”
Backslash Character constants: ( Escape Sequences)
These constants are used in output function.
‘\n’ newline ‘\\’ backslash
‘\t’ horizontal tab ‘\’’ single quote
‘\b’ backspace ‘\0’ null character
‘\r’ carriage return ‘\”’ double quote
‘\f’ form feed
VARIABLES:
A variable is a data name that may be used to store data value.Unlike constants that remain unchanged
during the execution of the program, a variable may take different values at different times during execution. A
variable can be of letters, digits and underscore subject to the following conditions.
1. They must begin with a letter or an underscore.
2. The maximum length of the variable name can be 31 characters. But length should not exceed 8
characters because only first 8 characters are treated as significant.
3. Uppercase and lowercase are significant.
4. It should not be a keyword.
5. White space is not allowed between characters.
Eg:- for valid variables: value , T_raise, x1 , ph_value
Eg:- for invalid variables: 123 (area) % 25th
Types of variables:
Depending upon the data contained in the memory location, the variables are classified as follows.
Integer Variables
Long interger
Short integer
Unsigned interger
Integer
Real Variables
Floating point
5
Double
Character Variables
Signed character
Unsigned character
String Variable
A variable which may have only integer values is called integer variable, that has real values is called real variable,
that has character data is called character variable and that has string data is called string variable.
Variable type declaration:
It is compulsory that at the beginning of the program the variable type must be declared. After
designing a suitable variable name, we must declare them to the compiler.
Declaration does two things;
i) It tells the computer what the variable name is.
ii) It specifies what type of data the variable will hold.
The declaration of the variable must be done before they are used in the program.
Syntax: datatype list of variables;
A) Integer Variable:
The word int is used to store integer values.
Eg:- int i , sum , area;
short int i, sum, area;
long int sum;
According to the size of the numbers we can declare it as short or long etc.
B) Real Variable:
The word float and double is used to determine real variable. Double has more precision.
Eg:- float side, circum;
double side, cir;
long float side;
double and long float have the same effect.But double is used widely.
C) Character Variable:
The word char is used to declare character data.
Eg:- char a, b;
char text;
D)String Variable:
A string is stored as an array of character . Suppose we want to store “PEPSI” to the variable drink , it
is done in the following manner.
drink[0] = ‘P’
drink[1] = ‘E’
drink[2] = ‘P’
drink[3] = ‘S’
drink[4] = ‘I’
drink = P E P S I \0
a[0] a[1] a[2] a[3] a[4] a[5]
* multiplication
/ division
Integer Arithmetic: When both the operands in an arithmetic expression is an integer, the expression is
called integer expression and the operation is called integer arithmetic. Integer arithmetic always yields
an integer value.
Eg:- if a=14 and b=4
a-b=10 a+b=18 a*b=56 a/b=3 a%b=2
Real Arithmetic: An arithmetic operation involving only real operands is called real arithmetic. A real
operands may assume values either in decimal or exponential notation.
Eg:- a-b=10.5 a+b=18.2 a*b=25.0 a/b=3.2
The operator % cannot be used with real operands.
Mixed mode Arithmetic: When one of the operands is real and the other is integer, the expression is
called mixed mode arithmetic expression. If either operand is of real type, then only real operation is
performed and the result is always a real number.
Eg:- 15/10.0 = 1.5
15/10 = 1
Relational Operators:
Comparisons can be done with the help of relational operators. The values of relational expressions is either
0 or 1 . It is 1 if the specified relation is true and 0 if the relation is false. The following are the 6 relational
operators.
< less than
<= less than or equal to
> Greater than
>= Greater than or equal to
== is equal to
!= not equal to
Eg:- 10 < 20 is true
20 < 10 is false
Logical Operators:
Logical AND: A compound expression is true when two conditions (expressions) are true.
` Exp1 && Exp2
The two expressions must be an integer type.
Situation Results
True && True True
True && False False
False &&False False
False && True False
Eg:- a=4 ; b=5 ; c=6
(a < b ) && ( b < c )
( 4 < 5) && ( 5 < 6 )
True && True
True
Situation Results
True | | True True
True | | False True
False | | False False
False | | True True
Operators Meaning
& Bitwise AND
| Bitwise OR
^ Bitwise exclusive OR
<< Shift left
>> Shift right
Special Operators:
There are special operators in C to performs particular type of operations.
A. Unary Operators:.They precede their single operands.
Operators Meaning
* Contents of the storage field
to which a pointer is pointing
& Address of a variable
Typeof Forced type conversion
B. Comma Operator:
C uses comma in two ways. The first uses comma as a separator in the variable declaration. Eg:-
int a,b,c;
UNIT – II
(Managing input and output operations –Decision making and branching –Decision making and looping.)
Code Meaning
%c Read a single character
%d Read a decimal integer
%i Read a decimal integer
Code Meaning
%c a single character
%d Decimal notation
%i Decimal notation
%e Decimal floating point
%f “
%g “
%o Octal
%s String of characters
%u Unsigned decimal
%x Hexadecimal
%% Print a percent sign
C language possess such decision making capabilities by supporting the following statements.
i. if statements
ii. switch statement
iii. Conditional operator
iv. goto statement
The if statement is a powerful decision making statement and is used to control the flow of execution of
statements. It is usually a two-way decision statement and is used in conjunction with an expression. It allows
the computer to evaluate the expression first and then depending on the value of the expression ( relation or
condition) is true or false, it transfers the control to a particular statement.
True
The program has 2 paths to follow, one for true condition and the other for false condition.
The statement block may be a single statement or a group of statements. If the test expression is
true, the statement- block will be executed, otherwise the statement-block will be skipped and the
false
Statement-x
If the test expression is true , then the true –block statement , immediately following the if statements
are executed; otherwise, the false block statements are executed, In either case, either true block or false
block will be executed, not both. In both the cases , the control is transferred subsequently to the
statement-x.
Next Statement
#include<stdio.h>
main()
{
float x,y;
printf(“Enter 2 values\n”);
scanf(“%f%f”,&x,&y);
if(x>y)
{
printf(“Largest Value is=%f\n’,x);
}
else
{
printf(“Largest Value is=%f\n’,y);
}
}
Syntax:
if (test condition -1)
{
if (test condition -2)
{
statement 1;
}
else
If the condition 1 is false, the statement-3 will be executed; otherwise it continues to perform the second task. If
the condition2 is true, then statement-1 will be evaluated; otherwise statement-2 will be evaluated and then the control is
transferred to statement-x.
Flow Chart:
Test
cond 1
Test
cond 2
Next Statement
Next Statement
#include<stdio.h>
main()
{
float x,y,z;
printf(“Enter 3 values\n”);
scanf(“%f%f%f”,&x,&y,&z);
if(x>y)
{
if (x>z)
printf(“Largest Value is=%f\n’,x);
else
printf(“Largest Value is=%f\n’,z);
}
else
{
if( y>z)
printf( “largest value is=%f\n”,y);
else
printf( “largest value is=%f\n”,z);
}
}
4. The elseif ladder:
When multipath decisions are involved we can put all ifs together.A multipath decision is a
chain of ifs in which the statement associated with each else is an if.
Syntax:
if ( condition -1)
statement 1;
elseif ( condition -2)
statement-2 ;
elseif ( condition -3)
statement-3;
elseif ( condition -n)
statement-n;
else
default –Statement;
statement-x;
The conditions are evaluated from top to down. As soon as a true condition is found, the statement
associated with it is executed and the control is transferred to the statement-x. When all the n conditions become false,
then the final else containing the default-statement will be executed.
Example: /* Program to display name of the day depending upon the number entered from the keyboard*/
#include<stdio.h>
main()
{
int day;
printf(“Enter numbers between 1 to 7 \n”);
scanf(“%d”,&day);
if ( day==1)
printf(“Monday \n”);
if ( day==2)
printf(“Tuesday \n”);
if ( day==3)
printf(“Wednesday \n”);
if ( day==4)
printf(“Thursday \n”);
if ( day==5)
printf(“Friday \n”);
if ( day==6)
printf(“Saturday \n”);
if ( day==7)
printf(“Sunday \n”);
else
printf(“Enter the correct number \n”);
}
The expression is an integer expression or character. Value-1, value-2.. are constants or constant expressions and
are known as case labels. Each of these values should be unique within switch statement. Block-1, block-2 … are statement
lists and may contain zero or more statements.There is no need to put braces around these blocks. Case labels end with a
colon( : ).
When the switch is executed, the value of the expression is successfully compared against the values value-1,
value-2..If a case is found whose value matches with the value of the expression, then the block of statements that follows
the case are executed.
The break statement at the end of each block signals the end of a particular case and causes an exit from the
switch statement, transferring the control to the statement-x following the switch.
The default is an optional case. When present, it will be executed if the value of the expression does not match
with any of the case values. If not present, no action takes place if all matches fail and the control goes to the statement –
x.
false
Body of the loop
Test
condit
ion
In the entry controlled loop, the control conditions are tested before the start of the loop
execution. If the conditions are not satisfied, the body of the loop will not be executed.
In exit- controlled loop the test is performed at the end of the body of the loop and therefore the
body is executed unconditionally for the first time.
The entry and exit controlled loops are also called as pre-test and post-test loops.
A looping process should include the following four steps:
1. Setting and initialization of a condition variable.
2. Execution of the statements 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.
C language provides three constructs for performing loop operations. They are:
1. The while statement
2. The do statement
3. The for statement
A. The while statement:
The basic format of the while statement is
while(test condition)
{
Body of the loop
}
The while is an entry controlled loop statement. The test condition is evaluated and if the condition is
true , then the body of the loop is executed. After execution of the body, the test condition is once again
evaluated and if it is true, the body is once again executed. This process of repeated execution of the
body continues until the test condition finally becomes false and the control is transferred out of the
loop.
Eg:-// program to find sum of first 100 natural numbers 1+2+…100
main()
{
int sum, digit;
sum=0;
B. Do – while loop:
Do-while is an exit-controlled loop statement. On reaching the do – statement , the program
proceeds to evaluate the body of the loop first. At the end of the loop , the test condition in the while
statement is evaluated. If the condition is true, the program continues to evaluate the body of the loop
once again. This process continues as long as the condition is true. When the condition becomes false,
the loop will be terminated and the control goes to the statement that appears immediately after the
while statement.
This takes the form:
do
{
Body of the loop
}
while(test condition);
Eg:- // displays odd numbers from 1 to 100
main()
{
int x=1;
do
{
printf(“%d”,x);
x=x+2;
}
while(x<=100);
}
C. The for statement:
The for loop is an entry-controlled loop.
The general form is:
for(initialization ; test condition ; increment)
{
Body of the loop
}
C programming allows to use one loop inside another loop. The nesting may continue upto any desired
level.
Syntax:
The following program uses a nested for loop to find the prime numbers from 2 to 100 −
#include <stdio.h>
int main () {
return 0;
}
Eg:- main()
{
int 1,value;
i=0;
while(i<=10)
{
printf(“enter a number”);
scanf(“%d”,&value);
if(value<= 0)
{
printf(“Zero or negative value found”);
break;
Exit }
from i++;
loop
The above program segment will process only the positive integers, whenever zero or negative value is
found , the computer will display the message Zero or negative value found as an error and it does not
repeat the loop further.
Eg:- // using break in do-while
main()
{
int 1,value;
i=0;
do
{
printf(“enter a number”);
scanf(“%d”,&value);
if(value<= 0)
{
printf(“Zero or negative value found”);
break;
Exit }
from i++;
loop }
while(i<=10);
}
main()
{
int 1,value;
i=0;
for( i=0;i<=10;i++){
printf(“enter a number”);
scanf(“%d”,&value);
if(value<= 0){
printf(“Zero or negative value found”);
continue;}}}
The above program will process only the positive integers, whenever the zero or negative value is found,
the computer will display the message Zero or negative value found as an error and it continues the
same loop as the given condition is satisfied.
UNIT – III
(Arrays- Character Arrays and Strings –User defined functions.)
ARRAYS
An array is a sequential collection of related data items which are stored in consecutive memory
locations that share a common name. In other words an array is a group or table of values referred by the same
variable name.The individual values in an array are called elements.
Arrays are sets of values of the same type,which have a single name followed by an index. In C , square brackets
appear around the index right after the name. Eg:- salary[10].
Declaring the name and type of an array and setting the number of elements in the array is known as
dimensioning the array.
Depending upon the number of subscripts in the array, arrays can be classified into
i. One-dimensional arrays
ii. Two-dimensional arrays
iii. Multi-dimensional arrays
One-dimensional Arrays:
A list of items can be given one variable name using only one subscript and such a variable is called a
single-subscripted variable or a one dimensional-array.
An array must be declared before it ish used.
Syntax:- data_type array_name[size];
The data type specifies the type of the element, whether int,float or char. The size indicates the maximum
number of elements that can be stored inside the array.It should be positive integer.
Eg:- int group[5];
group is an array which contains 5 integer constants.The computer reserves 5 storage locations as shown below.
group[0]
group[1]
group[2]
group[3]
group[4]
The first element in the array is numbered 0, so the last element is 1 less than the size of the array i.e for
5 it is 0,1,2,3 and 4.
After an array is declared , its elements must be initialized. Array can be initialized either at two stages :
a) At compile time b) At run time.
At compile time:
Syntax: data_type array_name[size] ={ list of values};
The values in the list are separated by commas.
Eg:- int group[5] = {20,30,40,10,50};
20 group[0]
30 group[1]
If the number of values is less than the number of elements, then only that many number are initialized. The
remaining elements will be set to zero automatically.
Sometime the size may be omitted , in such cases, the compiler allocates enough space for all initialized
elements.
E.g:- int counter[]={2,4,1,0};
This would declare counter array to contain four elements with initial value 1.
At run time:
For large arrays e.g. for(i=0;i<100;i++)
{
if(i<50)
sum[i]=0;
else
sum[i]=1.0;
}
The first 50 elements of the array sum is initialized to zero while the remaining 50 elements are initialized to
one at run time.
scanf (“%d%d%d”,&x[0],&x[1],&x[2]);
This will initialize array elements with the values entered through the keyboard.
2. main()
{
int a[100];
int i,n;
printf(“how many numbers are in the array? :”);
Two-dimensional array:
When a table of values are to be stored, two-dimensional arrays are used. A two-dimensional will
require two pairs of square brackets.
Syntax:- data_type array_name[row-size][column-size];
Eg:- int x[2][2];
It is stored in memory as follows:
Column Column
0 1
Row 1 [0][0] [0][1]
Row 2 [1][0] [1][1]
Two-dimensional arrays may be initialized by following their declaration with a list of initial values enclosed in
braces. The initialization is done row by row.
2. main()
{
int a[50];
int i,j,n,m;
printf(“Enter how many rows and cols in the array?”);
scanf(“%d%d”,&n,&m);
printf(“Enter the elements”);
for(i=0;i<=n-1;i++)
{
for(j=0;j<=m-1;j++)
{
scanf(“%d”,&a[i][j]);
}
}
printf(“contents of the array\n”);
for(i=0;i<=n-1;i++)
{
for(j=0;j<=m-1;j++)
{
printf(“%d”,&a[i][j]);
}
printf(“\n”]);
}}
I. strcat () function:
The strcat function joins two strings together.
Syntax: strcat( string1, string2);
Strign1 and string2 are character arrays.When the function strcat is executed, string2 is appended
to string1.It does so by removing the null character at the end of string1 and placing string2 from there.
Eg:- 0 1 2 3 4 5 6 7 8 9
part1 = V E R Y \0
0 1 2 3 4 5 6 7 8 9
part2= G O O D \0
0 1 2 3 4 5 6 7 8 9
part1 = V E R Y G O O D \0
0 1 2 3 4 5 6 7 8 9
part2= G O O D \0
We must make sure that the size of the string2( to which string2 is appended) is large enough to
accommodate the final string.
strcat may also append a string constant to a string variable.
Eg:- strcat( part1,”hello”);
C permits nesting of string functions. Eg:- strcat(strcat(str1,str2),str3);
II. strcmp() function:
The strcmp function compares two strings identified by the arguments and has a value 0 if they
are equal.If they are not, it has the numeric difference between the first non-matching characters in the
strings.
Syntax:
strcmp(string1,string2);
string1 and string2 may be string variables or string constants.
Eg:- strcmp(name1,name2);
strcmp(name1,”john”);
strcmp(“RAM”,ROM”);
The actual parameters must match the functions parameter in type,order and number.
Function Declaration: (or) Function Prototype :
All functions in a C program must be declared before they are called.
Syntax:
Function_type function_name(Parameter list);
Eg:- int mul(int m, int n);
temp = square(i);
printf(“%d\t%d\n”,i,temp);
}
square(int n);
{
int value;
value = n * n;
return(value);
}
ACTUAL AND FORMAL ARGUMENTS:
Sometimes a function may be called by a portion of a program with some parameters and these
parameters are known as actual arguments.
The formal arguments are those parameters present in a function definition. It is also called as
dummy arguments or parametric variables.
Eg: main()
{
RECURSION:
The function which calls itself directly or indirectly again and again is known as the recursive
function. There is much difference between the normal function and the recursive function. The normal
function will be called by the main function whenever the function name is used. On the other hand the
recursive function will be called by itself directly or indirectly as long as the given condition is satisfied.
Eg:- main()
{
int a,fact;
printf(“Enter a number”);
scanf(“%d”, &a);
fact = rec (a);
printf(“Factorial =%d”,fact);
}
rec ( int x)
{
int f;
if (x = =1)
return;
else
f=x*rec(x-1);
return f;
}
UNIT-IV
(Structures and Unions – Pointers – File Management in c.)
POINTERS
Definition:
A pointer is a variable which holds the address of another variable. The Pointer is a powerful
technique to access the data by indirect reference because it holds the address of that variable where it has been
stored in the memory.
1) p1=&x;
The memory address of x is assigned to a pointer variable p1.
2) y=*p1;
The contents or value of the pointer variable *p1 is assigned to the variable y, not the memory address.
3) p1=&x;
p2=p1; /* address of p1 is assigned to p2 */
The address of p1 is assigned to pointer variable p2. The contents of both p1 and p2 will be same.
Eg/-
#include <stdio.h>
main()
{
int x=10;
int *ptr;
ptr=&x;
printf(“ Address of x=%u”,&x);
Printf(“Address of x=%u”,ptr);
Printf(“Address of ptr=%u”,&ptr);
Printf(“Address of ptr=%u”,ptr);
Printf(“Address of x=%d”,x);
Printf(“Address of x=%d”,*(&x));
Printf(“Address of x=%d”,*ptr);
}
o/p:
Address of x=6485
Address of x=6485
Address of ptr=5276
Address of ptr=6485
Address of x=10
Address of x=10
Address of x=10
Pointer Arithmetic:
Some arithmetic operation can be performed with pointers. The C language four arithmetic operators
that may be used with pointers such as,
addition +
subtraction –
incrementation ++
decrementation –
C allows to add integers to or subtract integer from pointers,as well as to subtract one pointer from another
p1+4, p2=2 and p1=p2 are valid but p1+p2 is illegal because no two pointers can be added
.Pointers can be compared using relational operator.
p1>p2,p1==p2 and p1!=p2 are valid.
The following pointers variables can be used in expression. If p1 and p2 are properly declared and initialized,
then the following statement are valid.
y=*p1 X *p2;
sum=sum+*p1;
Z=5* - *p2/*p1; // (5*(-(*p2)))/(*p)
In case of pointer incrementation.
Eg/-
int value,*p1;
value=100;
P1=&value;
P1++;
o/p:
Contents of the array,
Value =11
Value=12
Value=13
STRUCTURES:
C supports a constructed data type known as structures. Structure consist of a group of variable of
different datatypes placed in a common name. A structure is a heterogeneous datatype where as an array is a
homogeneous data type.
Defining a structure:
The format of a structure must be defined first.
Syntax:
struct tag_name
{
datatype member1;
datatype member2;
……
};
Here, struct is a keyword and it declares a structure to hold different data fields.Each field is called a structure
element or member. Each member may belong to different data types. The tag_name is the name of the
structure and is called structure tag. The tag_name is used for declaring variables. The template should end with
a semicolon.
Eg:-
struct book_bank
{
char title[20];
char author[15];
int pages;
float price;
};
book_bank is the name of the structure. It holds four data fields namely title,author,pages and price. Each of the
members belong to different type of data.
Declaring Structure variables:
The above definition has not declared variables. We can declare structure variables like any other
variable. Declaring includes
i. The keyword struct
Structure Initialization:
Like any other variable structure be can also be initialized.
At Compile time:
main()
{
struct st_record
{
int weight;
int height;
};
struct st_record s1={50,70,80);
struct st_record s2={55,75,85);
……
}
We can also initialize a structure variable outside the function.
struct st_record
{
int weight;
int height;
};
main()
{
struct st_record s1={50,70,80);
struct st_record s2={55,75,85);
……
}
We can also assign values as follows.
At Run time:
We can also use scanf to give values through keyboard at runtime.
Eg:- scanf(“%s%d”,s1.name, &s1.weight);
Example:
struct person
{
char name[20];
int day;
char month[10];
int year;
float salary;
};
main ( )
{
struct person p;
printf(“Input values”);
scanf(“%s%d%s%d%f ” , p.name, &p.day, p.month, &p.year, &p. salary);
printf(“%s%d%s%d%f ” , p.name, &p.day, p.month, &p.year, &p. salary);
}
Copying and Comparing Structure Variables:
Two variables of the same structure types can be copied the same way as the ordinary variables.
For example , if b1 and b2 belong to the same structure then
b1 = b2;
b2 = b1; are valid statements.
C does not permit any logical operations on structure variables.
b1!=b2;
b2==b1 are invalid.
We can compare them only by comparing the members individually.
b1.author==b2.author
Arrays of Structures:
Similar type of structures placed in a common heading or a common variable name is called an
array of structures.
Eg:- struct book
{
char name[10];
int pages;
float price;
} b[100];
In the above example b is an array of 100 elements b[0] …..b[99]. Each element is defined to be of type
struct book.
Eg:- struct book
{
char name[10];
int pages;
float price;
ii. The second method involves passing a copy of the entire structure to the called function.
eg:
UNIONS
Union is a variable which is similar to the structure. It contains a number of members like structure
but it holds only one object at a time. In the structure each member has its own memory location, whereas
members of union have same memory locations.The union requires bytes that are equal to the number of
bytes required for the largest members. For example, if the union contains char, int and longint then the
number of bytes reserved in the memory for the union is 4 bytes.
eg:
main()
{
union result
{
int marks; char grade;
};
struct res
{
char name[15]; int age;
union result perf;
}data;
printf(“size of union:%d\n”, sizeof(data.perf)); printf(“size of structure:%d\n”, sizeof(data));
}
O/P:
size of union: 2 size of structure: 19
i. fopen()-creates a new file for use and opens an existing file for use.
ii. fcloseQ-closes a file which has been opened for use.
iii. getc()-reads a character from a file.
iv. putc()-writes a character to a file.
v. getw()-reads a integer from a file.
vi. putw()-writes an integer to a file.
vii. fprintf()-writes a set of data values to a file.
viii. scanf()-reads a set of data values from a file.
ix. fseek()-sets the position to a desired point in the file.
x. ftell()-gives the current position in the file.
xi. rewind()-sets the position to the beginning of the file.
Defining and opening a file:
If we want to store data in a file,we have to specify the
• filename
• data structure and
• purpose
Filename:
It is a stimg of characters.lt contains two parts
i. a primary name
ii. an optional period with the extension.
Data structure:
Data structure of a file is FILE. All files should be declared as type FILE before they are used.
Purpose:
When we open a file,we must specify whether to read or write a file.
fclose(pl);
fclose(p2);
This statement would read a character from the file whose file pointer is fp2.
Example:
N.Raajarajeswari, Dept of IT Page 50
# include<stdio.h> mainQ
{
FILE*fl; char c;
printf("Data Input\n");
fl =fopen("Input","w");
while((c=getchar())!=EOF)
putc(c,fl);
fclose(fl);
printf("Data OutputVn");
fl=fopen("Input","r");
wh i le((c=getc(f 1)) !=EOF)
printf("%c",c);
fclose(fl); »
}
Output:
Data Input
This is an example to demonstrate file handling in C.
Data Output
This is an example to demonstrate file handling in C.
ii. The getw and putw functions:
The getw and putw are integer oriented functions.lt is used to read and write integer values.
The general forms are
putw(integer,fp);
getw(fp);
fseek():
This function is used to move the file position to a desired location within the file.
fseek(file_ptr,offset,position);
i. file_ptr is the file pointer to the file concerned.
ii. offest is a number/variables of type long,it specifies the number of position (bytes) to be moved
from the location specified by position.
iii. position can take one of the following 3 values.
0 - beginning of file
1 - current position
2 - end of file
iv. if offset is positive then moves forward and if negative moves backward
v. operations on fseek function:
i. fseek(fp,ol,0); - go to the begining
ii. fseek(fp,ol,l); - stay at current position
iii. fseek(fp,ol,2); - go to the end of the file
Example:
# include<stdio.h>
main(int argc,char*argv[])
{
FILE* fs,* ft;
char ch;
if(argc!=3)
{
puts("Insufficient arguments");
exit();
}
fs=fopen(argv[l],"r");
if(fs==NULL)
{
UNIT-V
(Dynamic memory allocation – Linked lists- preprocessors-programming guidelines.)
Ptr is a pointer of type cast-type. The malloc returns a pointer to an area of memory with size byte-size.
Example: X=(int *) malloc ( 100 x sizeof(int));
A memory space equivalent to 100 times the size of an int bytes is reserved and the address of the first byte
of the memory all ocated is assigned to the pointer X of type int.
LINKED LISTS:
List is a set of items organized sequentially.Eg:-Arrays. In arrays we use the index for accessing and
manipulation of array elements. But the major problem with the arrays is that , the size of the array must
be specified precisely at the beginning.
Linked list is a dynamic data structure. Each item in the list is a part of a structure and also contains
a “link” to the structure containing the next item. This type of list is called a linked list because it is a list
whose order is given by links from one item to the next.
Each structure of the list is called a node and consists of two fields, one containing the item
and the other containing the address of the next item in the list.
Example:
35.50 Node1.age
Xxx Node1.next
49.00 Node2.age
0 Node2.next
Example: struct link_list
{
float age;
struct link_list *next;
};
struct link_list node1, node2;
node1.next = &node2;
node1.age=35.50;
node2.age=49.00;
node2.next=0;
Advantages of Linked List:
1. Linked Lists can grow or shrink in size during the execution of a program.
2. It does not waste memory space.
3. It provides flexibility by allowing the items to be rearranged efficiently.
4. It is easier to insert or delete items by rearranging the links
A B C 0