Ecs C - Prog Material
Ecs C - Prog Material
SYLLABUS
Unit-I
Unit-II
Unit-III
Unit-IV
Unit-V
Files: Streams and file types, Steps for file operation, File I/O,
Structures read and write, other file functions, Command line
arguments, I/O redirection
DEPARTMENT OF ELECTRONICS AND COMMUNICATION
SYSTEM
STUDY MATERIAL
Unit-I
Introduction to C programming - Structure of a C program – C character
set – Delimiters – Keywords – identifiers – Constants – variables – rules
for defining Variables – data types – Declaring and initializing variables
– type Conversion. Operators and expressions
Introduction to C programming
C was an offspring of ‘Basic Combined Programming
Language’(bcpl) called B, developed in the 1960’s at Cambridge
university. B language was modified by Dennis Ritchie and was
implemented at Bell Laboratories in 1972.The new language was
named as C. since it was developed along with UNIX operating
system, it is strongly associated with UNIX. It can run under
various operating systems including MSDOS.
Importance of C:
1. It is robust language.
2. Rich set of built-in functions and operators are available.
3. Easy to create complex programs.
4. Suitable to write both application software as well as system
software.
5. It is highly portable. Because C programs written for one
computer
can be run on another with little or no modification.
6. It is well suited for structured programming. So that it is easy to
debug,
test and maintain a module.
7. It can extend itself.
Documentation section
link section
Definition section
Global declaration section
Main( ) function section
{
declaration part
executable part
Subprogram section
function 1
function 2
function 3
.
.
function n
c) Function main ( ):
Every program in C must contain main ( ) function. Empty
parenthesis after main is necessary. The function main ( ) is a starting
point of every C program. The execution of the program always begins
with the function main ( ).
d) Declaration Part:
It declares the entire variables that are used in the
executable part. Initializations of variables are also done in this
section. Initialization means providing initial value to the variables.
e) Executable Part:
This part contains the statement following the declarations
of the variables. This part contains a set of statements or a single
statement. These statements are enclosed between braces.
f) User-defined function:
The functions defined by the user are called user-defined
functions. These functions are generally defined after the main ( )
function. They can be also be defined before main ( ) function. This
portion is not compulsory.
g) Comments:
It is not compulsory in a program. However to understand
the flow of a program, the programmer can include comments in the
program. Comments can be inserted by the programmer. These are
useful for documentation. The clarity of the program can be followed if
it is properly documented.
Example
/ * This is a single comment * /
/ * This is an example of / * nested comments * / * /
/ * This is an example of
comments with multiple lines * / / * It can be nested * /
C Character Set
The characters are used to form words, numbers and
expressions depending upon the computer on which the program runs.
The characters in C are classified into the following characteristics.
1. Letters 2. Digits 3. White Spaces 4. Special characters.
Character Set
Identifiers:
Identifiers are names of variables, functions and arrays. They
are user-defined names, consisting of sequence of letters and digits,
with the letter as the first character. Lower case letters are preferred.
However, the upper case letters also permitted. The underscore ( _ )
symbol can be used as an identifier.
Example: 1. #define N 10
2. #define a 15
Here “N” and “a” are user-defined identifiers.
Constants:
The constants in C are applicable to the values that do not
change during the execution of a program. There are several types of
constants in C. They are classified as follows.
A. Numerical constants:
1) Integer constants:
It refers to a sequence of digits from 0 to 9 without decimal
points or fractional part or other symbols. It requires minimum two
bytes and maximum 4 bytes. Integer constants can either be
positive, negative or maybe zero. The number without a sign is
assumed as positive.
Example: 10, 20, +30, -15
2) Real constants:
The numbers with fractional part is called real or floating-point
constants. Many parameters or quantities are defined not only in
integers but also in real numbers.
Example: 1) 54.98
2) 25.75
B. Character constants:
1. Single character constants:
A character constant is a single character. They are also
represented with a single digit or a single special symbol or white
space enclosed within a pair of single quote marks.
Examples: 1) ‘a’
2) ’#’
3) ’2’
4) ’ ’
2. String Constants:
They are a sequence of characters enclosed within a double
quote marks. The string may be a combination of all kinds of
symbols.
Example: “ Hello”, “India”, “444”, “a”.
Variables:
A variable is a data name that may be used to hold a data
value. A variable may take different values at different times
during the program execution.
3. Arrays
An array is a collection of elements of similar data types in
which each element is located in separate memory location.
Eg. int b[4];
Variables:
A variable is a data name that may be used to hold a data
value. A variable may take different values at different times
during the program execution.
Rules for forming a variable:
1.The starting character should be a letter.
2.The maximum number of characters may be 8 characters. it
differs
3.Upper and lower case are significant. Example: TOTAL is not
same as total or Total.
4.The variable should not be a keyword.
5.White space is not allowed.
6.Special characters except _(underscore) symbol is not
allowed.
Valid examples:
1. john
2. value
3. tot_amt
4. a1
Data types:
1. Primary data types.
2. User- defined data type
3. Derived data type
4. empty data set
b. Character
i. signed char 8 bits
ii. unsigned char 8 bits
2. Floating-point type
i. float 32 bits
ii. double 64 bits
iii. long double 80 bits
Declaration of variables:
Purpose:
1. It tells the compiler what the variable name is.
2. It specifies what type of data the variable will hold.
Syntax:
v1,v2,v3….vn- variables
Example:
1. int count;
2. int a,b;
3. float area,volume;
4. char array;
5. double a1;
Type definition:
Purpose:
This allows the user to define the identifier that would represent
an existing data type. The user-defined type is later used to
declare variables.
General form:
Typedef - keyword
Type - exiting data type
Identifier –new name given to the data type
Typedef cannot create a new type. Using identifier the variables
can be declared using the following syntax:
Examples:
Typedef int units;
Units batch1,batch2;
Units name[10],name1[20];
It is used to declare the variables that can have one of the values
enclosed within braces(known as enumerated constants).we can
declare variables to be of this ‘new’ type as below:
OUTPUT:
Jan=0
Feb=1
June=5
Dec=11
Explanation: In the above program enumerated data type month is
declared with 12-month names within two curly braces. The compiler
assign 0 value to first identifier and 11 to last identifier. Using printf()
statement the constants are displayed for different identifier. By
default the compiler assign value from 0 onwards. Instead of 0 the
programmer can initialize his/her own constant to each identifier.
Storage classes:
Purpose:
It provides the information about location and visibility of
variables.
Types meaning
1. auto local variable known only to the function
where it is declared
default is auto.
2.static local variable which exists and retains it ‘s
value even after
control is transferred to the calling function.
3.extern global variable known to all function sin the file
4.register local variable which is stored in the register.
Example:
auto int count;
register char ch;
static int x;
extern long total;
Assignment statement:
Purpose : values can be assigned to variables using the
assignment operator = as follows
Examples:
It is possible to assign the values during declaration time as
follows:
Example:
Arithmetic operators:
Arithmetic operators are used to perform arithmetic
operations like addition , subtraction, multiplication and division
and to find the remaindering division. The corresponding symbols
are +(addition or unary plus),- (subtraction or unary minus),*,/,%
(modulo division).C does not have an operator exponentiation.
Relational operators:
Purpose:
To relate any two or more quantities.
Operator Meaning
< is less than
> is greater than
> is greater than or
equal to
<= is lesser than or equal
to
== is equal to
!= is not equal to
Logical operators:
Purpose :
To combine two or more expressions.
Operator meaning
&& logical and
|| logical or
! logical not
Assignment operators:
= is used to assign value to a variable. In addition
to this c has
shorthand operators.
Syntax:
Advantages:
1. No need to repeat the operator again in the right
hand side.
2. The statement is more concise and clear.
3. The statement is more efficient.
4. It is easy to read.
Conditional operator:
Purpose:
A ternary operator pair “?:” is used to construct
conditional expressions
Syntax:
Example :
x=(a>b)?a:b;
In the above the condition is evaluated first .if true
then a will be assigned to x or else b will be assigned to x. The
above syntax is equivalent to if …else statement.
Bitwise operators:
Purpose:
Manipulating the data at bit level.
Operator Meaning
& bitwise AND
| bitwise OR
^ bitwise EXCLUSIVE OR
<< shift left
>> shift right
~ one’s complement
Special operators:
sizeof - to determine the size of the variable
,(comma) - to link the related expressions together
example : value=(x=10,y=17,x+y)
. and -> - member selection operator
& and * - pointer operator
Expressions:
Combination of both operand and operator.
Types:
1. Arithmetic
2. Relational
3. Logical
Arithmetic expression:
Operand combined with arithmetic operators called as
arithmetic expressions
Examples:
a+b
c-d
Types:
1. Integer arithmetic
2. Real arithmetic
3. Mixed arithmetic
Integer arithmetic:
Arithmetic operator combined with integer operands.
Example:
a + b; where a and b are of type integer.
Real arithmetic:
Arithmetic operator combined with real operands.
Example:
a + b where a and b are of type real.
Evaluation of expression:
Expression evaluation based on the priority of
operators.
High priority * / % left to right
Low priority + -
Logical expression:
Whenever the logical operators combine any two relational
expressions then it is called logical expression.
Example:
((a<b )&& (c>d))
Operator precedence:
1. Logical NOT
2. Logical AND
3. Logical OR
Casting a value:
If we need to force the type conversion explicitly then
it is called as coercion.
Example:
ratio=(float) number1/number2;
Where number 1 and number2 are of type integer type,
ratio is of type float.
General form of Casting:
Suggested Questions
Unit-II
If statement:
Purpose:
It is a powerful decision making statement to control
the flow of execution. It is basically two-way decision statement
and is used in conjunction with and expression.
Syntax:
entry
false
true
Simple if statement:
Syntax:
If …else statement:
Syntax:
Else … if ladder:
Syntax:
Loop constructs:
Purpose:
It is used to repeat the block of statements for n number of
times.
Process involved in looping statement is as follows:-
1. Setting and initialization of counter.
2. Execution of the statements of the statements in the loop.
3. Test for a specified condition for execution of the loop.
4. Incrementing the counter.
Types:
1. While statement
2. Do statement
3. For statement
1) While statement:
a. The while is an entry- controlled loop statement.
b. The test -condition is evaluated first and if the
condition is true, then the body of
loop is executed. Again the test-condition is tested and body
of the loop will be
repeated until the condition becomes false
c. If at the entry condition itself the test-condition is false then
body of loop will be
skipped.
Syntax:
Example:
#include < stdio.h>
void main()
{
int i=1;
while (i<1)
{
printf(“this is number %d\n”);
i++;
}
}
2) The do statement:
a. The do is an exit- controlled loop statement.
b. The body of loop will be executed once and the condition is
tested if the condition is true then body will be repeated or
else exit from the loop.
Syntax:
Example:
------------------
-----------------
do
{
printf(“well done!”);
}
while(number<=10);
---------------
---------------
3) For statement :
If we know the exact number of times for repetition of block
of statements, then for statement can be used. it is entry
controlled control loop.
Syntax:
Suggested Questions
Objective answers:
18.What is the size of long int?
19.Name any two ascii types of constants.
20.Must all the variables appearing within a C program be
declared ?
21.What is meant by linking
22.When is the logical expression evaluated in a do..while
statement?
23.What symbol terminates each C statement/
24.What sre symbols used for logical operators AND & OR?
25.Give the conversion specifications used for printing octal & hexa
decimal values.
26.every line in c programming should end with a semi colon.- say
true or false
27.in c language , lowercase letters are significant- say true or false
28.every c program end with and END word.
29.main() is where the program begins its execution.
30.a line in c program may have more than oneline of output.
31.a printf() statement can generate only one line of output.
32.syntax error will be detected by the compiler.
33.what are trigraph characters? How are they useful?
34.what is variable.
35.what is initialization? Why it is important?
36.what are enumeration variables? How are they declared?
37.describe the purpose of the qualifiers const and volatile.
38.which of the following are invalid constant and why?
0.0001
5x1.5
99999
“12.342”
39.which of the following are invalid variable names and why?
Maximum
Last.rollno
Mn+me
Row total
40.which of the following arithmetic expressions are valid? If invalid,
give reason.
25/3%2
12.4%2
21 %(int)3.2
41.write the c assignment statements to evaluate the following
equations.
42.Area= IIr2+22/7rh
43.Torque=2m1m2
44.m1+m2
45.determine the valueof each of the following logical expressions if
a=10,b=25and c=-7
a>b&&a<c
a<b &&a>c
b>12&&c<0 ||c<0.0
46.state errors ,if any, in the following input statements
scanf(“%c %f %d”,city,&price);
scanf (“%s %d”,city,quan);
47.what is the use of conditional operator?
48.write the syntax of if.. statement . write the difference between
while statement and do…while statement
Suggested Questions:
49.Explain if statement with an example
50.Differentiate while & do...while statement
51.?
52.write a program to check whether the given year is a leap year
or not
53.write a program to find largest among three given numbers.
54.write a program to find reverse of the given digit
55.write a program to do arithmetic operations for any two given
numbers using switch case statement.
56.write important features of for statement.
57.write a program to convert the given farenheit temperature to
Celsius temperature.
58.write a program to generate fibanocci numbers
59.write a program to generate prime numbers.
60.write a program to calculate simple and compound interest
Essay Answers
61.Explain about looping statements with suitable examples
62.Write a program to print the fibonacci series
63.Write a program to print the prime numbers between 1 to 100
64.Write a program in c to solve a quadratic equation to check all
possibilities of their coefficients
STUDY MATERIAL
Unit-III
Arrays : Array initialization – definition – characteristics- one –
dimensional array, predefined streams- Two- dimensional array – Three
or multi dimensional arrays. Strings and Standard functions:-
Declaration and initialization of string- Display of string with different
formats – String standard functions – Application of strings. Pointers:
Features, Pointer declaration, Arithmetic Operations with pointers-
Pointers and Array – Pointers and Two-dimensional array – Array of
pointers – Pointers to pointers – Pointer and Strings –Void pointers.
Functions: Definition, Declaration, The return statement, Types of
functions, Call by value and Call by reference, Functions returning
more values, Functions as an argument. Functions with Arrays and
pointers – Recursion – Preprocessor Directives.
ARRAYS
Definition :
An array is a group of related data items that share a common name.
Example:
An array name salary can be used to represent a set of salaries of a
group of employees.
A particular value in an array is called an element and can be written
as follows
TYPES :
1. One dimensional arrays / Single subscripted array
2. Two dimensional array
3. Multi dimensional array
DECLARATION OF ARRAYS:
Syntax:
where
type - int, float ,double, longint,char
variable_name - valid c programming variable
size - no. of elements
Example:
1. int a[10];
2. float height[20];
3. char name[10];
Explanation:
1. In the first declaration we can store atmost 10 elements
of type integers.
2. The second declaration can hold 20 elements of real
numbers.
3. In third we can store atmost 9 characters. While
declaring character array the last character must be a null
character(‘\0’). This character is automatically included while assigning
values to these variables. While mentioning about the size we must
include one extra space with maximum number of characters.
INITIALIZATION OF ARRAYS:
Syntax:
Example:
a. static float total[5] = {0.5,15.63,-20};
In the above the first three elements are set to 0.5, 15.63, -20
and the remaining elements are set to
zero.
b. static int count[]= {1,1,1,1};
In the above the size is omitted. The compiler itself allocates
enough space for all initialized
elements.
DECLARATION OF ARRAYS:
Syntax:
where
type - int, float ,double, longint,char
variable_name - valid c programming
variable
size - no. of elements
Example:
1. int a[10][10];
2. float height[20][2];
3. char name[10][10];
Explanation:
1. In the first declaration we can store atmost 100 elements of
integers.
2. The second declaration can hold 40 elements of real numbers.
3. In third we can store almost 10 names of 9 characters. While
declaring character array the last character must be a null
character(‘\0’). This character is automatically included while assigning
values to these variables. While mentioning about the size we must
include on extra space with maximum number of characters.
INITIALIZATION OF ARRAYS:
Syntax:
Example:
DECLARATION OF ARRAYS:
Syntax:
where
type -- int , float , double , longint , char
array_name -- valid c programming variable
si -- size of ith dimension where i =
1,2,3…n
#include <stdio.h>
#include <string.h>
main()
{
int i, a[10], n, t;
/*INPUT THE NUMBER OF ELEMENTS*/
printf(“Enter the total no of elements \n”);
scanf(“%d”,&n);
/*ENTER THE VALUES TO BE SORTED*/
printf(“Enter elements \n”);
for(i=1;i<=n;i++)
scanf(“%d”,&a[i]);
/*BUBBLE SORT*/
for(i=1;i<=n-1;i++)
{
for(j=i;j<=n;j++)
{
if (a[i]>a[j])
{
t=a[i];
a[i]=a[j];
a[j]=t;
}
}
}
/*PRINT THE RESULT*/
printf(“ sorted elements \n”);
for(i=1;i<=n;i++)
printf(“%d”,a[i]);
getch();
return(0);
}
Example:
1. char city[10];
2. char name[30];
3. static char city[9]= “new york”;
4. static char city[9]={‘n’,’e’,’w’,’,’,’y’,’o’,’r’,’k’,’\o’};
Example:
char name[15];
scanf(“% s”,name);
In the above example & is not required before the variable name.
Drawback:
1. We cannot read a line of text from the terminal.
Example:
/**************************************/
/* program to read a line of text from terminal*/
/**************************************/
#include <stdio.h>
main()
{
char line[81],character;
int c;
c=0;
printf(“enter text .press <enter> at end\n”);
do
{
character=getchar();
line[c]=character;
c++;
}
while (character!=’\n’);
c=c-1;
line[c]=’\0’;
printf(“\n%s\n”,line);
}
The characters from str1 and str2 should be copied into the
str3 one after another. The size of the array str3 should be large
enough to hold the total characters.
Example:
PROGRAM FOR CONCATENATION OF TWO STRINGS:
#include <stdio.h>
#include <conio.h>
#include <string.h>
main( )
{
int i , j , k;
static char f_str[10]={“hello”};
static char s_str[10]={“world”};
char t_str[20];
for(i=0;f_str[i]!=’/0’;i++)
t_str[i]=f_str[i];
t_str=’ ‘;
for(j=0;s_str[j]!=’/0’;j++)
t_str[i+j+1]=s_str[j];
t_str[i+j+1]=’ ‘;
printf(“%s”,t_Str);
}
Output:
hello world
Functio Description
ns
srlen ( ) Determines length of a string
srcpy ( ) Copies a string from source to destination
srncpy( Copies character of a string to another string upto the
) specified length.
srcmp Compares characters of two strings
()
sricmp( Compares two strings
)
srncmp( Compares characters of two strings upto specified length
)
srnicmp Compares characters of two strings upto specified length.
() Ignores case.
srlwr( ) Converts uppercase characters of a string to lowercase
srupr( ) Converts lower characters of a string to upper`
srdup( ) Duplicates a string.
strchr( ) Determines first occurrence of a given character in a string
strrchr( Determines last occurrence of a given character in a string
)
strstr ( )Determines first occurrence of a given string in another
string
strcat( ) Appends source string to destination string.
strncat( Appends source string to destination string upto specified
) length.
strrev( ) Reverses all characters of a string.
strset Sets all characters of string with a given argument or
() symbol.
strnset ( Sets specified numbers of characters of string with a given
) argument or symbol.
strspn( ) Finds upto what length two strings are identical.
strpbrk( Searches the first occurrence of the character in a given
) string and then it displays the string starting from that
character.
STRCAT( ) FUNCTION:
Syntax:
Example:
Part1=”computer ”;
Strcat(part1,”science”);
In the given syntax string1,string2 are character arrays. When
the function is executed string2 is appended to string1 by removing
null characters at the end of string1. thus in the given example the
output should be “computer science”. Thus the resultant value is
stored in part1.
STRCMP( ) FUNCTION:
Syntax:
Example:
Part1=”computer ”;
Strcmp(part1,”computer ”);
The above function compares the two given strings string1 and string2
and return value 0 if both are equal .if not it will return the numerical
difference between the mismatching characters in the strings. In the
above example it return o as a value.
STRCPY( ) FUNCTION:
Syntax:
Example:
Strcpy(part1,”science”);
In the given syntax string1,string2 are character arrays.
When the function is executed string2 is copied to string1. Thus in the
given example the output should be “science”. Thus the resultant
value is stored in part1.
STRLEN( ) FUNCTION:
Syntax:
Example:
Part1=”computer”;
N = Strlen(part1);
In the given syntax string1 is character array. When the
function is executed it counts and returns number of characters in a
string. The counting ends at the first null character. Thus in the given
example the output should be 8. Thus the resultant value is stored in
N.
USER-DEFINED FUNCTIONS:
DEFINITION:
A function is a self-contained block of code that performs a particular
task. once a function is designed and blocked it is called as ‘black-box’
that takes some data from the main program and returns value.
Example:
Printline()
{
int a;
for(a=1;a<40;a++)
printf(“=”);
printf(“\n”);
}
This example defines a function called printline that prints a line of 40
characters. The function is used in main as follows.
Main()
{
printline();
printf(“Use of C functions”);
printline();
}
Syntax:
Working of functions
main()
{
_______
_______
abc(x,y,z); Function call
Actual argument
_______
_______
}
abc(l,k,j) Function definition
{
Formal argument
________
________
return();
}
Actual argument
The arguments of calling function are actual arguments In the
above example, ‘x’ , ‘y’ and ‘z’ are actual arguments.
Formal arguments
The arguments of called function are formal arguments. In the
above example, ‘l’ , ‘k’ and ‘j’ are formal arguments.
Function name
Here, ‘abc’ is a function name.
Argument list
Variable names enclosed within parenthesis are
called argument list.
Function call
A function can be called by its name, terminated by
a semicolon.
Example
function fact (int n1)
{
int f1;
for(i =1;i<=n1;i++)
f1=f1*i;
return(f1);
}
Suppose if the return type is integer then there is no need to
mention about the
return type in the function definition as well as in the proto type. If
the function returns non integer value then there is need for
explicit specification about the return type. The return statement
is used to return a value to the calling function. It takes the
following form
Local and Global variables
There are 2 kinds of variables.
Local variables
The local variables are defined within the body of the
function. The variable defined is local to that function only. Other
functions can not access these variables.
Global variables
Global variables are defined outside the main( ) function.
Multiple functions can use them.
local variables: Global variables:
Example:
int m;
main( )
{
int i;
float balance;
……..
……..
function1( );
}
function1( )
{
int i;
float sum;
……
……
}
In the above example, variable m is a global variable and
can be accessed anywhere in the program where as variable i is a
local variable and should be accessed only in the function in which
it is declared. The variables balance and sum are local variables
and can be accessed in the functions main and function1
respectively.7
The Return Statement
The user defined functions uses a return statement to return the
value to the calling function. Exit from the called function to the
calling function is done by the use of a return statement. When
the return statement is executed it always returns 1.
Eg. Write a program to use a return statement in different
ways.
#include<stdio.h>
#include<conio.h>
main( )
{
int pass(int);
int x,y;
clrscr( );
printf(“ enter the value of x:”);
scanf(“%d”,&x);
if(x= =1|| x<0)
return 0;
y=pass(x);
switch(y)
{
case 1:
printf(“ The value returned is %d”,y);
break;
default:
printf(“The cube of %d is : %d”, x,y);
}
return NULL;
}
pass(a)
{
if(a = = 0)
return;
else
return(a*a*a);
}
Output:
Enter the value of x: 5
The cube of 5 is: 125
Types Of Functions:
Depending on whether the argument is present or not and
whether a value is returned or not, may belong to one of the
following categories.
1. Functions with no arguments and no return values.
2. Functions with arguments and no return values.
3. Functions with arguments and return values.
4. Functions with no arguments and return values.
Example:
/* addition of two numbers*/
#include<stdio.h>
main( )
{
add ( );
}
/* function definition*/
add()
{
int a,b;
a=a+b;
printf(“%d”,a);
return(0);
}
With Arguments but no return values:
In the previous category there is no data communication between
the functions. So this approach is not better. To make it efficiently
we could make the calling function to read data from the terminal
and pass it on to the called function. The nature of data
communication between the calling function and the called
function is with arguments but no return values.
Example:
/* addition of two numbers*/
#include<stdio.h>
main( )
{
int a=2,b=3;
add (a,b);
}
/* function definition*/
add(int a1,int b1)
{
a1=a1+b1;
printf(“%d”,a1);
return;
}
The arguments that we are using in the main function are called
actual arguments. The arguments that we are using in the
called function instead of the actual arguments are called as
formal arguments.
When a function call is made, only a copy of the values of actual
arguments is passed into the called function. Changes inside the
function will have no effect on variables used in the actual
argument list.
With Arguments and return values:
In the previous category the calling function sends some data to
the called function, but the called function does not return
anything to the calling function. So it is like one-way
communication. To make it more effective, both send and receive
data in this category. If there is any change of values in called
function, it has to be shown in the main function also.
Example:
/* addition of two numbers*/
#include<stdio.h>
main( )
{
int a,b,c;
c=add (a,b);
printf(“%d”,c);
getch();
}
/* function definition*/
add(int a1,int b1)
{
a1=a1+b1;
return(a1);
}
With no arguments and return values:
Function as an argument:
Eg: Write a program to pass a user-defined function as an
argument to another function:
main ( )
{
int y=2, x;
x= double(square(y));
printf(“x=%d”, x);
}
double(m)
{
return(m*2);
}
square(k)
{
return(k*k);
}
Output:
x=8
Recursion:
75.Recursion is the process where a function is called repetitively
by itself.
76.The recursion can be used directly or indirectly.
Direct recursion
A function calls itself till the condition is true.
Example 1:
//program to find the factorial of a number
#include<stdio.h>
main()
{
int n;
scanf(“%d”,&n);
printf(“%d”,factorial(n));
}
factorial(int n)
{
int fact;
if(n==1)
return 1;
else
fact=n*factorial(n-1);
return(fact);
}
Steps:
1.When n=3, fact=3*factorial(2)
2.When n=2, fact=2*factorial(1)
3.When n=1, 1 is returned & control goes to step 1
where fact = 2*1=2 & control is returned to step 1
where fact = 3*2=6 & value is given to the calling
function
Indirect Recursion
A function calls another function then the called function calls the
calling function.
Example.
Void main()
{
add();
}
add()
{
static int i=0;
while (i<5)
{
i++;
main();
}
}
STORAGE CLASSES:
Purpose:
Storage classes tell the compiler the information about location and
visibility of variables.
C has four storage classes
• Automatic variables
• External variables
• Static variables
• Register variables.
Automatic variables:
• They are declared inside the function where they are used.
• They are created when a function is called and destroyed when the
function is exited.
• They are local to the function where they are declared and so are
called local or internal variables.
• A variable declared inside a function without any storage class
specification is treated as auto by default.
• The value of an auto variable cannot be changed accidentally, so
the same name can be used in different functions.
Syntax:
Int variable name;
Or
Auto int variable name;
Example:
main()
{
int a=1000;
function2();
printf(“%d\n”,a);
}
function2()
{
int a=10;
function1();
printf(“%d\n”,a);
}
function1()
{
int a=100;
printf(“%d\n”,a);
}
Output:
100
10
1000
EXTERNAL VARIABLES:
• Variables that are both alive and active throughout the program are
external or global variables.
• They can be accessed by any function within the program.
• They are declared outside a function.
• Once a variable is declared as global any function can change its
value. Therefore these are generally used when values are to be
shared between functions.
• A global variable is visible only from the point where it is declared.
main()
{
y=5;
……
}
int y;
f1()
{
y=y+1;
}
This will cause the compiler to generate an error message since y has
not been defined in the function main.
To avoid this we use the storage class extern.
main()
{
extern int y;
……
……
}
f1()
{
extern int y;
……
……
}
• The keyword extern informs the compiler that thevariable y has
been declared somewhere and asks to perform a lookup for the
variable. The extern declaration does not allocate storage space for
the variables.
• Multiple files can share a variable provided it is declared as en
external variable (i.e) it is declared as a global variable in one file
and specified as an extern in the other.
Example:
int a;
main()
{
a=10;
function2();
printf(“%d\n”,a);
}
function2()
{
a=a*10;
function1();
printf(“%d\n”,a);
}
function1()
{
a=a*10;
printf(“%d\n”,a);
}
Output:
1000
1000
1000
STATIC VARIABLES:
• The value of static variables persist until the end of the program.
• Can be of internal or external type depending on the place of
declaration.
• Internal static variables are those that are declared inside a
function.They are similar to auto variables but are alive throughout
the entire program. They are used to retain values between function
calls.
• External static variables are those that are declared outside
functions.
• A static external variable is available only within the file where it is
declared.
• A static variable is initialized only once.
Example:
/*Static variable example*/
main()
{
int i;
for( i = 0; i<=3; i++)
{
stat();
}
}
stat()
{
static int x=0;
x=x+1;
printf(“%d\n”,x);
}
Output:
x=1
x=2
x=3
REGISTER VARIABLES:
• Register variables tells the compiler to store the value of a variable
in a register instead of the memory.
• Register access is much faster than memory access.
• Frequently used variables can be placed in the register.
• Leads to faster execution of programs.
• Most compilers allow only int and char datatype to be placed in the
register.
• C automatically converts register variables into non register
variables once the limit is reached.
Syntax:
VISIBILITY AND LIFETIME OF VARIABLES:
POINTERS:
A pointer is a variable that contains an address which is a
location of another variable in memory.
REPRESENTATION OF A VARIABLE:
The computer’s memory is a sequential collection of ‘storage
cells’ called as a byte. Each byte has a unique address associated
with it. Whenever a variable is declared the value will be stored in a
memory location in the given name. Thus it may have some address
the above ‘quantity’ is a variable name with the content 100 stored in
the location 5000. If we use a pointer variable for indicating this
content then the pointer variable itself contains the address 5000 as its
value. Thus pointer variable is a variable which contains the address of
another variable. Using pointer variable p the memory representation
will be as like as follows
The above tells the compiler three things about the variable pt_name.
1. The asterisk (*) tells that the variable pt_name is a pointer
variable.
2. pt_name needs a memory location.
3. pt_name points to a variable of type data type.
Example:
int *p;
declares the variable p as a pointer variable that points to an integer
data type. The type int refers to the data type of the variable being
pointed to by p and not the type of the value of the pointer. Similarly
the statement
float * x;
declares x as a pointer to a floating point variable. Once a pointer has
been declared , it can be made to point to a variable using an
assignment statement such as
p = &quantity;
Thus p now contains the address of the variable quantity. This as
called pointer initialization.
quantity = 100;
p = &quantity;
n = *p;
Thus in the above example the first statement declares the pointer
variable p ,which points to integer data type. In the second statement
100 is assigned to quantity. In the third statement the address is
assigned to the pointer variable p. In the fourth statement the content
is assigned to the variable n.
POINTER EXPRESSIONS:
Like other variables, pointer variables can be used in
expressions. For example , if p1 and p2 are properly declared and
initialized pointers, then the following statements are true.
y = *p1 * *p2;
sum =sum+ *p;
p1++;
y = *p1/ *p2;
In the above the first one is to perform multiplication of the content of
p1 and p2 and assign it to y. In the second statement the content of p
is added with sum. In the third statement the address p1 is
incremented by one. The fourth statement divides the p1 by p2. There
should be a blank space between / and the indirection operator *
otherwise it is treated as a comment.
mentioned below.
p1 = p1+1;
p1++;
provided p1 has been declared and initialized properly. If p1 is a
integer pointer in the location 2000,then the above expression causes
the pointer to move to 2002 location.
Datatype Memory locations
2000 2001 2002 2003
2004 2005
Int
Char
Float
Where
base address
The name x is defined as a constant pointer pointing to the first
element ,x[0] and therefore the value of x is 1000,the location where
x[0]is stored. That is
x = &x[0] = 1000
If we declare p as a pointer , then we can make the pointer p to the
array x by the following assignment:
p=x;
That is equivalent to
p=&x[0];
Suppose if we want to access the next element then we can
increment the address by p++ to move from one element to another.
The relationship between p and x is shown below:
P= &x[0] (=1000)
P+1=&x[1] (=1002)
P+2=&x[2] (=1004)
P+3=&x[3] (=1006)
P+4=&x[4] (=1008)
Example:
/*Program to calculate the sum of numbers in an array using
pointers*/
#include<stdio.h>
Main()
{
int x[10], *p, i, sum=0;
printf(“Enter the elements\n”);
for(i=0;i<10;i++)
scanf(“%d”,&x[i]);
p=x;
for(i=0;i<10;i++)
{
sum = sum + *p;
p++;
}
printf(“Sum = %d”,sum);
}
(1,1
)
(2,0
)
(3,0 (3,2
) )
#include<stdio.h>
main()
int a[5][3],i,j;
for(i=0;i<5;i++)
for(j=0;j<3;j++)
{
scanf(“%d”,&a[i][j]);
printf(“Original Matrix\n”);
for(i=0;i<5;i++)
for(j=0;j<3;j++)
printf(“%d\t”,a[i][j]);
printf(“\n”);
}
for(j=0;j<3;j++)
for(i=0;i<5;i++)
printf(“%d\t”,*(*(a+i)+j));
printf(“\n”);
}
getch();
reference. The function that can be called by reference van change the
Example:
#include<stdio.h>
Main()
{
int x=100,y=200;
printf(“Before exchange : x = %d y = %d\n”,x,y);
exchange(&x,&y);
printf(“After exchange : x = %d y = %d\n”,x,y);
}
exchange(int *a, *b)
{
int t;
t=*a;
*a = *b;
*b = t;
}
Output:
Before exchange : x=100 y=200
After exchange : x=200 y=100
Thus, call by reference provides a mechanism by which the function
can change the stored values in the calling function.
Note:
Syntax:
Example:
#include<stdio.h>
void Main()
int exp(),val(),I,v;
for(I=1;I<=5;I++)
v=val(exp,I);
printf(“%d”,v);
int val(f,I)
int (*f)(),I;
return (2 * (*f)(I));
int exp(int I)
{
return(I*I);
ARRAY OF POINTERS:
Example:
#include<stdio.h>
main()
int *arr[3],i=10,j=20,k=30,m;
arr[0]=&I;
arr[1]=&j;
arr[2]=&k;
for(m=0;m<3;m++)
printf(“%d\n”,*(arr[m]));
Output:
10
20
30
memory is as follows.
I j k
Datatype *array[expression1];
Syntax:
Example:
#include<stdio.h>
void main()
int *p[3],I,j;
int a[]={1,2,3},b[]={4,5,6},c[]={7,8,9};
p[0]=a;
p[1]=b;
p[2]=c;
printf(“the values are…\n”);
for(I=0;I<3;I++)
for(j=0;j<3;j++)
printf(“%d”,*(p[I]+j));
address of the first array a. p[1] has the base address of the second
array b and so on. The expression (p[I]+j) denotes the jth value at the
ith row. Thus (p[2]+1)represents the first element in the third array
‘c’.*(p[I]+j) represents the value at the jth column in the ith row.
Preprocessor Directives :
Explanation:
In the above program after conversion the statement
say(HELLO) is treated as printf(“HELLO”) . It is not essential to
enclose the text in quotation marks in the stringizing operator.
Example:
Write a program to find the larger of the two numbers using
macro with arguments.
#include<stdio.h>
#include<conio.h>
# define MAX(x,y) if (x>y) c=x; else c=y;
void main()
{
int x=5,y=8,c;
clrscr();
MAX(x,y);
printf(“\n Larger of two numbers = %d”,c);
}
Output:
Larger of two numbers = 8
Explanation:
In the above program macro MAX() is defined with two
arguments x and y. When a macro is called, its corresponding
expression is executed and result is displayed .The expression
contains if statement that determines the largest number and
assigns it to variable c.
}
#else
# error <error message>
# endif
The #line directive
The syntax is
#line <constant> [<identifier>]
This causes the compiler to imagine the line number of
the next source line is given by <constant> and <identifier>
gives the current input file. If <identifier > is absent , then the
cuurent file name remains unchanged.
Example : # line 15 add.c
The INLINE directive
Reports the compiler that the source code has in line
‘asm’ statements. The source code will contain the assembly
code.
The #pragma SAVEREGS
It guarantees that a huge function will not modify the
value of any of the registers when it is entered. Place this
directive immediately preceding the function definition.
The #pragma DIRECTIVE
The ANSI-C and TURBO-C provide pragma directives >
these # pragma directives are defined with #(hash) and these are
the preprocessor directives. It sets/resets certain warning and
errors during compilation of C program.
Syntax:
# pragma warn +xxx
# pragma warn –xxx
ANSI Violations and #pragma
Example:
Write a program to set off certain errors shown by the program
using #pragma directive
#include<stdio.h>
#include<conio.h>
#pragma warn-aus
#pragma warn-def
#pragma warn-rvl
#pragma warn-use
main ()
{
int x=2,y,z;
printf (“\n y=%d”,y);
}
Explanation:
The above program contains following warnings
85.Possible use of ‘y’ before definition in function.
86.‘Z’ is declared but never used in function main.
87.‘x’ is assigned a value which is never used in function.
88.Function should return a value in function main.
The display of these errors can be made on/off by using
the pragma options.
Standard i/o predefined Streams in Stdio.h
The predefined streams automatically opens when the program
is started.
isalpha(d) d is a letter
isupper(d) d is a capital letter
islower(d) d is a small letter
isdigit(d) d is a digit
isalnum(d) d is a letter or digit
isxdigit(d) d is a hexa decimal digit
isspace(d) d is a space
ispunct(d) d is a punctuation
Isprint(d) d is a printable character
isgraph(d) d is a printable but not a space
iscntrl(d) d is a control character
isascii(d) d is an ascii code
time. Sometimes our initial judgement of the size of the arrays may be
avoid such problems C allows the user to specify the size of the array
Storage of a C program
Stack
Heap
Permanent storage area
permanent storage area. Local variables are stored in the stack. The
free region is called the heap and is used for dynamic memory
memory space.
Malloc():
Syntax:
Example:
Calloc():
Syntax:
Example:
……..
……..
struct student
char name[25];
float age;
};
record *st_ptr;
int class=30;
……..
……..
st_ptr=(record*)calloc(class,sizeof(record));
Free():
Syntax:
Example:
Free(p);
Realloc():
already allocated
1. When the previously allocated memory is not sufficient and the user
requires additional space.
2. When the memory allocated is larger and the user wishes to reduce
it.
In both the cases the memory size can be changed with the use of
realloc().
Syntax:
the pointer variable ptr and returns a pointer to the first byte of the
The newsize may be smaller or larger than the original size. The
realloc() function does not modify the original contents. If the function
Program:
void main()
p[0]=(int*)malloc(c*sizeof(int));
cols
p[2]=(int*)malloc(c*sizeof(int));
for(I=0;I<3;I++)
for(j=0;j<c;j++)
scanf(“%d”,(p[I]+j));
for(I=0;I<3;I++)
for(j=0;j<c;j++)
printf(“%d”,*(p[I]+j));
Suggested Questions
Section A
Section –B
122.Write short notes on functions
123.Differentiate local and global variables
124.Write short notes on different types of arguments
125.Explain string handling functions in detail with examples.
126.Write a program which will read a text and count all
occurrences of a particular word.
127.Explain the usage of break & continue statement
128.Write short notes on conditional operatorWrite short notes
on multidimensional arrays
129.Write a program to search an element using linear search.
130.Write a program to sort the given set elements using
selection sort
131.Write a program to arrange the given set of element using
ascending order.
132.Write a program to arrange the given set numbers in
descending order.
133.Write a program to add two given matrices of order m x n
134.Explain about switch statement
135.Distinguish between local and global variables
136.Distinguish between formal and actual arguments.
137.Distinguish between automatic and static variables.
138.Distinguish between global and extern variables.
139.Is the main user defined function? If yes means how it differs
from the other user defined functions?
140.Write a program to calculate npr using user defined function.
141.Write a recursive program to generate fibonacci nubers
142.Write shorts notes on auto storage class
143.Explain about register & extern variables
144.Write a recursive program to calculate the factorial of a
given number.
145.Write a program to find if a string is a palindrome or not.
Section –C
146.Explain recursion with an example
147.Explain about user defined functions
148.Write a program to sort a set of numbers and to print
minimum & maximum
of the set
149.Explain multidimentional arrays.
150.Write a program to find sum of positive & negative real
numbers seperately
from a given set of real numbers using continue and while
statement
151.Explain any 4 string functions with examples
152.Discuss on different storage classes
8. Write a program to print the set of names in alphabetical
order
9. Write a program to count the number of palindromes in a
given text.
153.Write a program to sort a list of names in alphabetical order.
154.Write notes on one dimensional array with relevant example.
155.Write notes on two dimensional arrays with examples.
156.Write a program to multiply 2 matrices.
157.Write a program to find the transpose of a matrix
Section D
1. Explain functions with suitable example and write a program
for NCR using
Functions
2. Explain arrays with relevant examples.
3. Explain strings with relevant examples.
4. Explain the various storage classes
5. Write notes on two dimensional arrays. How will you multiply
2 matrices.
6. Write a program to sort out a list of n names in bith ascending
and descending order.
STUDY MATERIAL
Unit-IV
Structure and Union: Features of structure, Declaration and
initialization of structure, Structure within structure, Array of structure,
Pointer to structure, Bit fields, Union.
data items.
Advantages:
1. Structures enable the user to group together a collection of different
Struct student
{
char stud_name[20];
char stud_rollno[10];
float stud_mark1;
float stud_mark2;
float stud_mark3;
};
STRUCTURE DEFINITION:
A structure definition creates a format that may be used to
declare structure variables.
General format for structure definition is as follows:
Example:
Struct book_bank name of the structure
or structure tag
{
char title[20];
char author[15]; structure elements or members
int pages;
float price;
};
struct book_bank b1,b2,b3; structure variables
In the above example book_bank is a tag-name which is optional
one. If you give the tag-name then later in the program you can
possible. The title, author, pages and price are members of the
structure. While defining the structure memory is not allocated for its
members. Only during the declaration the memory is allocated for the
Scanf(“%s”,book1.title);
Example:
/*Program to illustrate the dot operator*/
#include<stdio.h>
struct student
{
char stud_name[25];
char stud_rollno[10];
float mark1,mark2,mark3,tot;
}student1;
void main()
{
printf(“Enter student details\n”);
printf(“\nStudent Name : “);
scanf(“%s”,student1.stud_name);
printf(“\nRoll no : “);
scanf(“%s”,student1.stud_rollno);
printf(“\nMark1 : “);
scanf(“%f”,&student.mark1);
printf(“\nMark2 : “);
scanf(“%f”,&student.mark2);
printf(“\nMark3 : “);
scanf(“%f”,&student.mark3);
student1.tot = student1.mark1 + student1.mark2 +
student1.mark3;
printf(“The student details are as follows….\n”);
printf(“Student name : %s\n”,student1.stud_name);
printf(“Roll no : %s\n”,student1.stud_rollno);
printf(“Marks : %f %f
%f\n”,student1.mark1,student1.mark2,student1.mark3);
printf(“Total : %f\n”,student1.tot);
}
STRUCTURE INITIALIZATION:
Like any other type, a structure variable can be initialized.
However, a structure must be declared as static if it is to be initialized
inside a function.
Example:
main( )
static struct
{
int weight;
float height;
}student={100,150.45};
……………………..
……………………..
}
Thus in the above the value 100 to student.weight and 150.45 to
student.height. There is a one- to-one correspondence between the
members and their initializing values.
A variation in initializing a structure is as follows:
Main( )
{
struct st_record
{
int weight;
float weight;
};
static struct st_record stu1={30,70.56};
static struct st_record stu2={45,65.73};
……………
……………
}
Another variation in initializing structure variable outside the function
is as follows:
struct stu
{
int weight;
float height;
}stu1={56,170.56};
main()
{
static struct stu student2 = {23,150.5};
………………..
………………..
}
COMPARISON OF STRUCTURES:
Two variables of same structure type can be compared in the
same way as ordinary variables. If book1 and book2 are of same type
then it is possible to compare two variables as book1== book2.
similarly we can assign book2 to book1 as book1=book2.etc.
Example:
/*Program to illustrate comparison and copying of structure
variables*/
struct student
{
char stud_name[25];
char stud_rollno[10];
float mark1,mark2,mark3,tot;
}
void main()
{
static struct student s1={“aaa”,”00CS0001”,50,50,50};
static struct student s2,s3={“bbb”,”00CS002”,20,90,30};
s2=s1; //assigns structure s1’s contents to structure
s2
if(s2 = = s1) //compares structure s2 and s1
ARRAYS OF STRUCTURES:
We use structures to describe the format of a number of related
variables. For example if we want to analyse the marks obtained by a
class of students then we can use array of structures.
Example:
/*Program to illustrate arrays of structures*/
#include<stdio.h>
struct student
{
char stud_name[25];
char stud_rollno[10];
float mark1,mark2,mark3,tot;
};
void main()
{
static struct student s[3];
int I;
for(I=0;I<3;I++)
{
printf(“Enter student %d details\n”,i);
printf(“\nStudent Name : “);
scanf(“%s”,s[I].stud_name);
printf(“\nRoll no : “);
scanf(“%s”,s[I].stud_rollno);
printf(“\nMark1 : “);
scanf(“%f”,&s[I].mark1);
printf(“\nMark2 : “);
scanf(“%f”,&s[I].mark2);
printf(“\nMark3 : “);
scanf(“%f”,&s[I].mark3);
s[I].tot = s[I].mark1 + s[I].mark2 + s[I].mark3;
}
printf(“The student details are as follows….\n”);
for(I=0;I<3;I++)
{
printf(“Student name : %s\n”,s[I].stud_name);
printf(“Roll no : %s\n”,s[I].stud_rollno);
printf(“Marks : %f %f
%f\n”,s[I].mark1,s[I].mark2,s[I].mark3);
printf(“Total : %f\n”,s[I].tot);
}
}
The above example declares a structure with 6 members. Also
we have declared s to be an array consisting of 3 members of type
follows
S[1].stud_name
S[1].stud_rollno etc.
Disadvantages:
1.The method becomes unmanageable when the structure size is
large.
Example:
#include<stdio.h>
Struct student
{
char stud_name[25];
char stud_rollno[10];
struct marks
{
float mark1;
float mark2;
float mark3;
}m;
float tot;
};
void main()
{
float total(float,float,float);
static struct student s[3]={{“aaa”,”00CS001”,40,50,60},
{“bbb”,”00CS002”,20,30,40},
{“ccc”,”00CS003”,10,70,50}}
for(I=0;I<3;I++)
{
s[I].tot =
total(s[I].m.mark1,s[I].m.mark2,s[I].m.mark3);
}
printf(“The student details are as follows….\n”);
for(I=0;I<3;I++)
{
printf(“Student name : %s\n”,s[I].stud_name);
printf(“Roll no : %s\n”,s[I].stud_rollno);
printf(“Mark1 : %f \n”,s[I].m.mark1);
printf(“Mark2 : %f\n”,s[I].m.mark2);
printf(“Mark3 : %f\n”,s[I].m.mark3);
printf(“Total : %f\n”,s[I].tot);
}
}
return(a+b+c);
Example:
#include<stdio.h>
Struct student
{
char stud_name[25];
char stud_rollno[10];
struct marks
{
float mark1,mark2,mark3;
}m;
float tot;
};
void main() (struct student is the return type)
{
struct student total(struct student);
static struct student s[3]={{“aaa”,”00CS001”,40,50,60},
{“bbb”,”00CS002”,20,30,40},
{“ccc”,”00CS003”,10,70,50}}
static struct student s1[3];
for(I=0;I<3;I++)
{
s1[I] = total(s[I]); passing the structure as a
parameter
}
printf(“The student details are as follows….\n”);
for(I=0;I<3;I++)
{
printf(“Student name : %s\n”,s1[I].stud_name);
printf(“Roll no : %s\n”,s1[I].stud_rollno);
printf(“Mark1 : %f \n”,s1[I].m.mark1);
printf(“Mark2 : %f\n”,s1[I].m.mark2);
printf(“Mark3 : %f\n”,s1[I].m.mark3);
printf(“Total : %f\n”,s1[I].tot);
}
}
return(a);
passes to the function. The function can access indirectly the entire
Advantages:
structure.
• Arrow operator.(->)
• Member operator.(.)
Example:
function*/
#include<stdio.h>
Struct student
{
char stud_name[25];
char stud_rollno[10];
struct marks
{
float mark1;
float mark2;
float mark3;
}m;
float tot;
};
void main()
{
void total(struct student *p);
static struct student s={“aaa”,”00CS001”,40,50,60},*ptr;
ptr=&s;
total(ptr);
printf(“The student details are as follows….\n”);
printf(“Student name : %s\n”,ptr->stud_name);
printf(“Roll no : %s\n”,(*ptr).stud_rollno);
printf(“Mark1 : %f \n”,ptr->m->mark1);
printf(“Mark2 : %f\n”,ptr->m->mark2);
printf(“Mark3 : %f\n”,ptr->m->mark3);
printf(“Total : %f\n”,(*ptr).tot);
}
Rules:
• The called function must be declared for its type, appropriate to the
data type it must return. For example if the function is returning a
copy of the entire structure, then it must be declared as struct with
an appropriate tag name.
• The structure variable used as the actual argument and the formal
argument must be of the same struct type.
• The return statement is necessary only when the function is
returning some data.
• When a function returns a structure, it must be assigned to a
structure of identical type in the calling function.
• The called function must be declared in the calling function for its
type, if it is placed after the calling function.
UNIONS:
Unions are the concept derived from structure . So the definition
of union is same as structure except with the keyword union. The main
difference between the structure and the union is in the memory
allocation only. In structure the memory is allocated for all the
members included within the structure and all can be accessed
simultaneously. In union the memory is allocated for the longest
member in the union. So that all the members in the union can share
the allocated memory one at a time.
Example:
Union product
{
int quantity;
float price;
char code;
}p1;
In the above the memory is allocated based on the longest data
type float. Thus 4 bytes will be allocated and that memory is shared by
Example:
/unions example*/
void main()
{
union samp
{
char color;
int size;
}shirt;
shirt.color=’r’;
printf(“%c\n”,shirt.color);
shirt.size=12;
printf(“%d\n”,shirt.size);
}
Thus at a time only one member can be accessed. If we have a
statement as follows
shirt.size=12;
printf(“%d %c\n”, shirt.size, shirt.color);
Then the output will be
158.garbage character
BIT FIELDS:
There are occasions where data items require much less space
than the allocated space. C allows the user 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 to
16 bits in length. The name and size of bit fields are defined using a
structure.
159.Bi t field provides exact amount of bits required for storage of
values. If a variable value is 1 or 0 we need a single bit to store it.
160.The variable is expressed between 0 and 3, then the two bits are
sufficient for storing these values.
161.Similarly if a variable assumes value between 0 and 7 then three
bits will be sufficient to hold the variable and so on.
162.The number of bits required for a variable is specified by non-
negative integer followed by colon.
163.To hold the information we use the variable. The variables occupy
a minimum of one byte for char and two bytes for integer.
164.The information about the vehicle, following information has to
be stored in the memory.
165.Petrol vehicle
166.Diesel vehicle
167.Two wheeler vehicle
168.Four wheeler vehicle
169.Old model
170.New model
In order to store the status of the above information we may need two
bits for types of rules as to whether the vehicle is of petrol or diesel
type.
Three bits for its type as to whether the vehicle is two or four wheeler.
There are restricted on bit fields when array are used. Array of bit
fields are not permitted.
The pointer cannot be used for addressing the bit field directly,
although the use of the member access operator (à) is acceptable.
The structure for the above problem would be as follows
Struct vehicle
{
Unsigned type:3;
Unsigned fuel:2;
Unsigned model:3;
};
The colon (;) in the above declaration tells to the compiler that bit
fields are used in the structure and the number after it indicates how
many bits are required to allot to the field.
Example:
Write a program to store the information of vehicle. Use bit
fields to store the status of information.
#include <stdio.h>
#include <conio.h>
#define PETROL 1
#define DIESEL 2
#define TWO_WE 3
#define FOUR_WE 4
#define OLD 5
#define NEW 6
Void main()
{
Struct vehicle
{
Unsigned type:3;
Unsigned fuel:2;
Unsigned model:3;
};
Struct vehicle v;
v.type=FOUR_WE;
v.fuel=DIESEL;
v.model=OLD;
clrscr();
printf(“\ntype of vehicle:%d”,v.type);
printf(“\nfuel:%d”,v.fuel);
printf(“\nmodel:%d”,v.model);
}
OUTPUT:
Type of vehicle:4
Fuel: 2
Model:5
Explanation: In the above program using #define macros are
declared. The information about the vehicle is indicated between
integer 1 to 6. The structure vehicle is declared with bit field. The
number of bits required for each member is initialized. As per the
program for type of vehicle requires 3bit, fuel requires 2 bits and
model requires 3 bits. An object v is declared. Using the object bit
fields are initialized with data.
Format:
Thedatetype can either be signed or unsigned int and the bit_length
Rules:
• The first field always starts with the first bit of the word.
• The sum of all the fields in the structure should not be more than
the size of a word.
• There can be unnamed fields declared with size
Example: unsigned :2;
Main()
struct num
unsigned a:1;
unsigned b:2;
unsigned c:3;
unsigned d:6;
}n;
n.a=0;
n.b=2;
n.c=4;
n.d=14;
printf(“%d %d %d %d\n”,n.a,n.b,n.c,n.d);
Output:
0 2 4 14
Suggested Questions :
between Them.
Unit-V
Files: Streams and file types, Steps for file operation, File I/O,
Structures read and write, other file functions, Command line
arguments, I/O redirection
FILE:
A file is a place on disk where a group of related data is
stored.
Example: input.data
Data structure is defined as FILE in the standard I/O library. So all
files should be declared as type FILE (defined data type).
Purpose may any one of the following .
• read ( r )
• write ( w )
• append ( a )
CLOSING A FILE:
A file must be closed as soon as all operations on it have
been completed. This ensures that all outstanding information
associated with the file is flushed out from buffers and all links to
the files are broken. It also prevents any accidental misuse of the
file. Another instance where we have to close a file is when we
want to reopen the same file in a different mode.
SYNTAX:
Example:
FILE * p1, * p2;
p1=fopen(“input”,”w”);
p2=fopen(“output”,”w”);
---------------------------
fclose(p1);
fclose(p2);
---------------------------
Function Operation
name
fopen( creates a new file or opens an existing
) file for use
fclose( closes a file which has been opened for
) use
getc( ) reads a character from a file
putc ( ) writes a character to a file
fprintf( writes a set of data values to a file
)
fscanf( reads a set of data values to a file
)
getw( ) reads an integer from a file
putw( ) writes an integer to a file
fseek( ) sets the position to a desired point in
the file
ftell( ) gives the current position in the file
rewind( sets the position to the beginning of the
) file
SYNTAX:
getc( ):
To read a character from a file.
putc( ):
To write a character to a file.
Example:
char a,b=’b’;
FILE *f1, *f2;
……
a=getc(f1);
…….
Putc(b,f2);
Program :
# include <stdio.h>
main ( )
{
FILE *f1;
char c;
printf(“data input \n”);
f1=fopen(“input”,”w”); /* open the file input*/
while ((c=getchar( ))!=EOF) /*get a character from keyboard */
putc (c, f1); /*write a character to input */
fclose(f1); /*close the file input */
printf(“\n data output \n\n”);
f1=fopen(“input”,”r”); /*reopen the file input */
while ((c=getc(f1))!=EOF) /*read a character from input */
printf(“%c”,c); /*display a character on screen */
fclose(f1); /*close the file input */
}
SYNTAX:
getw( ):
To read an integer from a file.
putw( ):
To write an integer to a file.
Example:
int a,b=10;
FILE *f1, *f2;
……
a=getw(f1);
…….
Putw(b,f2);
Program :
# include <stdio.h>
main ( )
{
FILE *f1;
Int i,c;
printf(“data input \n”);
F1=fopen(“input”,”w”); /* open the file input*/
For (i=1;i<=10;i++)
Scanf(“%d”,&c)
If (c==-1) break;
putw (c, f1); /*write a number to input */
fclose(f1); /*close the file input */
printf(“\n data output \n\n”);
f1=fopen(“input”,”r”); /*reopen the file input */
while ((c=getw(f1))!=EOF) /*read a number from input */
printf(“%d”,c); /*display the number on screen
*/
fclose(f1); /*close the file input */
}
fscanf( ):
To read a group of data from a file.
fprintf( ):
To write a group of data to a file.
Example:
char a,b=’b’;
int c,d=10;
FILE *f1, *f2;
……
fscanf(f1,“%d %c”,&c,&a);
…….
fprintf(f2,”%d %c”,d,b);
Program:
# include <stdio.h>
main ( )
{
FILE *f1;
char name[10];
int roll;
printf(“data input \n”);
f1=fopen(“input”,”w”); /* open the file input*/
scanf(“%s %d”,name,&roll); /*get a group of data from
keyboard */
fprintf(f1,”%s %d”,name,roll); /*write a character to input */
fclose(f1); /*close the file input */
printf(“\n data output \n\n”);
f1=fopen(“input”,”r”); /*reopen the file input */
fscanf (f1,”%s %d”,name,&roll); /*read data from input */
printf(“%s %d”,name,roll); /*display data on screen
*/
fclose(f1); /*close the file input */
}
SYNTAX:
feof( ):
It is used to test for end of file condition. It takes the file pointer
as the only argument and returns a nonzero integer value if all of the
data from specified file has been read, and returns zero otherwise.
Example:
If (feof(fp))
Printf(“end of data”);
ferror( ):
This function reports the status of the file indicated. It takes a file
pointer as its argument and returns nonzero integer if an error
has been detected or returns a zero otherwise.
Example:
If ( ferror(fp)!=0)
Printf(“an error has occurred”);
Program:
#include<stdio.h>
void main()
{
FILE *f1;
Char filename[10];
Int a,b,i;
F1=fopen(“TEST”,”w”);
For(I=0;I<10;I++)
{
scanf(“%d”,&a);
putw(a,f1);
}
fclose(f1);
x: printf(“Enter the filename);
Scanf(“%s”,filename);
If((f1=fopen(filename,”r”))==NULL)
{
printf(“Invalid file name\n”);
goto x;
}
else
{
while(feof(f1)==0)
{
b=getw(f1);
printf(“%d\n”,b+10);
}
}
fclose(f1);
}
ftell():
The function ftell() gives the current position of a file. It
takes a file pointer as an argument and returns a type long that
corresponds to the current position.
SYNTAX:
rewind():
The function rewind() moves the pointer to the start of the
file. It takes a file pointer as an argument and moves the pointer
to the start of the file.
SYNTAX:
Example:
FILE *f1;
……
rewind(f1);
n=ftell(f1);
Now n will have a value of 0 ( the start of the file).
Advantages of rewind():
Helps to read a file more than once without having to open and
close it.
fseek():
This function is used to move to the desired position in the
file. It takes 3 arguments.
1. file pointer – pointer to the concerned
file.
2. Offset – specifies the number of
positions(bytes) to be moved.
3. Position – position takes one of the 3
values
179.0 – start of file.
180.1 – current position
181.2 – end of file.
Example:
fseek(fp,0L,0) – go to the beginning of the file.
fseek(fp,0L,2) – go to the end of the file.
fseek(fp,0L,1) – stay in the current position.
fseek(fp,m,0) – move to m+1th byte.
fseek(fp,m,1) – go forward by m bytes.
fseek(fp,-m,1) – go backwards by m bytes.
Program:
#include<stdio.h>
void main()
{
FILE *f1;
Long n;
F1=fopen(“test”,”w”);
While((c=getchar())!=EOF)
Putc(c,f1); //writes characters
into the file.
Printf(“No of characters %ld\n”,ftell(f1); //gives the current
position of the //pointer in the file
Fclose(f1);
Fp=fopen(“test”,”r”);
N=0L;
While(feof(f1)==0) //moves the
position by 5 bytes.
{
fseek(f1,n,0);
printf(“Current position %ld current character
%c\n”,ftell(f1),getc(f1));
n=n+5L;
}
fseek(f1,-1L,2) //moves to the last
character
do //prints the file in
reverse
{
printf(“%c”,getc(f1));
}while(!fseek(f1,-2L,1);
fclose(f1);
}
C PREPROCESSOR DIRECTIVES:
The preprocessor is a program that processes the source
code before it passes through the compiler. It operates under the
preprocessor directives or preprocessor command lines.
Preprocessor directives are placed before the main() function.
Rules:
• Preprocessor directives begin with #.
• They are placed before the main() function.
• They do not require a semicolon at the end.
Categories:
1. Macro substitution directives
2. File inclusion directives
3. Compiler control directives
Macro substitution:
Macro substitution is a process where an identifier in a
program is replaced by a predefined string composed of one or
more tokens. The processor accomplishes this task by using
#define statement. This statement is known as a macro definition.
SYNTAX:
UNDEFINING A MACRO:
A defined macro can be undefined ,using the statement
#undef identifer
Example:
#undef SQUARE
The above will undefine the macro definition SQUARE
FILE INCLUSION:
An external file containing functions or macro
definitions can be included as a part of a program. So that we
need not rewrite those functions or macro definitions. This is
achieved by the preprocessor directive
#include <stdio.h> /* include the predefined header file in to
our program*/
#include “define.h” /* include the user defined header file to the
program*/
Example:
#include “test.c”
#define M 100
void main()
{
……
……
}
TYPE DEFINITION:
This allows the user to define the identifier that representS an
existing data type. The user-defined type is later used to declare
variables.
General form:
Typedef - keyword
Type - exiSting data type
Identifier –new name given to the data type
Typedef cannot create a new type. Using identifier the
variables can be declared using the following syntax:
Examples:
Typedef int units;
Units batch1,batch2;
Units name[10],name1[20];
BITWISE OPERATORS:
Purpose:
Bitwise operators are required to manipulate
individual bits in memory.
Categories:
• Bitwise logical operators
• Bitwise shift operators
• One’s complement operator.
One’s complement operator:
This is a unary operator that causes the bits of its operand to be
inverted such that 0’s become 1’s and 1’s become 0’s.The symbol
used is ~.
Example:
~011 = 100
B = a >>6;
B = 0000 0001 1011 0110
BITFIELDS:
Refer IV unit.
So argv[0]=program
Argv[1]=x_file
Argv[2[=y_file
Program:
#include<stdio.h>
main(int argc,char *argv[])
{
FILE *fp;
Int I;
Char word[15];
Fp=fopen(argv[1],”w”);
Printf(“No of command line arguments = %d\n”,argc);
For(I=1;I<argc;I++)
Fprintf(fp,”%s”,argv[I]); //writes arguments into
file
Fclose(fp);
Fp=fopen(fp,”r”);
For(I=1;I<argc;I++)
{
fscanf(fp,”%s”,word); // reads and prints
the arguments
printf(“Command line argument[%d] is
%s\n”,I,word]);
}
fclose(fp);
}
Suggested Questions
Objective Questions
Short answers:
188.Write short notes on bitwise operators
189.Explain how strings may be written into file.
190.Write short notes on preprocessor directives
191.Explain command line arguments.
192.Explain about register & extern variables
193.Explain about conditional compilation
Long answers
194.Write short notes on file handling commands
195.Explain about macro preprocessor directives
196.Write a program to copy the contents of one file to another
using command Line arguments
4. Compare fread & fwrite , fscanf & fprintf with suitable
examples.