UNIT 4 Programming in C
UNIT 4 Programming in C
com
Computer Science
Grade: XII
Programming in c
Reference Note
1. Write a program to input any three numbers and find out which one is largest numbers.
2. Write a program to display day using the switch statement depending upon the number entered.
i.e. input 1 for Sunday, 7 for Saturday.
3. Write a program to input a number and check whether it is prime or not.
4. Write a program to display the sum of even and odd numbers from 1 to 50.
5. Write a program to accept the age of 10 different employees and count the number of employee.
a. Whose age is more than or equal to 60
b. Whose age is less than 35
6. Write a program to enter elements for 3x3 matrixes and Display its sum.
7. Write a program to accept 10 different numbers in array and sort in descending order.
8. Write a program to input a number and find out that number is palindrome or not.
9. Write a program to input the names of N numbers of students and sort them in alphabetical order.
10. Write a program to read a number and make the sum of individual digits and print using recursion
technique.
11. Write a program that reads different names and address into the computer and rearrange the
names into alphabetical order using the structure variables.
12. Write a program to read N students record store them in data file and display the content in
appropriate format by using fprintf and fscanf function.
Unit 4- Programming in C
What is C? Explain its development process.
C is a high level language because no need for any architecture knowledge in normal English form.
C is a compiler because it can translate the whole program at a time so we can call compiler. C is structured
programming language. It is called also procedural oriented programming language, function oriented
language, module programming language. It is simple, reliable and easy to use.
What are the features of C? What are its advantages and disadvantages?
C is a computer language and a programming tool which has grown popular because programmers
preferred it. It is a tricky language but a masterful one.
The C programming languages has the following features:
i) It has small size.
ii) It has extensive use of function call.
iii) It is a strong structural language having powerful data definition methods.
iv) It has low level (Bit Wise) programming available.
v) It can handle low level activities.
vi) Pointer makes it very strong for memory manipulations.
vii) It has level constructors.
viii) It can produce efficient programs.
ix) It can be complied on variety of computers.
Advantage of C language
It is machine independent programming language.
It is easy to learn and implement C language.
It can be implemented from mobile device to mainframe computers.
It is the mother of all modern programming language.
Disadvantage of C Language
There is no runtime checking.
It has poor error detection systems.
On large programs, it is hard to fix errors.
It does not support modern programming methodologies oriented programming language.
Website: www.bkbhusal.com.np 2 YouTube Channel: www.youtube.com/BkBhusalEduZone
Computer Science Reference Note for Grade-XII E-mail ID: [email protected]
Upper case and lowercase are allowed but not same, i.e. Text not same as text.
Only one special character underscores (_) will used.
For example, int a_b; Where a and _b are valid identifiers.
Keywords:-
Keywords are the reserved words which have standard, predefined meaning in C language. Keywords
cannot be used as names for the variables or other user defined program elements. There are 32 keywords
available in C. common examples are as follows.
auto double if static break else int
struct case enum long switch char extern
const float near typedef register union continue
far return unsigned default for short void
do goto signed while
Tokens:
In a C source code, the basic element recognized by the compiler is known as tokens. A token is source-
program text that the compiler does not break down into components elements.
The keywords like int, float, if, for etc.
Identifiers like main, printf, void etc.
Constants like a,b,c etc.
String literals like name, address, phone etc.,and
Operators like &&, ! etc.
Punctuation characters such as [ , ] , { , } , ( , ) , ; , : are also tokens.
2) Explain data types used in programming with examples.
Data types:
It is the set of keywords to declare variables. A set of data that specifies the possible range of values in a
program and stored in memory are called data types. Data types are used to define variables before use it.
Types of data types in C.
1) Primary data types
2) Secondary data types
Primary Data Types: The basic fundamental of data having unit feature on C programming is called Primary
Data Type. Example
Data Type Type Memory Require Format Specifies
Char Character 1 byte %C
Int Integer 4/2 byte %d
Float Floating point number 4 byte %f
Long Floating number 4 byte %ld
Double Large floating point number 8 byte %lf
Format Specifier: The output and input data are display and receive in specific pattern. Format
specifier uses the token % and character(s) after it. It is used to format for all types of data i.e.
integer, float, character and string.
Format Specifier Used by scanf() function
%d , % i Signed integer + or – number o to 9
%f Scans floating point numbers.
%s String, Collection of character i.e. word
%c Character, one single key stroke.
Operator:
An operator is a symbol that operates on a certain data type. The operator generally remains between the
two operands. An expression is a combination of variables, constants, and operators written according to
the syntax of the language. The data items that operators act upon are called operands.
Types of operator
1. Arithmetic Operator(Binary Operator)
2. Relational Operator (Comparison Operator)
3. Logical Operator (Boolean Operator)
4. Assignment Operator
5. Increment and Decrement Operators (Unary Operator)
6. Conditional Operator (Ternary Operator)
7. Bitwise Operator
8. Comma Operator
9. Size of Operator
1. Arithmetic Operator
The arithmetic operators perform arithmetic operations and can be classified into unary and binary
arithmetic operations. The arithmetic operators can operate on any built-in data type. A list of arithmetic
operators and their meanings are given below:
Operator Meaning
+ additional or unary plus
- subtraction or unary minus
* multiplication
/ division
% modulo division (returns remainder after division)
2. Relational Operator
The relational operators help to compare two similar quantities and depending on their relation, take some
decisions. If the condition is true, it evaluates to an integer 1 and zero if the condition is false. The basic
types of relational operator are:
Operator Meaning
< less than
> greater than
<= less than or equal to
>= greater than or equal to
== equal to
!= not equal to
3. Logical Operator
The logical operators are used to give logical value either true or false. They compare or evaluate logical
and relational expressions. There are three logical operators.
Operator Meaning Examples
&& Logical AND (a>b) && (a>c)
|| Logical OR (a>b) || (a>c)
! Logical NOT !(a==b)
4. Increment and Decrement Operators:
The increment and decrement operators are very commonly used in C language. The increment operators
and decrement operators are extensively used in the loops using structures such as for, while, do, etc. The
syntax of the operators is given below.
++<variable name> Pre increment
--<variable name> Pre decrement
<variable name>++ Post increment
<variable name)-- Post decrement
The pre increment operator increases the value of the variable by 1 and then the processing does whereas
post increment first processes and increase the value of it by 1.
5. Conditional Operator:
A conditional operator is very rarely used. This can be carried out with the conditional operator (? : ) An
expression that makes use of the conditional operator is called a conditional expression. This can replace
the if-else statement. The syntax of conditional operator is:
During evaluating the conditional expression, expression_1 is evaluated at the first step. If expression_1 is
true (nonzero), then expression_2 is evaluated and this becomes the value of the conditional expression.
Library function:
The special functions that are well defined in C programming languages are called library functions such as
printf(), scanf(),strlen(), sqrt(), tolower(), toupper(), getchar(), putchar() etc.
Control Structure:
Website: www.bkbhusal.com.np 6 YouTube Channel: www.youtube.com/BkBhusalEduZone
Computer Science Reference Note for Grade-XII E-mail ID: [email protected]
Control structures are those programming constructs which control the flow of program statements
execution in a program. Types of Control Structure
i) Branching / Decision ( Selective Control Structure)
ii) Looping (Repetitive Control Structure)
iii) Jumping (Unconditional Control Structure)
1. Decision (Selective) Control Structure
It is mainly used for decision making. It is also called conditional statements. Selection is made on
the basis of condition. We have options to go when the given condition is true or false. The flow of
program statements execution is totally directed by the result obtained from checking condition.
Types
a) Conditional Statements
i. if statements:
It is used to execute an instruction or block of instructions only if a condition is fulfilled.
Syntax,
if(condition)
{
Statements;
}
E.g. WAP to read a number and find even or odd by using if().
#include<stdio.h>
#include<conio.h>
void main()
{
int a,r;
printf("enter the number");
scanf("%d",&a);
r=a%2;
if(r==0)
{
printf("number is even %d",a);
}
if(r!=0)
{
printf("number is odd %d",a);
}
getch();
}
ii. if else statements
If the condition is true then the if() portion statements are evaluated otherwise else part of the
statements are evaluated.
Syntax,
if( condition)
{
Block of statements;
}
else
{
Block of statements;
}
E.g. WAP input any two numbers and display the largest one.
#include<stdio.h>
#include<conio.h>
void main()
{
int a,b;
printf("enter the number");
scanf("%d",&a);
printf("enter the number");
scanf("%d",&b);
if(a>b)
{
printf("A is greatest number",a);
}
else
{
printf("B is greatest number",b);
}
getch();
}
iii. if() else if() statements
When we have two or more condition to be checked in a series we can use if else if statement. It is
also known as multiple conditional statement or multipath conditional statement /if else ladder.
Syntax,
if(conditiona 1)
{
Statements 1;
}
else if(condition 2)
{
Statement 2;
}
else if(condition n-1)
{
Statement n-1;
}
else
{
Statement n;
}
}
Website: www.bkbhusal.com.np 8 YouTube Channel: www.youtube.com/BkBhusalEduZone
Computer Science Reference Note for Grade-XII E-mail ID: [email protected]
e.g. WAP to find the largest number among three input number .
#include<stdio.h>
#include<conio.h>
void main()
{
int a,b,c;
printf("\n Enter any three number");
scanf("%d",&a,&b,&c);
if(a>b&&a>c)
{
printf("\n Largest number is %d",a);
}
else if(b>a&&b>c)
{
printf("\n Largest number is %d", b);
}
else
{
printf("\n Largest number is %d",c);
}
getch();
}
Percentage division
p>=75 distinction
p>=60 and <75 first
p>=45 and <60 second
p>=35 and <45 third
otherwise failed
#include<stdio.h>
#include<conio.h>
Void main()
{
int eng,nep,comp,acc,eco,total;
Float per;
printf("Enter the five subject mark");
scanf("%d %d %d %d %d",&eng,&nep,&comp,&acc,&eco);
total=eng+nep+comp+acc+eco;
per=total/5;
if(eng>=35&&nep>=35&&comp>=35&&acc>=35%%eco>=35)
{
if(per>=75)
{
printf("\n Distinction");
else if(per>=60)
{
printf("\n First");
}
else if(per>=45)
{
printf("\n Second");
}
else
{
printf("\n Third");
}
}
else
{
printf("\n You are failed");
}
getch();
}
Syntax,
Switch(expression 1)
{
Case condition 1:
Statements ….
break;
.
.
Case condition n-1:
Statements…….
break;
default:
statement n;
}
E.g. WAP which reads any two integer values from user and calculates sum, difference and
product using switch case statement.
#include<stdio.h>
#include<conio.h>
Void main()
{
int a,b,c,ch;
printf("enter the two number");
Scanf("%d",&a,&b);
printf("\n 1. Sum");
printf("\n 2. Difference");
printf("\n 3. Product");
printf("\n Enter your choice");
Scanf("%d",&ch);
switch(ch)
{
case 1:
c=a+b;
Printf("\n Sum of two number is %d,c);
break;
case 2:
c=a-b;
printf("\n difference of two number is %d,c);
break;
case 3:
c=a*b;
printf("\n product of two number is %d,c);
break;
default:
printf("\n Wrong choice");
}
Website: www.bkbhusal.com.np 11 YouTube Channel: www.youtube.com/BkBhusalEduZone
Computer Science Reference Note for Grade-XII E-mail ID: [email protected]
getch();
}
1. Looping Statement
The looping statement is also called repetitive or iterative control structure. Looping statements are the
conditional control flow statements that repeats a certain portion of the program either a specified
number of times or until a particular condition is satisfied or true.
Types of loop
i) For Loop ii) While Loop iii) Do while Loop
1. For Loop:-
The execution of for loop until the condition is true. The for loop is a entry control loop because it
checks the condition at entry point.
Syntax,
for( initialization; condition; increment/ decrement)
{
// statements
}
1. Write a program to print the natural number from 1 to 10.
#include<stdio.h>
#include<conio.h>
void main()
{
int i;
for(i=1;i<=10;i++)
{
printf("/n%d",i);
}
getch();
}
2. Write a program to display even number from 1 to 20 and display their sum also.
#include<stdio.h>
#include<conio.h>
void main()
{
int i, s=0;
for(i=1;i<=20; i=i+2)
{
printf("/n even number are %d",i);
s=s+i;
}
printf("sum of even number is %d", s);
getch();
}
3. Write a program to find out sum of the cubes of first 10 numbers.
# include<stdio.h>
# include<conio.h>
Website: www.bkbhusal.com.np 12 YouTube Channel: www.youtube.com/BkBhusalEduZone
Computer Science Reference Note for Grade-XII E-mail ID: [email protected]
void main()
{
int i,c, sum=0;
for(i=1;i<=10;i++)
{
c=i*i*i;
sum=sum+c;
}
printf("/n sum of cube is %d", sum);
getch();
}
When for loop is declared inside another for loop is called nested for loop. The life of the inner for loop
is depending over the outer for loop. If the outer for loop condition is true then inner for loop is
evaluated. And will executes all the statements until condition is true if the inner for loop to be false
then the outer for loop condition is reevaluated and so on.
For example for( initialization; condition; increment/ decrement)
{
for( initialization; condition; increment/ decrement)
{
// statemetns
}
}
# include<stdio.h> # include<stdio.h>
# include<conio.h> # include<conio.h>
void main() void main()
{ {
int R,K; int R,K;
for (R=1;R<=5; R++) for (R=5;R<=1; R++)
{ {
for (K=10;K<=50;K=K+10) for (K=1;K<=R;K=K++)
{ {
printf("\n %d",K); printf("\n %d",R);
} }
printf("\n"); printf("\n");
} }
getch(); getch();
} }
While Loop:-
The while loop is also a entry control loop. While loop first checks whether the initial condition is
true or false and finding it to be true, it will enter the loop and execute the statement.
Syntax,
initialization;
while(condition)
{
// statement
increment/decrement
}
1. Write a program to print even number from 1 to 100.
# include<stdio.h>
# include<conio.h>
void main()
{
int i;
i=2
while<i<=100)
{
printf("%d\t", i)
i=i+2;
}
getch();
}
Do while loop:-
This loop is an exit control loop. This loop runs at least the once even though the termination
condition is set to false. This loop test the condition at exit point hence it is called exit control loop.
The syntax of the loop is similar to while loop.
initialization;
do
{
// statement
increment/decrement
} while(condition);
1. Write a program to display odd number from 100 to 1.
# include<stdio.h>
# include<conio.h>
void main()
{
int i;
i=99;
do
{
printf("%d\t",i);
i=i-2;
}while(i>=0);
getch(); }
2. Write a program to read the employee name, address for the N employee and display by
using while loops.
# include<stdio.h>
# include<conio.h>
void main()
{
int num;
char ename[20],eadd[30];
printf("\n enter the how many employee number");
scanf("%d",& num);
while(num>0)
{
printf("\n enter the name, address");
scanf("%s%s",ename,eadd);
num=num-1;
printf("%s%s",ename,eadd);
}
getch();
}
{
if(num==7)
{
continue;
}
printf("%d",num);
}
getch();
} OUTPUT: 1,2,3,4,5,6,8,9
Go to statement:
The goto statement is used to send the pointer to the specified label. If the label is not
defined then the goto statement will not work.
# include<stdio.h>
# include<conio.h>
void main()
{
int num;
Lab:
printf("Enter a number");
scanf("%d", &num);
if(num<100)
{
printf("Mark can't be less then 100");
goto Lab:
}
else
{
printf("Valid mark");
}
getch();
}
1. WAP to input any value and display the that value in reverse order.
# include<stdio.h>
# include<conio.h>
void main()
{
int i,r,n,x;
printf("enter a number");
scanf("%d",&n);
x=0;
while(n>0)
{
r=n%10;
x=x*10+r;
n=n/10;
}
printf("/n reverse number is%d",x);
getch();
}
2. WAP to input positive number and find its factorial number.
# include<stdio.h>
# include<conio.h>
void main()
{
int i,n,f;
printf("enter a number");
scanf("%d", &n);
if (n>0)
{
f=1;
for(i=n;i>=1;i--)
{
f=f*i;
}
printf("/n The factorial value is %d",f);
}
else
{
printf("/n it is not a positive number");
}
getch();
}
5.WAP to find out even number from 1 to 100 and find their sum also.
#include<stdio.h>
#include<conio.h>
void main()
{
int i,sum=0;
for(i=2; i<=100;i+2)
{
printf("\n Even number are %d",i);
sum=sum+i;
}
printf("\n Sum of even numbers is %d",sum);
getch();
}
6.WAP to input a number and find out that number is palindrome or not.
#include<stdio.h>
#include<conio.h>
void main()
{
int a,n,r,x;
x=0;
printf("\n Enter the any number");
scanf("%d",&n);
a=n;
while(n>0)
{
r=n%10;
x=x*10+r;
n=n/10;
}
if(a==x)
{
printf("Number is palindrome");
}
else
{
printf("Number is not palindrome");
}
getch();
}
7.WAP to input a positive number and find out the sum of its individual digits.
#include<stdio.h>
#include<conio.h>
void main()
{
int i,r;n,x;
printf("\n Enter a number");
scanf("%d",&n);
if(n>0)
{
x=0;
while(n>0)
{
r=n%10;
x=x+r;
n=n/10;
}
printf("\n the sum of digits is %d",x);
}
else
{
printf("\n It is not a positive number");
}
getch();
}
8.WAP to input a number and check it is Armstrong number or not.
#include<stdio.h>
#include<conio.h>
void main()
{
int i,r,n,x,a;
printf("Enter a number");
scanf("%d",&n);
a=n;
if(n>0)
{
x=0;
while(n>0)
{
r=n%10;
x=x+r*r*r;
n=n/10;
}
if(a==x)
{
{
printf("\t%d",j);
}
getch();
}
11.WAP to display all perfect square numbers from 100 to 500.
#include<stdio.h>
#include<conio.h>
void main()
{
int s,t;
printf("The square numbers between 100 to 500 are");
for(s=100;s<=500;s++)
{
for (t=1;t<=s;t++)
{
if(s==t*t)
{
printf("%d x %d = %d \n",s,s,t);
}
}
getch();
}
Arrays and String Function:
Arrays : An array is a collection of data of the similar type all of which are referred by a single variable
name. for example, instead of using 50 individual variables to store name of 50 students, we can use an
array to store name of 50 students.
Advantage of arrays.
- It is easier for handling similar types of data in a program.
- It is efficient for solving problems like sorting, searching, indexing etc.
- It is easier to solve matrix related problems.
- Graphics manipulations can be easily be done using array.
Disadvantages of arrays.
- It is not possible to hold dissimilar type of data in an array.
- It is difficult to visualize the multi dimensional array.
- It is static in nature so it is difficult to define the size of array during running time.
There are two types
1. One/signal dimensional: The values on an array variable assigned in one row and more than one
column are called signal dimensional array.
Syntax: type array_name[max. size];
Example int n[10];
int age[]= {18,12,19,20,16,16,17};
2. Two/Double dimensional: Two dimensional arrays are capable of storing data in multiple row and
columns.
Syntax: type array_name[No.Rows] [No.Cols];
Example int n[10][5];
}
for(i=0;i<20;i++)
{
if(age[i]>=20&& age[i]<=25)
{
c++;
}
}
printf("Total number of students having age between 20 to 25 is %d",c);
getch();
}
Program: Write a program to find the largest number among 'n' numbers.
#include<stdio.h>
#include<conio.h>
Void main()
{
int i, n, num[100],max;
printf("\n Enter the size of array not more than 100");
scanf("%d",&n);
for(i=0;i<n;i++)
{
printf("Enter array elements");
scanf("%d",&num[i])
}
max=num[0];
for(i=1;i<n;i++)
{
if(num[i]>max)
{
max=num[i];
}
}
printf("\n Largest number in array is %d",max);
getch();
}
Program: Write a program to read a matrix, store it in array and display it.
#include<stdio.h>
#include<conio.h>
void main( )
{
clrscr();
int I,J, matrix[3][4];
printf("Enter a matrix of 2x4:\n\n");
for(I=1; I<=3; I++)
{
for(J=1; J<=4; J++)
{
scanf("%d",&matrix[I][J]);
}
}
Printf("\n The elements of matirx are: \n\n"):
for(I=1; I<=3; I++)
{
for(J=1; J<=4; J++)
{
printf("%d\t",matrix[I][J]);
}
printf("\n");
}
}
int count2=0;
int i;
for (i=1; i<=10; i++)
{
printf("Enter the ages");
scanf("%d", &age[i]);
}
for (i=1; i<=10; i++)
{
if (age[i]>=60)
{
count1++;
}
else
{
if(age[i]<=35)
{
count2++;
}
}
}
printf("Employees above or equal to 60 %d",count1);
printf("Employees under or equal 35 %d",count2);
}
Program: Write a program to store N numbers in array and print out the sum with the entire array
variable.
# include<stdio.h>
# include<conio.h>
void main( )
{
int j, sum=0;
int n,num[10];
clrscr();
printf("Enter the how many no. you want to enter"):
scanf("%d",&n);
for (j=1; j<=n; j++)
{
printf("number stored %d",num[i]);
sum=sum+num[j];
}
printf("\n Sum is %d",sum);
}
Program: Write a program to accept 10 different numbers in array and sort in descending order.
# include<stdio.h>
# include<conio.h>
void main( )
{
clrscr( ):
int array[10];
int i, j ;
for (i=1; i<=10; i++)
{
printf(" Enter the data serially);
scanf("%d",&array[i]);
}
int temp;
for( i=1; i<=10; i++)
{
for (j=i+1; j<=10; j++)
{
if (array[i] < array[j])
{
Temp=array[i];
array[i]=array[j];
array[j]= temp;
}
}
}
printf("Sorting data in descending order\n");
for( i=1; i<=10; i++)
{
printf("%d\n",array[i]);
}
}
Program: Write a program to store twelve numbers in double dimensional array and print out the values
in table with row wise addition.
# include<stdio.h>
# include<conio.h>
void main( )
{
int j, k;
int num[3][4]={1,2,3,4,8,10,11,5,9,6,2,8}
clrscr();
printf("Data stored \t\t sum\n");
for (j=1; j<=3; j++)
{
int sum=0;
Program: WAP to enter elements for 2x2 matrix and display its transpose.
#include<stdio.h>
#include<conio.h>
void main()
{
clrscr();
int a[2][2];
int i,j;
printf("\n Enter number for 2x2 matrices");
for(i=0;i<2;j++)
{
for(j=0;j<2;j++)
{
printf("Enter number");
scanf("%d",&a[i][j]);
}
}
printf("\n Transpose of Matrix is");
for(i=0;i<2;j++)
{
for(j=0;j<2;j++)
{
printf("%d",a[i][j]);
}
printf("\n");
}
getch();
}
Program: WAP to enter elements for 3x3 matrix and display its sum.
#include<stdio.h>
#include<conio.h>
void main()
{
clrscr();
int m1[3][3], m2[3][3],
int i,j;
printf("\n Enter number for 2x2 matrices");
for(i=0;i<3;j++)
{
for(j=0;j<3;j++)
{
printf("Enter number for first matrix");
scanf("%d",&m1[i][j]);
}
}
for(i=0;i<3;j++)
{
for(j=0;j<3;j++)
{
printf("Enter number for Second matrix");
scanf("%d",&m2[i][j]);
}
}
printf("\n string=%s",n);
printf("\n length=%d",length);
}
2. strrev( ): It helps to reverse the character of the string.
Syntax: strrev(string);
3. strupr( ): It converts lowercase letters in string to uppercase.
Syntax: strupr(string);
4. strlwr( ): It converts uppercase letters in string to lowercase.
Syntax: strlwr(string);
5. strcpy( ): It is used to copy the content of one string to another.
Syntax: strcpy(target,source);
6. strcat( ): It is used to concatenate source string to the target string.
Syntax: strcat(target,source); or strcat(source,target);
7. strcmp( ): It compares two strings on following basis.
Syntax: strcmp(string1,string2);
Program: Write a program to read two strings in array and compare two strings and check that string is
palindrome or not.
#include<stdio.h>
#include<conio.h>
#include<string.h>
void main( )
{
int a;
char s1[20];
char s2[20];
printf("Enter a word");
scanf("%s",s1);
strcpy(s2,s1);
if(strcmp(s2,strrev(s1))==0)
{
printf("palindrome");
}
else
{
printf("Not palindrome");
}
getch();
}
Function:
Functions are the building block of statements, which takes some data, manipulate them and can return a
value. Bug free function can be used repeatedly from other part of the program.
Function is a self-contained sub program which can be directly used in program to perform specific task. It
consists a set of statements that take inputs, do some specific computation and produces output. The
commonly repeated task which are used and need to execute many times in program, basically defined as
function. After defining, Function can be used several times in a program. It reduces the code of program
by writing once instead of writing the same code again and again for different inputs. It also makes
program readable, manageable and understandable. A large program is broken into the basic building
blocks known as function.
Function 1 ()
main ( )
{ {
………….
function 1( ) }
…………… function 2 ( )
function 2 ( ) {
} ……………
}
The program is the collection of functions. It means it consist multiple functions. A function can be called
form another function. The same function can be called several times from the different location of
program. After execution of the statement of the function, the control always returns backs to the point
from where it is called.
There are two types of functions:
1. Library Functions (built in or ready made): C has the facilities to provide library function for
performing some operation. These functions are present in the c library and they are predefined.
Library function which is already defined in library of C language and directly used in program is
known as library function. It is a readymade or in-built function so that programmer can use this
function instantly when required. C has a large number of library function. It is very useful for
programmer to perform specific task in program and return the value. Some examples of
Library function are printf ( ), scanf ( ), strlen ( ), strrev ( ), srtcat ( ), gets, puts ( ) , getchar( ),
putchar( );
2. User Defined functions (Defined by user according to need): user can creates their own function
for performing this type of a function are called user define function.
Syntax of user defined functions
# include<stdio.h>
# include<conio.h>
function ( );
..............
.............
}
void main( )
{
}
function ( )
{
body of the function
}
Advantage of functions in C:
It reduces the code because it avoids rewriting same code again and again in a program.
The functions can be called several of times from any location in a program.
A large C program is organized in manageable form.
It enhances the reusability of code.
It is easy to debug the program.
The program can be developed in different phase.
The program can be tested and compiled independently.
Big programs can be divided into smaller module using functions.
Program development will be faster.
Use of functions reduce program complexity.
a. Function prototype:
Function prototype is the actual name of the function. The function name and the parameter list
together constitute the function signature. The function prototype is written at the beginning of
a program. Prototype is only needed if function definition comes after use in program. The
function prototype provides the following information to the compiler.
The type of data type which is going to return
The function name
The types of argument and number of argument
Syntax: return_data type function_name( argument 1, argument 2, argument 3,….)
Where,
In this example, area is the function name which consists int type two arguments and return
type is integer.
b. Function Definition:
Before using the function, it must be defined. Function definition consists of the type of data
type which is going to return, functions name and the data type and numbers of arguments. The
argument are separated by the comma (,) and enclosed within the parentheses. The next part of
the function is the body of function which is written within curly brace { }. The body consist the
number of statements for the execution.
Syntax: data_type function_name(argument 1, argument 2, argument 3,……..) Where,
data_type the type of data type such as int, float etc
function_name name of the function
argument the list of variable
Example:
int area (int l, int b)
{ int a; a = l*b return (a)
}
In the above example, area is the name of function, l and b are the argument that are used to
receive the value sent by calling statement and return value after processing.
Example:
x = area (l, b); sum (a, b);
d. Return statement:
After manipulation data within the function, the final value should be returned. The final value is
returned by using the return statement to the calling module. The return keyword followed
variable or expression that going to return. The return statement returns single value at a time.
Syntax: return expression
Where, expression is the value that is going to return. Example: return a;
Example-1. Write a program to input any two numbers and find sum of the number.
# include<stdio.h>
int sum (int, int); ---------------------------- prototype
void main ( )
{ Output:
int a, b, s; Enter first number 10
printf ("\n Enter first number"); Enter second number 5
scanf ("%d", &a); The sum is 50
printf ("\n Enter second number");
scanf ("%d", &b);
s = sum (a, b); -------------------- calling function In this program, prototype of function is defined
printf ("\n The sum is %d", s); initially. “sum” is the name of function which consists
} two integer arguments and return type is also integer.
Calling statement “s = sum(a, b)” calls the function and
int sum (int a, int b) ------------ function
pass the value through arguments a and b. The function
definition is defined as like as its prototype. After the processing
{ the value, the final result is stored in variable t and
int t; returned to the calling statement.
t = a + b;
return (t); -------------------------- returning value
}
Void statement:
If a function does not return any value to the calling module, then it is called the function’s return type is
void. In this function, the function accepts the values though the arguments and execute the result within
the function after the manipulation with that values.
Example: Write a program to input length and breadth of rectangle and find area.
# include<stdio.h>
void area (int, int);
void main ( ) Output:
{ Enter the length 6
int l, b, s; Enter the breadth 4
printf ("\n Enter the length"); The area is 24
scanf ("%d", & l);//
printf ("\n Enter the breadth");
scanf ("%d", &b);
area (l, b);
} In this program, return type of the function is void, it means the
void area (int l, int b) function does not return value to the calling statement. The calling
{ statement “area(l, b)” calls the function and pass the value through
int ar; arguments a and b. After the processing value, the final result is
ar = l*b; store in variable “ar” and it is displayed within the function.
printf ("\n The area is %d", ar);
}
Write a program to input any three numbers and find average of these numbers.
# include<stdio.h>
int average (int, int, int);
void main ( )
{ Output:
int a, b, c, d; Enter first number 4
printf ("\n Enter first number"); Enter second number 5
scanf ("%d", & a); Enter third number 6
printf ("\n Enter second number"); The average is 5
scanf ("%d", & b);
printf ("\n Enter third number");
scanf ("%d", & c);
d = average (a, b, c);
printf ("\n The average is %d", d);
} In this program, the final result is returned to its calling
int average (int a, int b, int c)
module.
{
inta v;
av = (a + b + c)/3;
return (av);
}
Write a program to input any three numbers and find average of these numbers.
# include<stdio.h>
int average (int, int, int); Output:
void main ( ) Enter first number 4
{ Enter second number 5
int a, b, c, d; Enter third number 6
printf ("\n Enter first number"); The average is 5
scanf ("%d", & a);
printf ("\n Enter second number");
scanf ("%d", & b);
printf ("\n Enter third number");
scanf ("%d", &c);
In this program, the final result is not returned to the
average (a, b, c);
} calling function.
int average (int a, int b, int c)
{
intav;
av = (a + b + c)/3;
printf ("\n The average is %d", av);
}
Write a program to input any three numbers and find average of these numbers.
#include<stdio.h>
int average ( ); Output:
void main ( ) Enter first number 4
{ Enter second number 5
int d; Enter third number 6
d =average ( ); The average is 5
printf ("\n The average is %d", d);
}
int average ( )
{
int a, b, c, av; In this program, calling statement does not consist any
printf ("\n Enter first number"); argument to pass the value
scanf ("%d", & a); to the function.
printf ("\n Enter second number");
scanf ("%d", & b);
printf ("\n Enter third number");
scanf ("%d", & c);
av = (a + b + c)/3;
return (av);
}
d. Function passing no arguments and returning no value:
In this method, the values are not passed to the function through argument form the calling function. The
inputs statements are used within the function for the value. The final value is executed within function
after the manipulation with that data.
Write a program to input any three numbers and find average of these numbers.
# include<stdio.h>
int average ( ); Output:
void main ( ) Enter first number 4
Enter second number 5
{ Enter third number 6
average ( ); The average is 5
}
int average ( )
{
int a, b, c, av;
printf ("\n Enter first number"); In this program, there is neither calling statement
scanf ("%d", & a); nor return statement for passing and returning
printf ("\n Enter second number"); value.
scanf ("%d", & b);
printf ("\n Enter third number");
scanf ("%d", & c);
av = (a + b + c)/3;
printf ("\n The average is %d", av);
}
Recursive Function:
The function which performs recursion is called recursive function. Recursion is a process by which a
function calls itself repeatedly until some specified condition has been satisfied.
Those function which calls itself is known as recursive function and the concept of using recursive functions
to repeat the execution of statements as per the requirement is known as recursion. The criteria for
recursive functions are:
1. The function should call itself.
2. There should be terminating condition so that function calling will not be for infinite number of
time.
Program: Write a program to calculate factorials by using recursion process.
#include<stdio.h>
#include<conio.h>
int fact(int);
void main( )
{
clrscr();
int n;
printf("Enter a number");
scanf("%d",&n);
printf("The factorial of %d is %d",n,fact(n));
}
int fact(int n)
{
if(n<=1)
return (1)
else
{
return(n*fact(n-1)); or z=(n*fact(n-1));
} return z;
}
Program: Write a program read a number and make the sum of individual digits & print using recursion
technique.
#include<stdio.h>
#include<conio.h>
int sum(int)
void main()
{
clrscr();
int n;
printf("Enter the any number");
scanf("%d",&n);
}
int sum (int n)
{
if (n<=0)
return 0;
else
return (n+sum(n-1));
}
Accessing a Function:
There are two types of accessing a function.
1. Call by value: Only the values of arguments are same to the function and any change made to the
formal arguments do not change the actual arguments.
Program: Write a C program try to exchange two values by using call by value accessing function.
# include<stdio.h>
# include<conio.h>
int swap (int, int)
void main( )
{
int a,b;
a=10
b=20
printf("Value of a=%d and b=%d",a,b);
swap (a,b);
printf("Value of a=%d and b=%d",a,b);
}
int swap(int x, int y)
{
int r;
r=x;
x=y;
y=r;
}
2. Call by reference: When we pass address to a function the parameters receiving the address should
be pointer. The process of calling a function by using pointer to pass the address of the variable is
known as call by reference.
Program: Write a C program to exchange two values by using call by reference accessing function.
# include<stdio.h>
# include<conio.h>
int swap(int *, int *)
void main( )
{
int a,b;
a=10
b=20
printf("Value of a=%d and b=%d",a,b);
swap(&a,&b);
printf("Value of a=%d and b=%d",a,b);
}
Example -Write a program to input any ten number in array and find sum of those numbers.
#include<stdio.h>
int sum (int num []); Enter any number : 52
void main () Enter any number : 54
{ Enter any number : 24
Enter any number : 26
int num [10], i, s; Enter any number : 32
for (i = 1; i < = 10; i++) Enter any number : 27
{ Enter any number : 29
printf ("Enter any number : "); Enter any number : 21
scanf ("% d", & num [i]); Enter any number : 23
Enter any number : 28
} The sum of number is 316
s = sum(num);
printf ("\n The sum of number is %d", s);
}
int sum(int num [])
{
int t, i;
for (i = 1; i < = 10; i++)
{
t = t + num [i];
}
return(t);
}
Write a program to input any ten number in array and find the largest number among them
#include<stdio.h>
int sum(int num[]);
void main()
{
int num[10], i, s;
for(i=1; i<=10; i++)
{
printf("Enter any number : ");
scanf("%d",&num[i]);
}
s = sum(num);
printf("\n The largest number is %d",s);
}
int sum(int num[])
{
int i, l;
l = num[1];
for(i=2; i<=10; i++)
{
if (l<=num[i])
{
l = num[i];
}
return(l);
}
Write a program to input word or sentence and count the total number of letter in that word and sentence.
#include<stdio.h>
int count(char str[]);
void main()
{
char str[500];
printf("Type any word/sentence : ");
gets(str);
printf("\n The total number of letter in that word/ sentence is %d", count(str));
}
int count(char str[])
{
int i;
for(i=0; str[i]!='\0'; i++)
{
}
return(i);
}
int ar;
ar = 3.14*r*r;
return(ar);
}
float circum(int r)
{
int cr;
cr = 2*3.14*r;
return(cr);
}
Write a program to input any number and check whether input number is even or odd.
#include < stdio.h>
void check (int);
void main ()
{
int n;
printf ("\n Enter number");
scanf ("%d", &n);
check (n);
}
void check (int num)
{
if (num%2 ==0)
{
printf ("\n %d is even number", num);
}
else
{
printf ("\n %d is odd number", num);
}
}
Write a program to input any number and check whether input number is positive, negative or zero.
#include<stdio.h>
void check(int);
void main()
{
int n;
printf("\n Enter number");
scanf("%d", &n);
check(n);
}
void check(int num)
{
if (num>0)
{
printf("\n %d is positive number", num);
}
else if (num<0)
{
Write a program to input any two number and find HCF and LCM.
#include<stdio.h>
int hcf(int, int);
int lcm(int, int);
void main()
{
int a, b, h, l;
printf ("\n Enter first number");
scanf ("%d", &a);
printf ("\n Enter second number");
scanf ("%d", &b);
h = hcf (a, b);
l = lcm (a, b);
printf ("\n The HCF of %d and %d number is %d",a,b, h);
printf ("\n The LCM of %d and %d number is % d", a, b, l);
}
int hcf(int a, int b)
{
int i, hf;
for(i=1; i<=a; i++)
{
if (a%i == 0 && b %i == 0 )
hf = i;
}
return(hf);
}
int lcm(int a, int b)
{
int i, hf, lc;
for(i=1; i<=a; i++)
{
if (a%i == 0 && b %i == 0 )
hf = i;
}
lc = (a*b)/hf;
return(lc);
}
Write a program to input any digit number and find sum of its digits.
#include<stdio.h>
int digits(int);
void main()
{
int n, d;
printf("\n Enter first number");
scanf("%d", &n);
d = digits(n);
printf("\n The sum of digits of %d is %d",n,d);
}
int digits(int n)
{
int r, s, a;
while (n!=0)
{
r = n%10;
s = s + r;
n = n/10;
}
return(s);
}
Write a program to input any number and check whether input number is prime or composite.
#include<stdio.h>
void check (int);
void main ( )
{
int n;
printf ("Enter any number");
scanf ("% d", & n);
check(n);
}
void check (int n)
{
int i, c;
for (i = 1; i < = n; i++)
{
if (n%i == 0)
{
c = c + 1;
}
}
if (c == 2)
{
printf("\t %d is prime number",n);
}
else
{
printf("\t %d is composite number",n);
}
}
Write a program to input any number and find its reverse order.
#include<stdio.h>
#include<conio.h>
int reverse(int);
void main()
{
int r=0,n,x=0;
printf("enter a number");
scanf("%d",&n);
rev=reverse(n)
printf("\n Reverse number is \t %d",rev);
int area()
{
int l,b,ar;
printf(“Enter length and breadth”);
scanf(“%d%d”,&l,&b);
ar = l*b;
return (ar);
}
int age;
char section;
float height;
};
We can also declare a structure
struct student
{
int roll;
char name[50];
int age;
char section;
float height;
} s1,s2;
We can also declare array of variables at a time of declaring a structure as:
struct student
{
int roll;
char name[50];
int age;
char section;
float height;
} s[100];
Union:
Unions like structure contain members whose individual data types may differ from one another.
However the member that composes a union all share the same storage area within the computer memory
were as each member within a structure is assigned its own unique storage area.
Syntax Union union_name
{
Union_member (s);
}
S.N. Structure S.N. Union
1 Structure is designed by using 'struct' 1 Union is designed by using 'union' keyword.
keyword.
2 Syntax: struct structure_name 2 Syntax: union union_name
{ {
Data_type member1; Data_type member1;
Data_type member1; Data_type member1;
} }
3 All the member of the structure variable 3 Only one member of the union variable can be
can be processed at a given time. processed at a time because only one member
of the union variable can be active at a time.
4 We use structure variable if memory is 4 We use union variables if memory is less and
large and have to store values all of the have to store one variable in one of the
variables. declared variables or members.
5 Structures are broadly used in 5 Unions are not used broadly as much as
programming. structures.
6 Structure declaration takes large amount 6 Union declaration shares the same area of
of spaces to store data and values. memory to save storage space.
Example 1, Write a C program to read different structure variables and display them.
#include<stdio.h>
#include<conio.h>
void main( )
{
struct student
{
int roll;
char name[30];
char section;
float height;
} s1
printf("\n Enter roll numer");
scanf("%d",&s1.roll );
printf("\n Enter name:");
gets(s1.name);
printf("\n Enter section:");
scanf("%c",&s1.section);
printf("\n Enter height");
scanf("%f,&s1.height);
printf("\n You have entered:\n);
printf(" Roll Numer %d Name is %s section %c and height is %f",
s1.roll,s1.name,s1.section,s.height);
}
Program: Write a program to input the employee name and their basic salary of n employees and display
the record in proper format.
#include<stdio.h>
#include<conio.h>
void main ()
{
struct employee
{
char name[10];
int salary;
};
struct employee e[100],t;
int i,j,n;
printf("\n How many records");
scanf("%d", &n);
{
t=s[j];
s[j]=s[j+1];
s[j+1]=t;
}
}
}
Printf("\n\n The records of the student after sorting\n");
Printf("\n Name of student Address ");
for (i=0; i<=n; i++)
{
printf("\n %s %s", s[i].name,s[i].address);
}
}
Pointer
A pointer is a variable that a points to a references a memory location where data is stored. Each memory
cell in the computer has an address which can be used to access its location. A pointer variable points to a
memory location rather than a value.
- We can access and change the contents of the memory location.
- A pointer variable contains the memory location of another variable.
- The asterisk tells the compiler that you are creating a pointer variable.
The pointer declaration syntax is as shown below.
Pointer_type *pointer_variable_name;
For e.g. int *p;
Address (&) and indirection (*) operator
The address (&) operator and immediately preceding variable returns the address of the variable
associated with it. Hence, the address of (&) operator returns the address of memory location in which the
variable is stored.
The indirection (*) operator is used to extract value from the memory location stored in the
particular memory location whose address is stored in pointer variable.
The syntax of declaring address operator to pointer variable is as follows.
Pointer_variable = &variable_name;
For Example
int *ptr, num=25;
ptr = #
Program: Write a complete program to display address and value of the pointer variable.
#include<stdio.h>
void main( )
{
int *p;
int age=17;
p=&age;
printf("\n Value of age is %d", age); output= 17
printf("\n Value of age is %d",*p); output=17
Advantage of Pointer
- Runtime memory creation.
- Runtime memory deletion.
- Hard Access through pointer.
- Data Structure Based Pointer.
- Applications of Pointer Ms-word, Excel, Access, SQL.
Functions
1. fputc= Store character into the file.
2. fputs= Store string in to the file.
3. fgetc= fetch character from the file.
4. fgets= fetch string from the file.
5. fwrite= store data (structure) in to the file.
6. fread= fetch data (structure) from the file.
7. fprintf= store data in to file.
8. fscanf= fetch variable from the file.
Store/write data
Syntax:
fprintf(fptr , ”format specifiers” ,variables);
Eg; suppose if we want to store name, disease, age and bed number of a patient then, it is written
as
fprintf(fptr , ”%s %s %d %d”, n, d, a, b);
Where, variable are initialized as:
char n[10], d[10];
int a, b;
Program example
1) Create a datafile “patient.txt” and store name, disease, age and bed number of a patient.
#include<stdio.h>
void main()
{
char n[10], d[10];
int a, b;
FILE *fptr;
fptr = fopen(“patient.txt”,”w”);
printf("Enter name, disease, age and bed number");
scanf(“%s %s %d %d”, n, d, &a, &b);
fprintf(fptr,"%s %s %d %d\n”, n, d, a, b);
fclose(fptr);
}
[Note: This program will store only single record to store multiple record we have to use loop as following
programs.
2) Create a datafile “student.txt” and store name, class and marks obtained in 3 different subject for few
students/n-students.
#include<stdio.h>
void main()
{
char n[10];
int c, e, ne, m, i, num;
FILE *fptr;
fptr = fopen("student.txt","w");
printf("How many record?");
scanf("%d",&num);
for(i=1;i<=num;i++)
{
printf("Enter name class and 3 marks");
scanf("%s %d %d %d %d",n, &c, &e, &ne, &m);
fprintf(fptr,"%s %d %d %d %d \n",n, c, e, ne, m);
}
fclose(fptr);
}
3) Create a datafile “student.txt” and store name, class and marks obtained in 3 different subject until user
press “y” / as per user requirement.
#include<stdio.h>
int main()
{
char n[10],ch[3];
int c, e, ne, m;
FILE *fptr;
fptr = fopen("student.txt","w");
do
{
printf("Enter name class and 3 marks");
scanf("%s %d %d %d %d",n, &c, &e, &ne, &m);
fprintf(fptr,"%s %d %d %d %d\n",n, c, e, ne, m);
printf("Press Y to continue");
scanf("%s",ch);
} while (strcmp(ch,"Y") == 0 || strcmp(ch,"y")==0);
fclose(fptr);
}
Add/Append data
1) A datafile “student.txt” contain name, class and marks obtained in 3 different subject of few students.
Write a C program to add 200 more records.
#include<stdio.h>
void main()
{
char n[10];
int c, e, ne, m, i;
FILE *fptr;
fptr = fopen("student.txt","a");
for(i=1;i<=200;i++)
{
printf("Enter name class and 3 marks");
scanf("%s %d %d %d %d", n, &c, &e, &ne, &m);
fprintf(fptr,"%s %d %d %d %d \n",n, c, e, ne, m);
}
fclose(fptr);
}
2) A datafile “student.txt” contain name, class and marks obtained in 3 different subject of few students.
Write a C program to add more records until user press “y” / as per user requirement.
#include<stdio.h>
void main()
{
char n[10], ch[3];
int c, e, ne, m;
FILE *fptr;
fptr = fopen("student.txt”,”a”);
do
{
printf("Enter name class and 3 marks");
scanf("%s %d %d %d %d", n, &c, &e, &ne, &m);
fprintf(fptr,"%s %d %d %d %d\n", n, c, e, ne, m);
printf("Press Y to continue");
scanf("%s",ch);
1) A d#include <stdio.h>
void main()
{
char n[10];
int c, e, ne, m;
FILE *fptr;
fptr = fopen("student.txt","r");
printf("Name\tPercentage\n");
while(fscanf(fptr,"%s %d %d %d %d",n,&c,&e,&ne,&m) != EOF)
{
printf("%s %d %d %d %d", n, c, e, ne, m);
}
fclose(fptr);
}
2) A datafile “student.txt” contain name, class and marks obtained in 3 different subject of few students.
Write a C program to read and display only records whose name is Ram.
#include<stdio.h>
void main()
{
char n[10];
int c, e, ne, m;
FILE *fptr;
fptr = fopen("student.txt","r");
while(fscanf(fptr,"%s %d %d %d %d",n,&c,&e,&ne,&m) != EOF)
{
strlwr(n);
if (strcmp(n,”ram”) == 0)
{
printf("%s %d %d %d %d", n, c, e, ne, m);
}
}
fclose(fptr);
}
3) A datafile “student.txt” contain name, class and marks obtained in 3 different subject of few students.
Write a C program to read and display only records who pass in all subjects.
#include<stdio.h>
void main()
{
char n[10];
int c, e, ne, m;
FILE *fptr;
fptr = fopen("student.txt","r");
while(fscanf(fptr,"%s %d %d %d %d",n,&c,&e,&ne,&m) != EOF)
{
if (e>=40 && ne>=40 && m>=40)
{
printf("%s %d %d %d %d", n, c, e, ne, m);
}
}
fclose(fptr);
}
4) A datafile “student.txt” contain name, class and marks obtained in 3 different subject of few students.
Write a C program to read and display only records who fail in any one subject.
#include<stdio.h>
void main()
{
char n[10];
int c, e, ne, m;
FILE *fptr;
fptr = fopen("student.txt","r");
while(fscanf(fptr, "%s %d %d %d %d", n, &c, &e, &ne, &m) != EOF)
{
if (e<40 || ne<40 || m<40)
{
printf("%s %d %d %d %d", n, c, e, ne, m);
}
}
fclose(fptr);
}
5) A datafile “student.txt” contain name, class and marks obtained in 3 different subject of few students.
Write a C program to read and display only name and percentage of all students
#include<stdio.h>
int main()
{
char n[10];
int c, e, ne, m;
float p;
FILE *fptr;
fptr = fopen("student.txt","r");
while(fscanf(fptr, "%s %d %d %d %d", n, &c, &e, &ne, &m) != EOF)
{
p = (e+ne+m)/3;
printf("%s %f", n, p);
}
fclose(fptr);
}
6) A datafile “student.txt” contain name, class and marks obtained in 3 different subject of few students.
Write a C program to read and display only records of all students who secure distinction.
#include<stdio.h>
int main()
{
char n[10];
int c, e, ne, m;
float p;
FILE *fptr;
fptr = fopen("student.txt","r");
while(fscanf(fptr, "%s %d %d %d %d", n, &c, &e, &ne, &m) != EOF)
{
p = (e+ne+m)/3;
if (p>=80)
{
printf("%s %d %d %d %d", n, c, e, ne, m);
}
}
fclose(fptr);
}
Program: Write a program to read a line and store it in a data file and display the contents.
#include<stdio.h.
#include<conio.h>
void main( )
char I;
FILE *f, *q;
f = fopen("store.txt","w");
while((i=getchar())!='\n')
{
fputc(i, f);
}
fclose( f);
q=fopen ("store.txt","r");
while((i=fgetc(q))!=EOF)
{
Printf("%c",i);
}
}
Program: Write a C program to read N students record store them in data file and display the content in
appropriate format by using fprintf and fscanf function.
#include<stdio.h>
void main( )
{
FILE *f;
f= fopen (''ratna.txt","w");
int i, rn, n;
char name[25], add[35];
printf("\n how many records?");
scanf("%d", &n);
printf("Enter %d student roll number, name and address:\n",n);
for (i=o; i<n; i++)
{
scanf("%d %s %s",&rn,name,add);
fprintf( f, "%d\t%s\t%s\n ",rn,name,add);
}
fclose(f);
printf("\n The %d data records",n);
f= fopen ("ratna.txt","r");
while (fscanf( f, "%d %s %s",&rn,name,add)!=EOF)
{
printf("\n %d\t%s\t%s",rn,name,add);
}
fclose(f);
}
Program: Write a program using C language that reads successive records from the new data file and
display each record on the screen in an appropriate format.
#include<stdio.h>
#include<conio.h>
void main( )
{
struct student.
{
char name[50];
char add[80];
};
struct student s;
char next='Y' ;
FILE *fp;
fp = fopen ("C:\\student.txt","w");
while(next=='Y' || next=='y')
{
printf("\n Enter the name of the student");
gets(s.name);
printf("\n Enter the address of the student");
gets(s.add);
fwrite(&s, sizeof (s), 1, fp);
printf("\n Do you want to write next record (Y/N)");
}
fclose(fp);
fp=fopen ("C:\\student.txt", "r");
printf("\n Name of student Address");
while (fread (&s, sizeof(s), 1,f(p)==1)
{
printf("\n %s \t\t\t %s",s.name,s.add);
}
fclose (fp);
Program: Write a C program to read sentence until enter key pressed. Put every words in data file by
using fputs( ) fucnction and display the content of file by using fgets( ) function.
#include<stdio.h>
#include<conio.h>
Void main( )
{
Char a[20];
FILE *f;
f= fopen ("senten.doc", "w");
printf("\n Enter sentence");
gets(a)
while (strlen (gets(a))>0)
{
fputs(a,f);
}
fclose(f);
f = fopen ("senten.doc", "r");
if (f== NULL)
printf("\n Cannot open the file");
else
{
While (fgets (a,19,f)!=NULL)
{
printf("%s",a);
}
}
fclose(f);
}
Program: Write a C program to read ages of N students, store them in age.txt file and find out the
average age after reading from data file.
#include<stdio.h>
#include<conio.h>
Void main( )
{
int ag,n, i, sum=0;
float avg;
FILE *f;
f= fopen("age.txt", "w");
printf("\n How many student:");
scanf("%d",&n);
for(i=0; i<n; i++)
{
printf("\n Enter %d student ages",i+1);
scanf("%d",&ag);
putw(ag,f);
}
fclose (f);
f= fopen ("age.txt", "r");
printf("\n Calculating average age from file");
for (i=0; i<n; i++)
{
sum=sum+getw(f);
}
avg = (float) sum / n ;
printf("\n Average age of %d student is %f", n, avg);
fclose(f);
}
Program: Write C program to read already created data file student.txt and display it contents if it opens
otherwise print message "The file ……does not exists".
#include<stdio.h>
#include<conio.h.
Void main( )
{
char i;
FILE *f;
f = fopen ("student.txt", "r");
If (f== NULL)
{
printf("\n The student.txt file does not exists");
}
else
{
while ( ( i=fgetc(f))!=EOF)
{
printf("%c",i);
}
}
fclose(f);
Web References:
3. https://www.javatpoint.com
4. https://www.w3schools.com
5. https://www.tutorialspoint.com
6. https://www.google.com
7. https://www.wikipedia.org