Problem Solving in C
Problem Solving in C
1)Input Unit: All the data received by the computer goes through the input unit. The input
unit comprises different devices. Like a mouse, keyboard, scanner, etc. In other words, each of
these devices acts as a mediator between the users and the computer.
The data that is to be processed is put through the input unit. The computer accepts the raw
data in binary form. It then processes the data, and produces the desired output.
The 3 major functions of the input unit are-
• Take the data to be processed by the user.
• Convert the given data into machine-readable form.
• And then, transmit the converted data into the main memory of the computer. The sole
purpose is to connect the user and the computer. In addition, this creates easy
communication between them.
2.Input/output Symbol: The input symbol is used to represent the input data, and the
output symbol is used to display the output operation. The symbol given below is used for
representing the Input/output symbol.
4.Decision Symbol: Diamond symbol is used for represents decision-making statements. The
symbol given below is used to represent the decision symbol.
5.Connector Symbol: The connector symbol is used if flows discontinued at some point and
continued again at another place. The following symbol is the representation of the connector
symbol.
6.Flow lines: It represents the exact sequence in which instructions are executed. Arrows are
used to represent the flow lines in a flowchart. The symbol given below is used for representing
the flow lines:
7.Hexagon symbol (Flat): It is used to create a preparation box containing the loop setting
statement. The symbol given below is used for representing the Hexagon symbol.
8.On-Page Reference Symbol: This symbol contains a letter inside that indicates the flow
continues on a matching symbol containing the same letters somewhere else on the same page.
The symbol given below is used for representing the on-page reference symbol.
9.Off-Page Reference: This symbol contains a letter inside indicating that the flow continues
on a matching symbol containing the same letter somewhere else on a different page. The
symbol given below is used to represent the off-page reference symbol.
10.Delay or Bottleneck: This symbol is used for identifying a delay in a flowchart. The
alternative name used for the delay is the bottleneck. The symbol given below is used to
represent the delay or bottleneck symbol.
12.Internal storage symbol: The symbol given below is used to represent the internal
storage symbol.
1. Simple
2. Machine Independent or Portable
3. Mid-level programming language
4. structured programming language
5. Rich Library
6. Memory Management
7. Fast Speed
8. Pointers
9. Recursion
10. Extensible
1)Simple: C is a simple language in the sense that it provides structured approach (to break
the problem into parts), rich set of library functions, data types etc.
2)Machine Independent or Portable: Unlike assembly language, c programs can be
executed in many machines with little bit or no change. But it is not platform-independent.
3)Mid-level programming language: C is also used to do low level programming. It is
used to develop system applications such as kernel, driver etc. It also supports the feature of
high level language. That is why it is known as mid-level language.
4)Structured programming language: C is a structured programming language in the
sense that we can break the program into parts using functions. So, it is easy to understand and
modify.
5)Rich Library: C provides a lot of inbuilt functions that makes the development fast.
6)Memory Management: It supports the feature of dynamic memory allocation. In C
language, we can free the allocated memory at any time by calling the free() function.
7)Speed: The compilation and execution time of C language is fast.
8)Pointers: C provides the feature of pointers. We can directly interact with the memory by
using the pointers. We can use pointers for memory, structures, functions, array etc.
9)Recursion: In c, we can call the function within the function. It provides code reusability for
every function.
10)Extensible: C language is extensible because it can easily adopt new features.
P.Madhubabu M.C.A & M.Tech 16
Problem Solving in C B.Sc 1st Year---1st Semester
Q3)Explain the structure of ‘c’ program?
Basic Structure of C Program: Every C program contains a number of several building
blocks known as functions. Each function of it perform task independently. A function is a
subroutine that may consist of one or more statements. A C program may have the following
sections.
1)Documentation Section
2)Link Section
3)Definition Section
4)Global Declaration section
5)Function main()
5.1)Declaration Part
5.2)Executable Part
6)Sub-Program Section
1.Documentation Section: The documentation section consists of a set of comment lines
giving the name of the program. Comments are providing description of the program.
When we write comments, we can understand what the program is doing as well as it
helps others to easily follow our code. This means readability and understandability of a
program will be more.
There are two types of comments in C
➔ Single Line comment
➔ Multi Line comment
Single Line Comment: These comments are for marking a single line as a comment. These
comments start with double slash symbol // and after this, whatever is written till the end of the
line is taken as a comment.
Ex: // this is single comment line.
Multi Line Comment: These comments are used for representing several lines as comments.
These comments start with /* and end with */. In between /* and */, whatever is written is
treated as a multi line comment.
Ex: /*
-------- line1--------
The file which contains c program instructions in high level language is said to be source
code. Every c program source file is saved with .c extension, for example Sample.c.
Whenever we press Alt + F9 the source file is submitted to the compiler. Compiler checks
for the errors, if there are any errors, it returns list of errors, otherwise generates object code in
a file with name Sample.obj and submit it to the linker. Linker combines the code from specified
header file into object file and generates executable file as Sample.exe. With this compilation
process completes.
Now, we need to Run the executable file (Sample.exe). To run a program we press Ctrl
+ F9. When we press Ctrl + F9 the executable file is submitted to the CPU. Then CPU performs
the task according to the instructions written in that program and place the result into
UserScreen.
Then we press Alt + F5 to open UserScreen and check the result of the program.
Q5) Explain about ‘C’ Tokens ?
In a passage of text, individual words and punctuation marks are called tokens or lexical units.
Similarly, the smallest individual unit in a c program is known as a token or a lexical unit. C
tokens can be classified as follows:
1. Keywords
P.Madhubabu M.C.A & M.Tech 20
Problem Solving in C B.Sc 1st Year---1st Semester
2. Identifiers
3. Constants
4. Strings
5. Special Symbols
6. Operators
1.Keywords: The C keywords are reserved words by the compiler. All the C keywords have
been assigned fixed meaning. The keywords cannot be used as variable names because they
have been assigned fixed jobs. The C language has 32 keywords.
These primary data types are divided into 3 categories . They are:
a)Integral Datatypes
b)Floating point Datatypes
c)Character Datatypes
a)Integral Datatypes: Integral data types are used to allocate memory for integer values.
→int, short int, long int are signed datatypes used to store positive values and also negative
values.
→unsigned int, unsigned short int, unsigned long int types allows only positive values.
→These integer datatype can also accepts octal values, hexa decimal values.
signed int – 2bytes -> -32,768 to +32767
unsigned int – 2bytes -> 0 to 65535
Syntax: Datatype variable-name; (or) Datatype identifier;
Ex: int a=26; //decimal representation
int a=032; //octal representation
int a=0x1a; //hexa decimal representation
b)Floating point Datatypes: float, double, long double are the floating datatypes, which are
used to store decimal values. float takes 4 bytes of memory and double takes 8 bytes of
memory it is capable of representing about twice as much precision as a float. The long double
takes 10 bytes of memory.
float pi;
double pi_sqr;
pi = 3.1417;
pi_sqr = pi * pi;
c)Character Data Types: signed char, unsigned char are the character datatypes.
Signed char – 1 byte -128 to +127
Unsigned char – 1 byte 0 to 255
signed char is used to store alphabets and unsigned char is used to store unsigned integer value
upto 255.
It allocates 1 byte memory for single character and also allocate memory for 1 byte to
unsigned integer. In ‘c’ language every character has a decimal value called ASCII(American
Standard Code Information Interchange)
Ex: char ch1 = ‘a’;
unsigned char ch2 = 25;
printf(“%c”,ch1);
printf(“%d”,ch2);
2.UserDefined Datatypes: structures, unions, typedef are examples to Userdefined datatypes.
The c language provides to create your own names for data types with this typedef keyword.
Ex: typedef int integer;
integer a, b;
Makes the name integer a synonym for int. it is used same as int.
The typedef declaration does not create a new type in any sense. It adds a new name for the
existing type. It makes easy to identify which purpose the variable is used.
Q7) Explain about Variables?
Variable: A variable is a name of the memory location. It is used to store data. Its value can
be changed, and it can be reused many times.
It is a way to represent memory location through symbol so that it can be easily identified.
Declaration of a variable:
Synatx: datatype variable1, variable2,…;
Example:
int a; int a,b,c;
float b; (or) float n,m,o;
char c; char x,y,z;
Here, a, b, c are variables. The int, float, char are the data types.
Assinging of Variables:
We can also provide values while declaring the variables as given below:
int a=10,b=20;//declaring 2 variable of integer type
float f=20.8;
char c='A';
Rules for defining variables:
→A variable can have alphabets, digits, and underscore.
→A variable name can start with the alphabet, and underscore only. It can't start with a digit.
→No whitespace is allowed within the variable name.
→A variable name must not be any reserved word or keyword, e.g. int, float, etc.
Valid variable names:
int a;
Flow-chart:
Program: Program to find biggest number from given three numbers using nested-if
#include<stdio.h>
#include<conio.h>
void main()
{
int a,b,c;
clrscr();
printf("enter the a,b,c values\n");
scanf("%d%d%d",&a,&b,&c);
if(a>b)
{
if(a>c)
printf("a is big");
else
printf("c is big");
}
else
{
if(b>c)
printf("b is big");
else
printf("c is big");
}
}
OUTPUT:
enter the a,b,c values: 10 20 30
c is big
Flow-chart:
Example: Program to check whether the given character is capital letter (or) small
letter (or) number (or) a symbol
#include<stdio.h>
#include<conio.h>
void main()
{
char ch;
clrscr();
printf("\n enter any character.....");
scanf("%c",&ch);
if(ch>='A'&&ch<='Z')
printf("%c is a Capital Letter...",ch);
else if(ch>='a' && ch<='z')
printf("%c is a Small Letter...",ch);
else if(ch>='0' &&ch<='9')
printf("%c is a number.....",ch);
else
printf("%c is a symbol....",ch);
getch();
}
OUTPUT:
enter any character.... G
G is a Capital Letter.....
enter any character.. $
P.Madhubabu M.C.A & M.Tech 39
Problem Solving in C B.Sc 1st Year---1st Semester
$ is a symbol......
ii) Branching statements:
Switch Statement: Switch statement takes the given expression and executes the block of the
given expression. If expression not found then executes default block.
Syntax:
switch( expr )
{
case exp1 :
statement1;
break;
case exp2 :
statement2;
break;
.....
.....
case exp_n :
statement-n;
break;
default:
default_statements;
}
Example: Program to read the single digit number and print that digit number into Words
#include<stdio.h>
#include<conio.h>
void main( )
{
int no;
clrscr();
printf("Enter any number:");
scanf(“%d”,&no);
switch(no)
{
case 0: printf("zero");
break;
case 1: printf("two");
break;
case 2: printf("two");
break;
case 3: printf("three");
break;
case 4: printf("four");
break;
case 5: printf("five");
break;
case 6: printf("six");
break;
case 7: printf("seven");
break;
case 8: printf("eight");
break;
P.Madhubabu M.C.A & M.Tech 40
Problem Solving in C B.Sc 1st Year---1st Semester
case 9: printf("nine");
break;
default: printf("Invalid single digit");
}
}
iii)Looping statements: A portion of the program that is executed repeatedly is called a
loop. A looping statement can also be called as iterative statement that executes a set of
statements repeatedly for the specified number of times based upon the given condition. The C
programming language contains three different program statements for program looping. They
are:
a)while loop
b)do while loop
c)for loop
a)while Loop: while loop executes the block number of times until the condition is false.
Syntax: initialisation_section;
while(condition)
{
//statements
Increment/decrement
}
Next_statements;
Flow-chart:
Example: Program to find sum of sequence numbers in a given range using do..while loop
#include<stdio.h>
#include<conio.h>
void main()
{
int i=1,n,sum=0;
clrscr();
printf("How much range you want……");
scanf(“%d”,&n);
do
{
sum=sum+i;
i=i+1;
} while( i<=n);
getch();
}
c)for loop: ‘for’ statement execute the block n number of times until the condition is false.
This for loop statement contains 3 parts. First one is initialization section in this section we can
define the variables which are used in the block, second one is condition, third one is
increment/decrement block
Syntax:
for(initialization ; condition; increment/decrement)
{
//statements;
}
Example: Program to generate the numbers in ascending and descending order in a given
range using for loop
#include<stdio.h>
#include<conio.h>
void main( )
{
int n;
clrscr();
printf("How much range you want……");
scanf(“%d”,&n);
printf(“\nASCENDING ORDER\n”);
printf(“--------------------------------\n”);
for(int i=1;i<=n;i++)
{
printf(“%d\t”,i);
}
printf(“\nDESCENDING ORDER\n”);
printf(“--------------------------------\n”);
for(int i=n;i>=1;i--)
{
printf(“%d\t”,i);
}
getch();
}
/************************************
EXAMPLE FOR goto
*************************************/
#include<stdio.h>
#include<conio.h>
#include<ctype.h>
void main()
{
int no;
char ch;
read:
clrscr();
printf(“Enter the number “);
scanf(“%d”,&no);
if( no % 2 == 0 )
printf(“Given no is even”);
else
printf(“Given no is odd”);
printf(“Do u want to check another no(y/n):”);
ch=getche();
if(ch==’Y’ )
goto read;
}
b)break: Terminates the loop in middle of execution
/*********************************************************
EXAMPLE FOR break
**********************************************************/
#include<stdio.h>
#include<conio.h>
main()
{
int i=0;
while( i<=10 )
{
i++;
P.Madhubabu M.C.A & M.Tech 45
Problem Solving in C B.Sc 1st Year---1st Semester
if(i==5 )
break;
printf(“%3d”,i);
}
printf(“while terminated”);
}
Output:
1234
While terminated
c)continue: used to skip the specific iteration of the loop and continue the next iterations
/*********************************************************
EXAMPLE FOR continue
**********************************************************/
#include<stdio.h>
#include<conio.h>
main()
{
int i;
i = 0;
while( i<=10 )
{
i++;
if(i==5)
continue;
printf(“%3d”,i);
}
}
Output: 1 2 3 4 6 7 8 9 10
d)exit: Terminates the application in middle of execution
/*********************************************************
EXAMPLE FOR exit
**********************************************************/
#include<stdio.h>
#include<conio.h>
#include<stdlib.h>
main()
{
int i=0;
while( i<=10 )
{
i++;
if(i==5 )
exit(0);
printf(“%3d”,i);
}
printf(“program terminated”);
}
Output:
1234
5)return: Terminates the function in middle of execution
/*********************************************************
EXAMPLE FOR ‘return’
**********************************************************/
P.Madhubabu M.C.A & M.Tech 46
Problem Solving in C B.Sc 1st Year---1st Semester
#include<stdio.h>
#include<conio.h>
#include<stdlib.h>
main()
{
int i=0;
while( i<=10 )
{
i++;
return;
printf(“%3d”,i);
}
printf(“program terminated”);
}
Output:
1
a[0]=10;
a[1]=20;
a[2]=30;
a[3]=40;
a[4]=50;
(or)
Declaration with Initialization: We can initialize the array at the time of declaration. Let's
see the code.
Ex2:
int a[5]={10,20,30,40,50};
Note:In such case, there is no requirement to define the size. So it may also be written as the
following code.
Ex3:
int a[]={10,20,30,40,50};
Operation on Array: Following are the various operations supported by an array.
i) Traverse − print all the array elements one by one.
ii) Insertion − add an element at given index.
iii) Deletion − delete an element at given index.
iv) Search − search an element using given index or by value.
v) Update − update an element at given index.
(or)
int a[2][4];
a[0][0]=1; a[0][1]=2; a[0][2]=3; a[0][3]=4;
a[1][0]=5; a[1][1]=6; a[1][2]=7; a[1][3]=8;
Example: Program to initialization of Double Dimensional array and access the values
#include<stdio.h>
#include<conio.h>
main()
{
int i, j;
int a[3][3] = {{1,2,3}, {4,5,6}, {7,8,9]};
printf(“Matrix is\n”);
for( i=0; i<3; i++ )
{
for(j=0; j<3; j++)
{
printf(“%3d”,a[i][j]);
}
printf(“\n”);
}
getch();
}
Example: Program to read matrix row, column sizes and read the matrix values and display the
matrix
#include<stdio.h>
#include<conio.h>
main()
{
int i, j, rows, cols, a[5][5];
clrscr();
printf(“Enter the matrix row, col sizes :”);
scanf(“%d%d”,&rows,&cols);
printf(“Enter a[%d][%d] matrix values :\n“,rows,cols);
P.Madhubabu M.C.A & M.Tech 50
Problem Solving in C B.Sc 1st Year---1st Semester
for( i=0; i<rows; i++ )
{
for( j=0; j<cols; j++ )
{
scanf(“%d”,&a[i][j]);
}
}
printf(“The Matrix is….. \n”);
for( i=0; i<rows; i++ )
{
for( j=0; j<cols; j++ )
{
printf(“%3d”,a[i][j]);
}
printf(“\n”);
}
getch();
}
(Or)
int a[2][3][3]= {
{ {1,2,3},{4,5,6},{7,8,9} } ,
{ {1,2,3}, {4,5,6}, {7,8,9} }
};
→If the string is shorter than the specified array size, the remaining elements of the array are
initialized to space.
Declaring Pointer Array: We may also initialize a char pointer with a string constant.
Example: char *ptr = “Hello”;
→All subsequent uses of the array name refer to the address of the array’s initial element. This
address as we said before cannot be changed. The pointer is a variable that is initialized with the
address of the array’s initial element. However we can assign a different address value to the
pointer. In this case the address with which it was initialized will be lost.
Note: Char array always refers to first value of the string. But pointer holds the address of
string. So we can modify the value of pointer but not modify the data in char[].
Rule for Declaring Array:
char st[]=”madhu”; //correct
st=”madhu”; //error
char *st=”madhu”;
st=”madhu”; //correct
Example-1: Program to assign the string into character array variable and print the string.
#include<stdio.h>
#include<conio.h>
main()
{
char st[6]={'m','a','d','h','u'};
int i;
clrscr();
for( i=0; i<6; i++ )
P.Madhubabu M.C.A & M.Tech 57
Problem Solving in C B.Sc 1st Year---1st Semester
printf("%c",st[i]);
getch();
}
Example-2: Program to assign the string into variable and print the string.
#include<stdio.h>
#include<conio.h>
main()
{
char st[]=”madhu”;
int i;
for( i=0; st[i]!=’\0’; i++ )
printf("%c",st[i]);
}
Example-3: Program to assign the string into variable and print the string.
#include<stdio.h>
#include<conio.h>
main()
{
char st[]=”madhu”;
int i;
clrscr();
printf(“%s”,st);
getch();
}
Example-4: Program to assign the string into character pointer variable and print the string.
#include<stdio.h>
#include<conio.h>
main()
{
char *st=”madhu”;
clrscr();
printf(“%s”,st);
getch();
}
Two dimensional array of characters: One character array is equal to one string. If we
want to store no. of strings into char variable we use two dimensional array.
Example:
char st[10]=”madhu”; //single array
3.Function Call: The function call tells the compiler when to execute the function
definition. When a function call is executed, the execution control jumps to the function
definition where the actual code gets executed and returns to the same functions call once the
execution completes. The function call is performed inside main function or inside any other
function or inside the function itself.
Function call syntax:
functionName(parameters);
Advantages of Functions:
1. Using funcions we can implement modular programming.
2. Functions makes the program more readable and understandable.
3. Using functions the program implementation becomes easy.
4. Once a function is created it can be used many times (code re-usability).
5. Using functions larger program can be divided into smaller modules.
C Header Files
2.User Defined Functions: In C programming language, users can also create their own
functions. The functions that are created by users are called as user defined functions. The user
defined function is defined as follows...
Example:
#include<stdio.h>
#include<conio.h>
void main()
{
int num1,num2,result;
int addition(int,int); // function declaration
clrscr();
printf("Enter any two integer numbers:") ;
scanf("%d%d",&num1,&num2);
result=addition(num1,num2); // function call
printf("SUM = %d", result);
getch() ;
}
int addition(int a,int b) // function definition
{
return a+b ;
}
Example:
#include <stdio.h>
#include<conio.h>
void main()
{
void addition() ; // function declaration
clrscr() ;
addition() ; // function call
getch() ;
}
void addition() // function definition
{
int num1, num2 ;
printf("Enter any two integer numbers : ") ;
scanf("%d%d", &num1, &num2);
printf("Sum = %d", num1+num2 ) ;
}
Example:
#include <stdio.h>
#include<conio.h>
void main()
{
int num1, num2 ;
void addition(int, int) ; // function declaration
clrscr();
printf("Enter any two integer numbers : ") ;
scanf("%d%d", &num1, &num2);
addition(num1, num2) ; // function call
getch() ;
}
void addition(int a, int b) // function definition
{
printf("Sum = %d", a+b ) ;
}
Example:
#include <stdio.h>
#include<conio.h>
void main()
{
int result ;
int addition() ; // function declaration
clrscr() ;
Example:
#include <stdio.h>
#include<conio.h>
void main()
{
int num1, num2, result ;
int addition(int, int) ; // function declaration
clrscr() ;
printf("Enter any two integer numbers : ") ;
scanf("%d%d", &num1, &num2);
result = addition(num1, num2) ; // function call
printf("Sum = %d", result) ;
getch() ;
}
int addition(int a, int b) // function definition
{
return (a+b) ;
}
→In the above example program, the variables num1 and num2 are declared as global
variables. They are declared before the main() function. So, they can be accessed by function
main() and other functions that are defined after main(). In the above example, the functions
main(), addition(), can access the variables num1 and num2.
2)Inside the function or block (Local Declaration): Declaring a variable inside the
function or block is called local declaration. The variable declared using local declaration is
called local variable. The local variable can be accessed only by the function or block in which it
is declared. That means the local variable can be accessed only inside the function or block in
which it is declared.
Example Program:
#include<stdio.h>
#include<conio.h>
void main()
{
void addition() ;
int num1,num2 ;
clrscr() ;
num1=10 ;
num2=20 ;
printf("num1=%d, num2=%d",num1,num2) ;
addition() ;
getch() ;
P.Madhubabu M.C.A & M.Tech 67
Problem Solving in C B.Sc 1st Year---1st Semester
}
void addition()
{
int sumResult ;
sumResult=num1+num2;
printf("\naddition=%d",sumResult) ;
}
→The above example program shows an error because, the variables num1 and num2 are
declared inside the function main(). So, they can be used only inside main() function and not in
addition() function.
3)In the function definition parameters (Formal Parameters): The variables declared
in function definition as parameters have a local variable scope. These variables behave like
local variables in the function. They can be accessed inside the function but not outside the
function.
Example Program:
#include<stdio.h>
#include<conio.h>
void main()
{
void addition(int,int) ;
int num1,num2 ;
clrscr() ;
num1=10 ;
num2=20 ;
addition(num1,num2) ;
getch() ;
}
void addition(int a,int b)
{
int sumResult;
sumResult=a+b;
printf("\naddition=%d",sumResult) ;
}
→In the above example program, the variables a and b are declared in function definition as
parameters. So, they can be used only inside the addition() function.
Q4)Explain about Storage Classes in ‘C’?
Storage class tells us:
1. Where the variable would be stored.
2. What will be the initial value of the variable, if the initial value is not specifically assigned
(i.e. the default initial value).
3. What is the scope of the variable; i.e., in which functions the value of the variable would be
available.
4. What is the life of the variable; i.e., how long would the variable exist.
There are four storage classes
1. Automatic variables.
2. External variables.
3. Static variables.
4. Register variables.
1)Automatic Variables: ‘auto’ is a keyword which defines the local variable and having
a local lifetime. This is the default for local variables and therefore is rarely used. If we not
initialize the values into automatic variables it stores garbage values(which are not expected).
Syntax: [auto] <data definition>;
Ex: auto int a=10;
int b=20; //default is auto
Automatic variables are declared inside the function in which they are to be utilized. They
are created when the function is called and destroyed automatically when the function is exited,
hence the name automatic. Automatic variables are private to that function. Because of this
property, automatic variables are also referred to as local or internal variables.
Variables, which are declared in local scope with out storage classes, are ‘automatic’ by
default. One important feature is that their value cannot be changed accidentally by what
happens in some other function in the program and without causing any confusion to the
compiler.
Example: Program for AUTOMATIC variables
#include<stdio.h>
#include<conio.h>
auto int x=20; //wrong
void main()
{
auto int a=10; // Explicitly declared as auto.
int b=20; // Implicitly auto.
printf(“a=%d, b=%d”,a,b);
}
2)External Variables: If we define the variables with ‘extern’ keyword that variables are
called ‘Extern variables’. Extern variables are used in different source files. It doesn’t allocate the
memory every time whenever it defines no. of times. It allocates the memory only one time at
first time it initialized. From second time onwards it refers the first address. Extern variable
treated as like global any where it can access, mainly it can access in any function in current file
or in another file. By default extern variables are initialized with zero.
Ex: extern int a=5;
There is one important point to remember that is inside a function the following statement is
unacceptable.
extern int x = 5, //WRONG
Example: Program for EXTERN variable
//first.c
#include<stdio.h>
P.Madhubabu M.C.A & M.Tech 69
Problem Solving in C B.Sc 1st Year---1st Semester
#include<conio.h>
#include"second.c"
extern int a;
void func1()
{
a++;
printf("a=%d\n",a); //a=11
}
int a=10;
void func2()
{
a++;
printf("a=%d\n",a); //a=12
}
void main()
{
clrscr();
func1();
func2();
func3();
getch();
}
//second.c
int a;
void func3()
{
a++;
printf("a=%d\n",a); //a=13
}
3)Static Variables: Static keyword can be applied to variables and also to functions. If we
define the variable as static in file level that variables data can be accessible in all functions. if we
define the variable as static in function level that variable can accessible in that function inner
blocks, not accessible in outside functions. Static is treated as global. By default all functions are
treated as global. Static variables are initialized with 0 by default.
Syntax:
static<data definition>;
static<function definition>;
Example: Program for STATIC variable
#include<stdio.h>
#include<conio.h>
void func1();
void func2();
void func3();
void func4();
static int a; //static variable declaration
void main()
{
a=10;
func1();
func2();
func3();
P.Madhubabu M.C.A & M.Tech 70
Problem Solving in C B.Sc 1st Year---1st Semester
func4();
}
void func1()
{
a++;
printf("a=%d\n",a); //a=11
}
void func2()
{
a++;
printf("a=%d\n",a); //a=12
}
void func3()
{
static int b=20; //local static variable
b++;
printf("b=%d\n",b); //b=21
{
b++;
printf("b=%d\n",b); //b=22
}
}
void func4()
{
printf("a=%d\n",a);
printf("b=%d\n",b); //error
}
4)Register Variables: It is possible for use to attribute the register storage class to certain
variables. We can tell the compiler that variable should be kept in one of the machine’s register,
instead of keeping in the memory (where normal variables are stored). Since a register access is
mach faster than a memory access, keeping the frequently accessed variables in the register will
lead to faster execution of programs. This is done as fOllows:
Ex: register int count;
The important point while using register variables is, register of CPU do not have addresses.
Thus, we should not refer the address of a register variable.
Every computer has a limited number of registers, which are storage area within the
CPU. Each register is capable of holding a unit of data (typically two or four bytes) and
arithmetic calculations are processed using these registers.
Example: Program for REGISTER variables
#include<stdio.h>
#include<conio.h>
void main()
{
register int a, b;
int c;
clrscr();
a=10, b=20;
c = a + b;
printf("result=%d",c);
getch();
}
Output:
Enter any positive integer: 3
Factorial of 3 is 6
In the above example program, the factorial() function call is initiated from main()
function with the value 3. Inside the factorial() function, the function calls factorial(2),
factorial(1) and factorial(0) are called recursively. In this program execution process, the
function call factorial(3) remains under execution till the execution of function calls factorial(2),
factorial(1) and factorial(0) gets completed. Similarly the function call factorial(2) remains under
execution till the execution of function calls factorial(1) and factorial(0) gets completed. In the
same way the function call factorial(1) remains under execution till the execution of function call
factorial(0) gets completed. The complete execution process of the above program is shown in
the following figure...
Pros (Advantages) of Recursion:
• It is simple, easily understandable, concise, compact and transparent to view a c
program.
• Lesser number of programming statements (coding) required with the use of recursion.
• It is very useful in solving mathematical (factorial, GCD, fibbonacci series etc.),
trigonometric (compute hyperbolic trigonometric value), logical games (tower of Hanoi,
Example:
struct Employee
{
int eid;
char ename[20];
double salary;
};
Initialization of structures:
struct student
{
int a;
char name[70],gender;
float height;
} x={786,”kumar”,’m’,5.8};
Creating Structure Object: If we create the variables to struct type that variables are
called as objects. These objects are used to store the values. We can create any no. of objects to
the structure type. Each object can hold different values.
Syntax: structvariable.membername;
Ex: v1.structure-element-1;
scanf(“%d%s%f”,&v1.eid,v1.ename,&v1.salary);
Array of Structure: Declaring an array of structure is same as declaring an array of
fundamental types. Since an array is a collection of elements of the same type. In an array of
structures, each element of an array is of the structure type.
Example:
struct car
{
char make[20];
char model[30];
int year;
};
Initializing Array of Structures: We can also initialize the array of structures using the same
syntax as that for initializing arrays. Let's take an example:
struct car
{
char make[20];
char model[30];
int year;
P.Madhubabu M.C.A & M.Tech 75
Problem Solving in C B.Sc 1st Year---1st Semester
};
struct car arr_car[2]={
{"Audi", "TT", 2016},
{"Bentley", "Azure", 2002}
};
Structure and Function: Structure can be implemented with the function easily. For this
process, passing of argument takes place similar to the array and variable. The relationship of
structure with the function can be viewed from three angle as:
i). Passing Structure to a Function
ii). Function Returning Structure
iii). Passing array of Structure to Function
ii). Function Returning Structure: All the values can be computed in the function programs
and return a combined value of whole structure back. This can be explained with a simple
problem to compute the net pay of an employee having structure as:
Example: Program to illustrate the concept of Function returning a Structure computed value
#include<stdio.h>
struct employee
{
char name[20]; float bp, da, hra, netpay;
}emp;
struct employee npay(struct employee);
void main( )
{
struct employee y;
printf("\n ENTER THE NAME, BASIC PAY, DA, HRA:");
scanf("%f%f%f", &y.bp, &y.da, &y.hra);
y=npay(y);
printf("\n Net pay is:%f ",y.netpay);
getch( );
}
struct employee npay(struct employee z)
{
z.netpay=z.bp+z.da+z.hra;
return(z);
}
Self referential structures: Self referential structures are those structures that contain a
refrence to data of its same type.ie in addition to other data, a self referential structure contains
a pointer to a data that is of the same type as that of the structure.
Ex:
struct node
{
Int val;
struct node *next;
};
Node contains 2 types one is integer val and next, which is a pointer to a node.
Q8)Explain Unions in C ?
A union is a variable that declares a set of multiple variables (called members or elements
having different data-types) sharing the same memory area. The compiler allocates sufficient
memory to hold the largest variable of the union.
All the members of union occupy the same memory locations called addresses. The old
value of the already declared member will be destroyed and new value to the new member will
be assigned in the memory by using the union concept.
Note that union declaration has more than one variable declaration, but only one can be
used at a time. Also with the declaration of union, the Turbo-C compiler will automatically
allocates the memory locations to the variable which has the long data type member element in
the union (i.e. the priority list be : double, long- float, float, long int, int, char).
Declaration of union: The general syntax used for the declaration of union be as follows:
Syntax: union union-tag
{
data type-1 member-element-1;
…………………..
dart type-n member-element-n;
}vl,v2 .... vn;
Example:
P.Madhubabu M.C.A & M.Tech 79
Problem Solving in C B.Sc 1st Year---1st Semester
void main()
{
//declaration of student array.
union student s[10];
}
Unions inside structures: Generally, unions can be very useful when declared inside a
structure.
Ex:
struct student
{
union
{
char name[80];
int rno;
};
int marks;
};
The fields of union will share memory, so in the main program we ask the user which data
he/she would like to store and depending on his/her choice the appropriated field is used.
The syntax for declaring enumeration types is to start with the enum keyword followed
by the list of constant names enclosed in braces, followed by the names of the enum types.
Ex:
enum choice
{
FALSE=0,
TRUE=1
}ch;
Note: In the above example ch is a variable to type choice. That variable only allows either
0 or 1.
0’s Constant is FALSE, 1 constant is TRUE.
Constant names in an enum declaration receive a default integer value based on their
position in the enumeration list. In most cases, the integer value is not important because you
are treating the enumeration as a unique value.
For example, we declare two enumeration variables called color and intensity. Color
can be assigned one of four constant values: red, blue, green, and yellow. Intensity can be
assigned one of three constant values: bright, medium and dark.
color = yellow; /* ok */
color = bright ; /* type conflict */
intensity = bright; /* ok */
intensity = blue; /* type conflict */
The default values start at zero and go up by one with each new name. In the
declaration of color, for instance, red, blue, green and yellow represent the integer values 0, 1,
2, and 3 respectively. The compiler need only allocates as much memory as is necessary for an
enum value. The potential values of color are small enough that only one byte is needed for
the variable.
enum { A, B, C, D, E }
0 1 2 3 4
enum { A=10, B, C, D, E }
10 11 12 13 14
enum { A, B=10, C, D=20, E }
0 10 11 20 21
enum { A, B, C=-5, D, E }
0 1 -5 -4 -3
Example: Program on Enumerated datatypes.
#include<stdio.h>
#include<conio.h>
enum{SUNDAY=1,MONDAY,TUESDAY,WEDNESDAY,THURSDAY,FRIDAY,SATURDAY } day;
enum{NO,YES}choice;
void main()
{
READ:
clrscr();
printf("Enter the week day (1..7): ");
scanf("%d",&day);
switch( day )
{
case SUNDAY: printf("day is Sunday"); break;
case MONDAY: printf("day is Monday"); break;
case TUESDAY: printf("day is Tuesday"); break;
case WEDNESDAY: printf("day is Wednesday"); break;
case THURSDAY: printf("day is Thursday"); break;
case FRIDAY: printf("day is Friday"); break;
case SATURDAY: printf("day is Saturday"); break;
default: printf("Invalid day");
}
printf("\n Do u want to continue(1/0) :");
scanf("%d",&choice);
if(choice==YES) goto READ;
}
printf(“address is %u”,p);
printf(“value is %d”,*p;
Uses of Pointers:
➢ Pointers provide a powerful and flexible method for manipulating the data of the
variables.
➢ Pointer is more efficient in handling arrays and different types of data.
➢ Pointers can be used to return multiple values from a function via function arguments.
➢ Pointers permit references to functions and they’re by facilitating passing of functions as
arguments to other functions.
➢ Pointers allow C to support dynamic memory management.
➢ Pointers reduce length and complexity of programs.
➢ They increase the execution speed and thus reduce the program execution time.
Example: Program to illustrate the concept of displaying the address of a Pointer variable
main ( )
{
int x, *q;
x = 220;
q=&x;
printf ("\n % d is stored at address % u", x, &x)
printf ("\n % d is stored at address % u", x, q) ;
printf ("\n % d is stored at address % u", * q, q)
printf ("\n % d is stored at address % u", * & x, &x)
getche ( );
}
Output:
220 is stored at address 5010
220 is stored at address 50 10
220 is stored at address 50 10
P.Madhubabu M.C.A & M.Tech 83
Problem Solving in C B.Sc 1st Year---1st Semester
220 is stored at address 5010
Output: SUM=5
MUL=10
DIV=-21
c may add or subtract integers from pointers. We can also subtract one pointer from the other.
We can also use short hand operators with the pointer variables as we use with other variables.
C also allows to compare pointers by using relational operators in the expression.
Ex: p1>p2, p1==p2.
Rules:
1) A pointer vaiable can be assigned the address of another variable.
2) It can be assigned the value of another pointer variable
3) It can be initialized with a NULL( OR 0) value.
4) Prefix or postfix increment and decrement operators can be applied on a pointer
variable.
5) A pointer variable cannot be multiplied by a constant.
6) A pointer variable cannot be added to another pointer variable
7) An integer value can be added or subtracted from a pointer variable
8) Pointer variable can be compared with another pointer variable of the same type using
relational operators.
Pointer arithmetic: A pointer in c is an address, which is a numeric value. Therefore, you can
perform arithmetic operations on a pointer just as you can on a numeric value. There are four
arithmetic operators that can be used on pointers: ++, --, +, and –
To understand pointer arithmetic, let us consider that ptr is an integer pointer which
points to the address 1000. Assuming 32-bit integers, let us perform the following arithmetic
operation on the pointer:
ptr++
Here variable arr will give the base address, which is a constant pointer pointing to the first
element of the array, arr[0]. Hence arr contains the address of arr[0] i.e 1000. In short, arr has
two purpose - it is the name of the array and it acts as a pointer pointing towards the first
element in the array.
int *p;
p = arr;
// or,
p = &arr[0]; //both the statements are equivalent.
Now we can access every element of the array arr using p++ to move from one element to
another.
NOTE: You cannot decrement a pointer once incremented. p-- won't work.
Pointer to Array: As studied above, we can use a pointer to point to an array, and then we
can use that pointer to access the array elements. Lets have an example,
#include <stdio.h>
int main()
{
int i;
int a[5] = {1, 2, 3, 4, 5};
int *p = a; // same as int*p = &a[0]
for (i = 0; i < 5; i++)
{
printf("%d", *p);
p++;
}
return 0;
}
In the above program, the pointer *p will print all the values stored in the array one by one.
We can also use the Base address (a in above case) to act as a pointer and print all the values.
Array of Pointers: We can also have array of pointers. Pointers are very helpful in handling
character array with rows of varying length.
char *name[3] = {"Adam","chris","Deniel"};
//Now lets see same array without using pointer
char name[3][20] = { "Adam", "chris", "Deniel"};
Now let's have a quick look at the methods used for dynamic memory allocation.
malloc() allocates single block of requested memory.
calloc() allocates multiple block of requested memory.
realloc() reallocates the memory occupied by malloc() or calloc() functions.
free() frees the dynamically allocated memory.
1)malloc() Method: malloc” or “memory allocation” method in C is used to dynamically
allocate a single large block of memory with the specified size. It returns a pointer of type void
which can be cast into a pointer of any form. It initializes each block with default garbage value.
Syntax: ptr=(cast-type*)malloc(byte-size)
Drawbacks of pointers in c:
1. Uninitialized pointers might cause segmentation fault.
2. Dynamically allocated block needs to be freed explicitly. Otherwise, it would lead to
memory leak.
P.Madhubabu M.C.A & M.Tech 92
Problem Solving in C B.Sc 1st Year---1st Semester
3. Pointers are slower than normal variables.
4. If pointers are updated with incorrect values, it might lead to memory corruption.
Basically, pointer bugs are difficult to debug. Its programmers responsibility to use pointers
effectively and correctly.
Where,
3.Reading from file (fscanf or fgets): Following are the list of functions which are used
for reading a file:
Functions Syntax Description
fscanf( ) int fscanf (FILE *stream, const It is used for reading the formatted data from
char *format,....); the stream.
fgets( ) char *fgets(char *str, int size, It stands for file get string. It is used for getting
FILE *stream); the string from a stream.
fgetc( ) int fgetc (FILE *stream); It will return the next character from the stream
from the end of the file or an error.
fread( ) int fread(void *str, size_t size, It is used for reading data from a file.
size_t num, FILE *stream);
4.Writing to a file (fprintf or fputs): Following are the list of functions which are used for
writing a file:
Functions Syntax Description
fprintf() int fprintf (FILE *stream, const It is used for writing the formatted output of the
char * format,...); stream.
fputs() int fputs(const char *str, FILE It is used for writing a line to a file.
*stream);
fputc() int fputc(int c, FILE *stream); It is opposite to fgetc() and is used for writing a
character to the stream.
fwrite() int fwrite(const void *str, It is used for writing data to a file.
size_t size, size_t count, file
*stream);
6.Closing a file (fclose): To close a file, use the fclose( ) function. The prototype of this
function is:
int fclose( FILE *fp );
→This function returns 0 if there are no errors and a value if there are some errors.
→Following are the functions which are used for detecting the errors:
→Each element of the array argv is a pointer where each pointer points to a string.
In main() the command line arguments are accepted by using the argc and argv.
Example: Write a program for reading a file character by character and display it on the
screen.
#include <stdio.h>
#include <string.h>
void main()
{
FILE *fp;
int c;
char fnm[25];
printf("\n Enter a filename:");
scanf("%s",fnm);
fp = fopen(fnm, "r");
if (fp==NULL)
{
printf("\n Error in opening the file");
exit(1);
}
c=fgetc(fp);
while(c!=EOF)
{
putchar(c);
c =fgetc(fp);
}
fclose(fp);
}
Q12)What are the input and output statements used in file handling?
Files have different Input/output statements used for different purposes. These are used
to put data from variable to data file. The various Input/output functions used with standard
1/0 are discussed as below:
a). Character Input/Output (Standard I/O)
b). String Input/Output (Standard I/O)
c). Formatted Input/Output (Standard I/O)
d). Record (Block) Input/Output (Standard I/O)
a). Character Input/Output Functions:
Now there need to be handle character data by using the following high-level
input/output functions. There are mainly four character 1/0 used which are discussed as:
1. putc( )
2. getc( )
3. putw( )
4. getw( )
1.putc(): This function is used to put or write a single character in the data file pressed from
the keyboard. The general syntax used is as:
putc (v,file-pointer);
P.Madhubabu M.C.A & M.Tech 96
Problem Solving in C B.Sc 1st Year---1st Semester
Here putc( ) is the high level character 1/0 function used in the C-Language, v is variable name
of character type. Note that when you use putc (), file should be open in "w" mode. It means a
new file will be created or it overwrites the data to an existing created file.
2.getc(): The purpose of getc( ) function is to read a single character from the existing data
file. The general syntax used for this purpose is as:
v = getc(fp);
Where fp is the file pointer, v is the character type variable and getc( ) is the high-level
input/output function used for reading the character data. Note that the file should be opened
in the read mode only and also file should be already created. Also note that data be stored in
the file before reading, otherwise it shows the empty space.
Example: Program for copy one file into Another File
#include<stdio.h>
#include<conio.h>
#include<ctype.h>
void main()
{
FILE *f1,*f2;
char c,k;
clrscr();
f1=fopen("sai","w");
printf("ENTER INTO FILE\n");
while((c=getchar())!=EOF)
putc(c,f1);
fclose(f1);
f1=fopen("sai","r");
f2=fopen("duplicate","w");
while((c=getc(f1))!=EOF)
putc(c,f2);
fclose(f1);
fclose(f2);
f2=fopen("duplicate","r");
printf("COPIED FILE\n");
while((c=getc(f1))!=EOF)
{
k=toupper(c);
printf("%c",k);
}
fclose(f2);
getch();
}
3.putw(): This function is used to put or write a single integer digit in the data file pressed
from the keyboard. Note that when you use putw( ) function, file should be opened in the "w"
mode. The general syntax used for this statement is as:
putw (v,file-pointer);
Here v is the integer variable name.
4.getw(): The purpose of getw( ) is to read a single integer value from the data file. The
general syntax is as:
v = getw (fl);
Here v is the integer variable and fl is the file pointer, getw( ) is the high level input/output
function.
Example: Program to check EVEN (or) ODD numbers in the files
#include<stdio.h>
#include<conio.h>
void main()
P.Madhubabu M.C.A & M.Tech 97
Problem Solving in C B.Sc 1st Year---1st Semester
{
FILE *f1,*f2,*f3;
int n,i;
clrscr();
f1=fopen("data","w");
printf("enter in file1\n");
for(i=1;i<=100;i++)
{
scanf("%d",&n);
if(n==-1)
break;
else
putw(n,f1);
}
fclose(f1);
f1=fopen("data","r");
f2=fopen("even","w");
f3=fopen("odd","w");
while((n=getw(f1))!=EOF)
{
if(n%2==0)
putw(n,f2);
else
putw(n,f3);
}
fclose(f1);
fclose(f2);
fclose(f3);
printf("EVEN NOS\n");
f2=fopen("even","r");
while((n=getw(f2))!=EOF)
printf("%4d",n);
fclose(f2);
printf("\n");
printf("ODD NOS\n");
f3=fopen("odd","r");
while((n=getw(f3))!=EOF)
printf("%4d",n);
fclose(f3);
getch();
}
b). String Input/Output: Strings are the major element of the character data, which can be
handled by the files. It is very easy to handle group of characters instead if individual character
using the file operations. There are mainly two types of string 1/0 functions used. These are as
follows:
1. fputs() 2. fgets()
1.fputs(): The purpose of this file is to write a string to the opened file in write mode. The
general syntax used is as follows:
fputs(ab, fp);
Where fp is the file pointer and A is a pointer, which points to an array of characters. For
example, below written are the valid statements for the proper use of fputs().
FILE *fp;
char ab[20];
P.Madhubabu M.C.A & M.Tech 98
Problem Solving in C B.Sc 1st Year---1st Semester
fp =fopen( "Mona", "w");
fputs(ab,fp);
Example: Program to illustrate the concept of writing the string by using the fputs()
main( )
{
FILE *f;
char xy[50];
printf("\n Enter any string from the keyboard “);
gets(xy);
f = fopen("Mona", "W");
fputs( xy, f);
fclose(f);
getche( );
}
Output:
Enter any string from the keyboard: Madhu
2.fgets(): The purpose of this file is to read a string from the opened file in read mode. The
general syntax used is as follows:
fgets (ab, n, fp);
Where fp is the file pointer, ab is a pointer, which points to an array of characters and n
is the length of the array (size of the array). For example, below written are the valid statements
for the proper use of gets FILE *fp; char ab[20]; int n; printf("\n Enter the value of n:");
scanf("%d", &n); fp =fopen( "Mona", "r"); fgets(ab, n, fp); This can be further explained by
taking an example of a C program as:
Example: Program to illustrate the concept of reading a string by using the fgets()
main( )
{
FILE *f;
char xy[50], ab[50];
int i=0;
printf("\n Enter any string from the keyboard “);
gets(xy);
f = fopen("Mona", "w");
fputs( xy, f);
fclose(f);
f = fopen("Mona", "r");
printf("\n Entered string is “);
if(fgets(ab,50,fp) !='\0')
{
while(ab[i] !='\0')
{
putchar(ab[i]);
i++;
}
}
fclose(f);
getche( );
}
Output:
Enter any string from the keyboard: Raj Kumar
Entered string is : Raj Kumar
P.Madhubabu M.C.A & M.Tech 99
Problem Solving in C B.Sc 1st Year---1st Semester
c)Formatted Input/Output:
We have discussed here character 1/0 and string 1/0 function to enter single character and
group of character data. Now question arises how can you handle mixed data. i.e. data of
integer, float, double and character type. The answer is the formatted Input/Output functions.
There are mainly two formatted 1/0 functions are used, which are discussed as below:
1. fscanf ( )
2. fprinff ( )
1.fprintf(): The function fprintf( ) is to write mixed data type in the data file. The mixed data
type are of integer, float, double, string and character type. The general syntax used for this
purpose is as follows:
fprintf (fp, "Control String", V1, V2,…… Vn);
Where fp is the file pointer, control string has all format codes or character conversion
codes (like % d for integer, %f for float value, % s for the string data, % c for character only
etc.), which are used for the output statement. Here V1, V2,… vn is the list of variable. Note
that the file should be opened in the write mode. For example, Write a C-program to explain
the concept of fprintf I/O function as:
2.fscanf(): The purpose of this function is to read mixed data from the data file. Note that file
should be opened in the read mode only. The general syntax used for this function is as follows:
fscanf (fp, "Control String ", & v1, & v2 ,…& vn);
Where fp is the file pointer, control strings are %d for the integer data, %f for the float
data, %s for the string , %c for the single character data etc. Here vl, v2......... vn are all the
variables. Also here &(Ampersand sign) is used to read data at the address of the memory cells.
For example, If you want to read data of different data-types, then a C program procedure be
used as below:
Example: Program for fscanf() and fprintf()
#include <stdio.h>
#include <conio.h>
#include <string.h>
struct person
{
char name[20];
long telno;
};
void appendData()
{
FILE *fp;
struct person obj;
clrscr();
fp=fopen("data.txt","a");
printf("*****Add Record****\n");
printf("Enter Name : ");
scanf("%s",obj.name);
printf("Enter Telephone No. : ");
scanf("%ld",&obj.telno);
fprintf(fp,"%20s %7ld",obj.name,obj.telno);
fclose(fp);
}
void showAllData()
{
FILE *fp;
struct person obj;
clrscr();
fp=fopen("data.txt","r");
P.Madhubabu M.C.A & M.Tech 100
Problem Solving in C B.Sc 1st Year---1st Semester
printf("*****Display All Records*****\n");
printf("\n\n\t\tName\t\t\tTelephone No.");
printf("\n\t\t=====\t\t\t===============\n\n");
while(!feof(fp))
{
fscanf(fp,"%20s %7ld",obj.name,&obj.telno);
printf("%20s %30ld\n",obj.name,obj.telno);
}
fclose(fp);
getch();
}
void findData()
{
FILE *fp;
struct person obj;
char name[20];
int totrec=0;
clrscr();
fp=fopen("data.txt","r");
printf("*****Display Specific Records*****\n");
printf("\nEnter Name : ");
scanf("%s",&name);
while(!feof(fp))
{
fscanf(fp,"%20s %7ld",obj.name,&obj.telno);
if(strcmpi(obj.name,name)==0){
printf("\n\nName : %s",obj.name);
printf("\nTelephone No : %ld",obj.telno);
totrec++;
}
}
if(totrec==0)
printf("\n\n\nNo Data Found");
else
printf("\n\n===Total %d Record found===",totrec);
fclose(fp);
getch();
}
void main()
{
char choice;
while(1)
{
clrscr();
printf("*****TELEPHONE DIRECTORY*****\n\n");
printf("1) Append Record\n");
printf("2) Find Record\n");
printf("3) Read all record\n");
printf("4) exit\n");
printf("Enter your choice : ");
fflush(stdin);
choice = getche();
switch(choice){
case'1' : //call append record
P.Madhubabu M.C.A & M.Tech 101
Problem Solving in C B.Sc 1st Year---1st Semester
appendData();
break;
case'2' : //call find record
findData();
break;
case'3' : //Read all record
showAllData();
break;
case'4' :
case 27 : exit(1);
}
}
}
d). Record Input/Output (Block I/O):
The purpose of this function is to read and write the data at once i.e. used to read or
write the entire block (group of records) using the permanent disk storage device. Every blocks
has some fixed size and works similar to an array or a structure. This is mainly used to write the
numeric data (integer, long integer, float and double) to the disk file in the binary format. For
this purpose mainly two record input/output functions are used. These are discussed in detail as
follows:
1. fwrite ( )
2. fread ( )
1.fwrite(): The purpose of this function is to write group of record (block) to a data file on the
secondary storage device disk. The general syntax used for this purpose is:
fwrite (p, n, s, fp);
Where p is an address of an array or structure (the pointer to array of structure), n is the
size of array or structure, s is the number of array or structure declared for writing the data and
fp is a file pointer. File should be opened in binary write mode. For example, write a C
program to explain the working of fwrite( ) function.
2. fread(): The purpose of this function is to read group of record (block) from the existing
created data file stored on the secondary storage device disk. The general syntax used for this
purpose is:
fread(p, n, s,fp);
Where p is an address of an array or structure (the pointer to array of structure) where
block will be stored after reading, n is the size of array or structure, s is the number of array or
structure declared for writing the data and fp is d file pointer. For example, write a C program
to explain the working of fread( ) function. File should be opened in binary read mode. This
can be done as follows: