0% found this document useful (0 votes)
39 views

Practical 6

This document provides code samples and explanations for programs involving matrix operations, string operations, arithmetic operations using functions, calculating area and circumference using functions, finding the factorial using a function, determining the type of triangle using a function, and solving numerical methods problems like finding the roots of a quadratic equation. The programs cover concepts like functions, arrays, loops, conditional statements, and mathematical operations. The document aims to demonstrate solving problems step-by-step using programming concepts.

Uploaded by

bhavi jaiswal
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
39 views

Practical 6

This document provides code samples and explanations for programs involving matrix operations, string operations, arithmetic operations using functions, calculating area and circumference using functions, finding the factorial using a function, determining the type of triangle using a function, and solving numerical methods problems like finding the roots of a quadratic equation. The programs cover concepts like functions, arrays, loops, conditional statements, and mathematical operations. The document aims to demonstrate solving problems step-by-step using programming concepts.

Uploaded by

bhavi jaiswal
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 60

PRACTICAL-6

OBJECTIVE- Write a program for matrix problem and string operation.


CONCEPT- A string is a collection of character. It is called the array of character.
It must be accessed by %s access character specifier in c and c++. A string is
always terminated with \0(null) character.
Example of string: “Gaurav”
A string always recognized in double quotes.it also consider space as a
character.
Example: “Gaurav Arora”
The above string contain 12 characters. Example ar[20].
The above example will store 20 character starting from 0 to 19.

String Function in C:
C language provide lots of string function for manipulating string.all the string
function are available in string.h header file.
These string functions are:
1.srelen()-the string function is basically used for the purpose of computing the
length of string.
2.strupr()-this string is basically use for converting the lowercase case
characters into uppercase.
3.strlwr()-this string function is basically used for converting uppercase
character into lower case characters.
4.strcmp()-this string function is basically used for the comparision of two
string.
5.strcat()-this string function is used for the purpose of concatenating or
merging two string.
6.strcpy():this string function function is basically used for the purpose of
copying one string to another string.
7.strrev()-this string function is basically used for the purpose of reversing the
string.
PRACTICAL-6.1
AIM: Write a program to display the sum of two matrix.
CODE INPUT:
#include<stdio.h>
int main(){
int n1,n2;
printf("enter rows and columns\n");
scanf("%d%d",&n1,&n2);
int a[n1][n2];
printf("enter elements of first matrix\n");
for(int i=0;i<n1;i++){
for(int j=0;j<n2;j++){
scanf("%d",&a[i][j]);
}
}
int b[n1][n2];
printf("enter elements of second matrix\n");
for(int i=0;i<n1;i++){
for(int j=0;j<n2;j++){
scanf("%d",&b[i][j]);
}
}
int ans[n1][n2];
for(int i=0;i<n1;i++){
for(int j=0;j<n2;j++){
ans[i][j]=a[i][j]+b[i][j];
}
}
printf("sum of the two array is:\n");
for(int i=0;i<n1;i++){
for(int j=0;j<n2;j++){
printf("%3d",ans[i][j]);
}
printf("\n");
}
return 0;
}
PROGRAM:

OUTPUT:

PROGRAM 6.2:
AIM: write a program to display the product of two matrix.
CODE INPUT:
include<stdio.h>
int main(){
int n1,n2,n3;
printf("enter n1 , n2 and n3\n");
scanf("%d%d%d",&n1,&n2,&n3);
int a[n1][n2];
printf("enter elements of first matrix\n");
for(int i=0;i<n1;i++){
for(int j=0;j<n2;j++){
scanf("%d",&a[i][j]);
}
}
int b[n2][n3];
printf("enter elements of second matrix\n");
for(int i=0;i<n2;i++){
for(int j=0;j<n3;j++){
scanf("%d",&b[i][j]);
}
}
int ans[n1][n3];
for(int i=0;i<n1;i++){
for(int j=0;j<n3;j++){
ans[i][j]=0;
}
}
for(int i=0;i<n1;i++){
for(int j=0;j<n3;j++){
for(int k=0;k<n2;k++){
ans[i][j]+=a[i][k]*b[k][j];
}
}
}
printf("multiplication of two matrix is:\n");
for(int i=0;i<n1;i++){
for(int j=0;j<n3;j++){
printf("%3d",ans[i][j]);
}
printf("\n");
PROGRAM:
OUTPUT:

PROGRAM-6.3
AIM: write a program to display string operation.
CODE INPUT:
#include<stdio.h>
#include<string.h>
int main(){
char str1[5]="ASdfG";
char str2[5]="hjkl";
printf("the length of the string is:%d\n",strlen(str1));
printf("the upper case character in string is:%s\n",strupr(str1));
printf("the lower case character in string is:%s\n",strlwr(str1));
printf("the copied string is:%s\n",strcpy(str1,str2));
printf("the concatinated string is:%s\n",strcat(str1,str2));
printf("the reversed order string is:%s\n",strrev(str1));
printf("the comparision between two string is;%d",strcmp(str1,str2));
return 0;
}

PROGRAM:
OUTPUT:

Results:
6.1 Printed multiplied 2D array.
6.2 Printed string operation.
6.3 Program to display string operation
Outcome:
6.1 Learned to multiply 2D array/matrix.
6.2 Learned to perform string operations.
6.3 Learned to perform different string operation.
PRACTICAL-7
OBJECTIVE- write a program using a single function.
CONCEPT-Functions are the set of statements that takes input , perform some
calculations and produces results. the operations of a functions occurs only
when it is called. Rather than writing the same code for different input
repeatedly, we can call the function instead of writing the same code over and
over again . functions accept parameters and accept data.a function performs
certain actions ,and it is important for resulting code. within a function it is
important for, there are number of programming statements enclosed by{}
FUNCTION DECLARATION: function declaration tells the compiler how many
parameters a function takes . function declaration need not toinclude
parameters name , but definition must.
SYNTAX:
<return _type _ name_ of _the _function(parameters);
FUNCTION DEFINATION:
A function definition consist function header and a function body.
Return _type function _name (parameters)
{
//body of function
}
RETURN TYPE:
The function always start with a return type of the function . but if there is no
return value then the void keyword is used as the return type of the function.
FUCTION_NAME: Name of the function which should be unique.
PARAMETERS: values that are passed during the function call .
FUNCTION CALL:
To call a function parameters are passed along the function name. in the
below example the first sum function is called and 10 and 20 are passed are
passed to the sum function .after the sum function calls a and bis returned and
control is also returned back to the main function of the program.
PROGRAM 7.1:
AIM: Write a program to display the arithmetic operation using function.
CODE INPUT:
#include<stdio.h>
int sum(int a,int b){
int sum=a+b;
return sum;
}
int sub(int a,int b){
int sub=a-b;
return sub;
}
int mul(int a,int b){
int mul=a*b;
return mul;
}
int div(int a,int b){
int div=a/b;
return div;
}
int main(){
int a,b;
printf("enter two numbers\n");
scanf("%d%d",&a,&b);
printf("sum is: %d\n",sum(a,b));
printf("sub is: %d\n",sub(a,b));
printf("mul is: %d\n",mul(a,b));
printf("div is: %d\n",div(a,b));
return 0;
}
PROGRAM:

OUTPUT:

PROGRAM 7.2
AIM: write a program to display the area and circumference of a circle using
function.
CODE:
#include<stdio.h>
float area(float a){
float area=3.14*a*a;
return area;
}
float circum(float a){
float circum=2*3.14*a;
return circum;
}
int main(){
float a;
printf("enter radius");
scanf("%f",&a);
printf("the area of circle is:%f\n",area(a));
printf("the circum of circle is:%f\n",circum(a));
return 0;
}
PROGRAM:

OUTPUT:

PROGRAM 7.3:
AIM: write a program to display the factorial using function.
SOURCE CODE:
#include<stdio.h>
int fact(int n){
int factorial=1;
for(int i=2;i<=n;i++){
factorial*=i;
}
return factorial;
}
int main(){
int n;
printf("enter a number:\n");
scanf("%d",&n);
printf("factorial is:%d",fact(n));
return 0;
}
PROGRAM:

OUTPUT:

PROGRAM 7.4:
AIM: Write a program to display the type of triangle using functions.
SOURCE CODE:
#include<stdio.h>
void triangle(int a,int b,int c){
if((a==b)&&(b==c)){
printf("it is an equilateral triangle");
}
else if((a==b)&&(b!=c)||(a==c)&&(a!=b)||(b==c)&&(b!=a)){
printf("it is an isosoles triangle");
}
else{
printf("it is a scalar triangle");
}
}
int main(){
int a,b,c;
printf("enter sides of the triangle");
scanf("%d%d%d",&a,&b,&c);
triangle(a,b,c);
return 0;
}
PROGRAM:
OUTPUT:

Result:
7.1 Printed answers using basic arithmetic.
7.2 Printed area and circumference of circle.
7.3 Printed factorial of the entered number.
7.4 Printed type of triangle by entered sides.

Outcome:
7.1 Learned the use of function for basic arithmetic.
7.2 Learned to print area and circumference of the
circle using function.
7.3 Learned to print factorial of the given number using
function.
7.4 Learned to identify the types of triangle using
function.
PRACTICAL-8
OBJECTIVE: programming for solving numerical method of problem.
CONCEPT:
Step1- Understanding the problem .
Here we try to understand the problem to be solved in totally. Before
with next stage or step , we should be absolutely sure about the
objective of the given problem.
Step2- analysing the problem.
After understanding thoroughly the problem to be solved we look at
different ways of solving the problem and evaluate each of these
methods.
The idea here is to search for an appropriate solutions to the
problem under consideration. The end result of these stage is board
interview of the sequence of the operation that are to be carried out
to solve the problem.
Step-3: DEVELOPING THE SOLUTION
Here the overview of the sequence of operations that was the result
off the operations that was the result of operation stage is expanded
to form a detailed step by step solution to the problem under
consideration .
Step 4 Coding and implementation.
The last stage of the problem solving is the conversion of the
detailed sequence of operation into a language that the computer
can understand . here each step is converted to its equivalent
instructions in the computer language that has been chosen for its
implementation.
The vehicle for the computer solutions to a problem to set of explicit
and umambiguous instruction expressed in the programming
language. This set of instruction is called a program in C.

PROGRAM 8.1:
AIM: write a program to display the roots of the quadratic equation.
CODE INPUT:
#include<stdio.h>
#include<math.h>
int main(){
int a,b,c,d,x,y;
printf("enter coeff of x^2,x,number\n");
scanf("%d%d%d",&a,&b,&c);
d=(b*b)-4*a*c;
if(d<0){
printf("imaginary roots");
}
else if(d==0){
printf("roots are equal");
x=(-b)/2*a;
printf("root is %d ",x);
}
else{
printf("real roots");
x=((-b)+sqrt(d))/2*a;
y=((-b)-sqrt(d))/2*a;
printf("roots are %f%f",x,y);
}
return 0;
}
PROGRAM:

OUTPUT:

PROGRAM 8.2:
AIM: write a program to display the right angle triangle..
CODE INPUT:
#include<stdio.h>
int main(){
for(int i=1;i<6;i++){
for(int j=1;j<=i;j++){
printf("*");
}
printf("\n");
}
return 0;
}
PROGRAM:

OUTPUT:

PROGRAM 8.3:
AIM: write a program to display pyramid pattern.
CODE INPUT:
#include<stdio.h>
int main(){
for (int i = 0; i<=6; i++)
{
for (int j=6; j>i; j--)
{
printf(" ");
}
for(int k = 1; k<=2*i-1; k++){
printf("*");
}
printf("\n");
}

return 0;
}

PROGRAM:

OUTPUT:
PROGRAM 8.4:
AIM: write a program to display the inverted pyramid pattern.
CODE INPUT:
#include<stdio.h>
int main(){
for (int i = 0; i<=5; i++)
{
for (int j=5; j>i; j--)
{
printf("*");
}
printf("\n");
}

return 0;
}

PROGRAM:

OUTPUT:
Result:
8.1 Programming formula to print roots of the
quadratic equation.
8.2 Program to print right angle triangle.
8.3 Program to print pyramid.
8.4 Program to print inverted pyramid.

Outcome:
8.1 Printed roots of the quadratic equations.
8.2 Printed half pyramid.
8.3 Printed pyramid.
8.4 Printed inverted pyramid.

PRACTICAl-9
PROGRAM 9.1:
AIM: Write a program to display the Fibonacci series using recursion.

OBJECTIVE: write a program using recursive function:


CONCEPT: recursion is a process of defining object based on
previously defined other objects of the same type. A recursion
relation defines some rules and a few initial values to built up an
entire class of objects. Here it must be noted that if an object is
defined in terms of itself , it causes self- recursion and leads to
infinite nesting . A real - world example of recursion is when you are
climbing a ladder. To reach the 3rd rung of ladder , you need to reach
the 2nd rung . Basically , it means that completing each step is
dependent on the completion of the previous rung .

Recursion Function Definition :-


When a function calls itself and
uses its own previous terms to define its subsequent terms , it is
called a recursive function .It is the technical recursive function’s
definition ,i.e., a recursive function built itself.

The Recursive Function has 2 parts :


The value of the smallest or the first terms in the sequence, usually
given as f(0) or f(1) .
The pattern or the rule which can be used to get the value of any
term , given the value of the term preceding it . In other words ,the
definition of f(n) when values of f(n-1) , f(n-2), etc are given .

Visualization of Recursive Function :- A Pascal’s triangle is the most


famous example of the recursive sequence . In this ,you can see that
each term is obtained by adding 2 other parts of the triangle . Below
is a visualization of the triangle .

Conclusion :- A Recursive function is a function that builds by calling


itself and is calculated using starting value and a pattern or rule
which gives the next value in the series . It can be applied to
arithmetic as well as geometric series . A common difference is used
to add or substract for getting the next term in an arithmetic
progression , and a common ratio is used to multiply or divide to get
the nest term in a geometric progression. There functions are widely
used in coding algorithms where one needs to traverse hierarchies
or find the factorial of a numbers.
PROGRAM 9.1:
AIM: Write a program to display the factorial function using
recursion.
SOURCE CODE:
#include<stdio.h>
int factorial(int n){
if(n==0){
return 1;
}
return n*factorial(n-1);
}
int main(){
int n;
printf("enter a number\n");
scanf("%d",&n);
printf("factorial is: %d",factorial(n));
}
PROGRAM:

OUTPUT:

PROGRAM 9.2:
AIM: Write a program to display the fibonacci using recursion.
SOURCE CODE:

Result:
9.1 Printed factorial using recursive function.
9.2 Printed fibonacci series using recursion.
9.3 Printed Ackerman function.

Outcome:
9.1 Learnt how to print factorial of a number using
Recursion.
9.2 Learnt how to print Fibonacci series using
Recursion.
9.3 Learnt how to print the Ackerman Function
PRACTICAL 10
OBJECTIVE: Using sorting and searching.
AIM: Programming to solve numerical method.
Basic of comparision Linear search Binary search
Definition The linear search start It finds the position of
searching from the first the first element by
element and compare finding the middle
each element with a element of the array.
searched element is noy
found.
Sorted data In a linear search the The pre condition for
element don’t need to the binary search is that
be arranged in sorted the element must be
order. arranged in a sorted
array.
Implementation The linear search can be The implementation of
implemented on any binary search is limits as
linear data it can be implemented
of those data structure
that have two way
transversal.
Approach It is based on sequence It is based on divide and
approach. conquer approach.
Size It is permeable for small It is permeable for large
size data type. size datatype
Efficiency It is less efficient in case It is less efficient in case
of large size data sets. of small size data sets.
Worst case Worst case for finding Worst case for finding
the element is (n) the element of 0(log n)
Best case scanerio The best case for finding The best case for finding
the first element is the the first element is the
list is 0(1) list is 0(1)
Dimensional array It can be implemented It can be implemented
on both single and multi only on multi
dimentional. dimentional.
BUBBLE SORT: It is the simple sorting algorithm that work by repeatedly
swapping the adjacent element if they are in wrong order. This algorithm is not
suitable for large data set as its average and worst case time complexity is is
quit high.
How does bubble sort works?
Input: arr[]={5 , 1 , 4, 2 , 8}
Bubble sort start with very first two elements comparing them to check which
one is greater.
First pass;
(5,1,4,2,8)-(1,5,4,2,8) here algorithm compare first two elements and
Swap since 4>5
(1,5,4,2,8)-(1,4,5,2,8) swap since 5>4.
(1,4,5,2,8)-(1,4,2,5,8) swaps since 5>4
(1,4,5,2,8)-(1,4,2,5,8) swaps since 5>2
(1,4,2,5,8)--(1,4,2,5,8) since these elements are already in sorted
Order (8,5) algorithm does not swap them.
Second Pass:
• Now, during second iteration it should look like this:
• ( 1 4 2 5 8 ) –> ( 1 4 2 5 8 )
• ( 1 4 2 5 8 ) –> ( 1 2 4 5 8 ), Swap since 4 > 2
• ( 1 2 4 5 8 ) –> ( 1 2 4 5 8 )
• ( 1 2 4 5 8 ) –> ( 1 2 4 5 8 )
Third Pass:
• Now, the array is already sorted, but our algorithm does not know if it is
completed.
• The algorithm needs one whole pass without any swap to know it is
sorted.
• ( 1 2 4 5 8 ) –> ( 1 2 4 5 8 )
• ( 1 2 4 5 8 ) –> ( 1 2 4 5 8 )
• ( 1 2 4 5 8 ) –> ( 1 2 4 5 8 )
• ( 1 2 4 5 8 ) –> ( 1 2 4 5 8 )
MergeSort Algorithm

The MergeSort function repeatedly divides the array into two halves until
we reach a stage where we try to perform MergeSort on a subarray of size
1 i.e. p == r .

After that, the merge function comes into play and combines the sorted
arrays into larger arrays until the whole array is merged.

MergeSort(A, p, r):

if p > r

return

q = (p+r)/2

mergeSort(A, p, q)

mergeSort(A, q+1, r)

merge(A, p, q, r)

To sort an entire array, we need to call MergeSort(A, 0, length(A)-1) .

As shown in the image below, the merge sort algorithm recursively divides
the array into halves until we reach the base case of array with 1 element.
After that, the merge function
picks up the
sorted sub-arrays and merges them to gradually sort the entire array.
Merge sort in action

The merge Step of Merge Sort


Every recursive algorithm is dependent on a base case and the ability to
combine the results from base cases. Merge sort is no different. The most
important part of the merge sort algorithm is, you guessed it, merge step.
The merge step is the solution to the simple problem of merging two sorted
lists(arrays) to build one large sorted list(array).

The algorithm maintains three pointers, one for each of the two arrays and
one for maintaining the current index of the final sorted array.

Have we reached the end of any of the arrays?

No:

Compare current elements of both arrays

Copy smaller element into sorted array

Move pointer of element containing smaller element

Yes:

Copy all remaining elements of non-empty array


Program 10.1: Program for linear searching.
Source code:
#include<stdio.h>
int search(int a[],int n,int key){
for(int i=0; i<n; i++){
if(a[i]==key){
printf("Index = %d",i);
}
}
}
int main(){
int a[]= {1,2,3,4,5};
int n = sizeof(a)/sizeof(a[0]);
search(a,n,5);
return 0;
}
Outcome:

Program 10.2: Program for binary searching.


Source code:
#include<stdio.h>
int BinarySearch(int arr[], int N, int x){
int start = 0, end = N;
while(start <= end){
int mid = (start + end)/2;
if(arr[mid] == x){
return mid;
}
if(arr[mid] < x){
start = mid +1 ;
}
else{
end = mid - 1;
}
}
return -1;
}
int main(){
int arr[] = {2,4,6,8,10,12,14};
int x = 2;
int N = sizeof(arr)/sizeof(arr[0]);
int result = BinarySearch(arr, N, x);
if(result == -1){
printf("key is NOT FOUND");
}
else{
printf("key is at : %d", result);
}
return 0;
}
Output:

Program 10.3: Program for bubble sorting.


Source code:
#include<stdio.h>
int bsort(int arr[],int n);
int main(){
int arr[5] = {5,10,8,2,1};
bsort(arr,5);
for (int i = 0; i < 5; i++)
{
printf("%d ",arr[i]);
}
return 0;
}
int bsort(int arr[],int n){
int c;
for (int j = 0; j < n; j++)
{
for (int i = 0; i < n; i++)
{
if (arr[i]>arr[i+1])
{
c = arr[i+1];
arr[i+1] = arr[i];
arr[i] = c;
}
}
printf("\n");
}
}
Output:

Program 10.4: Program for Merge sorting.


Source code:
#include <stdio.h>
#include <stdlib.h>
void merge(int arr[], int l,
int m, int r)
{
int i, j, k;
int n1 = m - l + 1;
int n2 = r - m;
int L[n1], R[n2];
for (i = 0; i < n1; i++)
L[i] = arr[l + i];
for (j = 0; j < n2; j++)
R[j] = arr[m + 1 + j];
i = 0;
j = 0;
k = l;
while (i < n1 && j < n2)
{
if (L[i] <= R[j])
{
arr[k] = L[i];
i++;
}
else
{
arr[k] = R[j];
j++;
}
k++;
}
while (i < n1) {
arr[k] = L[i];
i++;
k++;
}

while (j < n2)


{
arr[k] = R[j];
j++;
k++;
}
}
void mergeSort(int arr[],int l, int r)
{
if (l < r)
{
int m = l + (r - l) / 2;
mergeSort(arr, l, m);
mergeSort(arr, m + 1, r);
merge(arr, l, m, r);
}
}
void printArray(int A[], int size)
{
int i;
for (i = 0; i < size; i++)
printf("%d ", A[i]);
printf("\n");
}
int main()
{
int arr[] = {12, 11, 13, 5, 6, 7};
int arr_size = sizeof(arr) / sizeof(arr[0]);
printf("Given array is \n");
printArray(arr, arr_size);
mergeSort(arr, 0, arr_size - 1);
printf("\nSorted array is \n");
printArray(arr, arr_size);
return 0;
}
Output:
Result:
10.1 Searched element using program of the
linear search.
10.2 Searched element using program of the
binary search.
10.3 Searched element using bubble sorting.
10.4 Searched element using Merge.

Output:
10.1 Learned to use linear search.
10.1 Learned to use binary search.
10.1 Learned to use bubble sort.
10.1 Learned to use merge sort.

Lab 11
OBJECT: Programming using pointer and
structure.
AIM: Learn to use pointers and structure.
Pointers in C are used to store the address of variables or a memory location. This
variable can be of any data type i.e, int, char, function, array, or any other pointer. The
pointer of type void is called Void pointer or Generic pointer. Void pointer can hold
address of any type of variable. The size of the pointer depends on the computer
architecture like 16-bit, 32-bit, and 64-bit.
Syntax:
datatype *var_name;
Let pointer “ptr” holds the address of an integer variable or holds the address of
memory whose value(s) can be accessed as integer values through “ptr”. So to define
“ptr” we can do it in four ways, which are as following:
int *ptr;
int* ptr;
int * ptr;
int*ptr;

What is Structure data type?


A structure is a keyword that creates user-defined data types in C/C++. A
structure creates a data type that can be used to group items of possibly
different types into a single type.
Where to use the Structure data type?
We can use this data type to store dates of different attributes of different
data types.
For example, If we want to store data on multiple patients such as patient
name, age, and blood group.
How to create a structure?
‘struct’ keyword is used to create a structure. Following is an example.

• C

struct address{

char name[50];

char street[100];

char city[50];

char state[20];

int pin;

};
Program 11.1: Program to swap numbers using
pointer.
Source code:
#include <stdio.h>
// function to swap the two numbers
void swap(int *x,int *y)
{
int t = *x;
*x = *y;
*y = t;
}
int main()
{
int num1,num2;
printf("Enter value of num1: ");
scanf("%d",&num1);
printf("Enter value of num2: ");
scanf("%d",&num2);
//displaying numbers before swapping
printf("Before Swapping: num1 is: %d, num2 is: %d\n",num1,num2);
//calling the user defined function swap()
swap(&num1,&num2);
//displaying numbers after swapping
printf("After Swapping: num1 is: %d, num2 is: %d\n",num1,num2);
return 0;}
Outcome:

Program 11.2: Program to print string using


pointer.
Source code:
#include<stdio.h>
int main(){
char *college = "GEC Bilaspur";
printf("%s",college);
return 0;
}

Output:

Program 11.3: Program to print student


information using structure.
Source code:
#include<stdio.h>
#include<string.h>
struct student {
char firstName[50];
int roll;
float marks;
} s;
int main(){
strcpy(s.firstName,"Sunny");
s.roll = 501;
s.marks = 90;
printf("First name: %s\n",s.firstName);
printf("roll no. : %d\n",s.roll);
printf("marks: %d\n",s.marks);
return 0;
}

Output:

Program 11.4: Program to input and print car’s


name and price using structure.
Source code:
#include<stdio.h>
#include<string.h>
struct car {
char carname[50];
float price;
} c;
int main(){
printf("Enter car's name: ");
scanf("%s",&c.carname);
printf("Enter car's price: ");
scanf("%f",&c.price);
printf("Car's name is %s.\n",c.carname);
printf("Car's price is %2.f.",c.price);
return 0;
}

Output:
Result:
11.1 Printed swap numbers.
11.2 Printed string.
11.3 Printed student details.
11.4 Printed car details by taking input.

Outcome:
11.1 Learned to use pointer for swapping
numbers.
11.2 Learned to use pointer or printing strings.
11.3 Learned to use structure for storing student’s
information.
11.4 Learned to use structure for taking input and
storing car’s information.
Lab 12
OBJECT: File handling in c.
AIM: Learn file operations.
So far the operations using the C program are done on a prompt/terminal
which is not stored anywhere. But in the software industry, most programs are
written to store the information fetched from the program. One such way is to
store the fetched information in a file. Different operations that can be
performed on a file are:
1. Creation of a new file (fopen() with attributes as “a” or “a+” or “w” or
“w+”)
2. Opening an existing file (fopen())
3. Reading from file (fscanf() or fgets())
4. Writing to a file (fprintf() or fputs())
5. Moving to a specific location in a file (fseek(), rewind())
6. Closing a file (fclose())
The text in the brackets denotes the functions used for performing those
operations.
Why do we need File Handling in C?
The output of a C program is generally deleted when the program is closed.
Sometimes, we need to store that output for purposes like data analysis,
result presentation, comparison of output for different conditions, etc. The
use of file handling is exactly what the situation calls for.
In order to understand why file handling makes programming easier, let us
look at a few reasons:
• Reusability: The file-handling process keeps track of the information
created after the program has been run.
• Portability: Without losing any data files can be transferred to another in
the computer system. The risk of flawed coding is minimized with this
feature.
• Efficient: A large amount of input may be required for some programs.
File handling allows you to easily access a part of a code using individual
commands which saves a lot of time and reduces the chance of errors.
• Storage Capacity: Files allow you to store data without having to worry
about storing everything simultaneously in a program.
Types of Files in C
Generally, a text file contains alphabets, digits, and special characters or
symbols, while a binary file contains bytes or a compiled version of the text.
It is important to recognize two types of files when dealing with files:
• Text Files
• Binary Files
Text Files: Text files contain data in the form of ASCII characters and are
generally used to store a stream of characters. Each line in a text file ends
with a new line character (‘/n’). Text files are used to store the source code.
Binary Files: Binary files contain data that is stored in a similar manner to
how it is stored in the main memory. Instead of ASCII characters, it is stored
in binary format. The binary files can be created only from within a program
and their contents can only be read by a program.
Functions in File Operations:
Opening or Creating a File
For opening a file, fopen() function is used with the required access modes.
Some of the commonly used file access modes are mentioned below.
File opening modes in C:

Opening
Modes Description

Searches file. If the file is opened successfully fopen( ) loads it into


memory and sets up a pointer that points to the first character in it. If
r the file cannot be opened fopen( ) returns NULL.

Open for reading in binary mode. If the file does not exist, fopen( )
rb returns NULL.

Searches file. If the file exists, its contents are overwritten. If the file
doesn’t exist, a new file is created. Returns NULL, if unable to open the
w file.

Open for writing in binary mode. If the file exists, its contents are
wb overwritten. If the file does not exist, it will be created.

Searches file. If the file is opened successfully fopen( ) loads it into


memory and sets up a pointer that points to the last character in it. If
the file doesn’t exist, a new file is created. Returns NULL, if unable to
a open the file.

Open for append in binary mode. Data is added to the end of the file. If
ab the file does not exist, it will be created.

Searches file. It is opened successfully fopen( ) loads it into memory and


sets up a pointer that points to the first character in it. Returns NULL, if
r+ unable to open the file.
Opening
Modes Description

Open for both reading and writing in binary mode. If the file does not
rb+ exist, fopen( ) returns NULL.

Searches file. If the file exists, its contents are overwritten. If the file
doesn’t exist a new file is created. Returns NULL, if unable to open the
w+ file.

Open for both reading and writing in binary mode. If the file exists, its
wb+ contents are overwritten. If the file does not exist, it will be created.

Searches file. If the file is opened successfully fopen( ) loads it into


memory and sets up a pointer that points to the last character in it. If
the file doesn’t exist, a new file is created. Returns NULL, if unable to
a+ open the file.

Open for both reading and appending in binary mode. If the file does
ab+ not exist, it will be created.

As given above, if you want to perform operations on a binary file, then you
have to append ‘b’ at the last. For example, instead of “w”, you have to use
“wb”, instead of “a+” you have to use “a+b”. For performing the operations on
the file, a special pointer called File pointer is used which is declared as:
FILE *filePointer;

So, the file can be opened as

filePointer = fopen(“fileName.txt”, “w”)


The second parameter can be changed to contain all the attributes listed in
the above table.
Reading From a File
The file read operations can be performed using functions fscanf or fgets. Both
the functions performed the same operations as that of scanf and gets but with
an additional parameter, the file pointer. So, it depends on you if you want to
read the file line by line or character by character.
And the code snippet for reading a file is as:

FILE * filePointer;

filePointer = fopen(“fileName.txt”, “r”);

fscanf(filePointer, "%s %s %s %d", str1, str2, str3, &year);


Writing to a File
The file write operations can be performed by the functions fprintf and fputs
with similarities to read operations. The snippet for writing to a file is as:
FILE *filePointer ;

filePointer = fopen(“fileName.txt”, “w”);

fprintf(filePointer, "%s %s %s %d", "We", "are", "in", 2012);


Closing a File
After every successful file operation, you must always close a file. For closing
a file, you have to use fclose() function. The snippet for closing a file is given
as:
FILE *filePointer ;

filePointer= fopen(“fileName.txt”, “w”);

---------- Some file Operations -------

fclose(filePointer)
Program 12.1: Program to input number in file.
Source code:
#include <stdio.h>
#include <stdlib.h>
int main()
{
int num;
FILE *fptr;
fptr = fopen("D:\\program.txt","w");
if(fptr == NULL)
{
printf("Error!");
exit(1);
}
printf("Enter num: ");
scanf("%d",&num);
fprintf(fptr,"%d",num);
fclose(fptr);
return 0;
}
Output:

Program 12.2: Program to print contents of file.


Source code:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main()
{
FILE* ptr;
char ch;
ptr = fopen("test.txt", "r");
if (NULL == ptr) {
printf("file can't be opened \n");
}
printf("content of this file are \n");
do {
ch = fgetc(ptr);
printf("%c", ch);
} while (ch != EOF);
fclose(ptr);
return 0;
}

Output:
Program 12.3: Program to input number in file.
Source code:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main()
{
FILE* ptr;
char ch;
ptr = fopen("test.txt", "r");
if (NULL == ptr) {
printf("file can't be opened \n");
}
printf("content of this file are \n");
do {
ch = fgetc(ptr);
printf("%c", ch);
} while (ch != EOF);
fclose(ptr);
ptr = fopen("test.txt","a");
fprintf(ptr,"\n%s","New");
fclose(ptr);
return 0;
}
Output:
Result:
12.1 Printed number in file.
12.2 Printed content to the file.
12.3 Appended new character in the file.

Outcome:
12.1 Learned to store number in the file.
12.2 Learned to read the content of the file.
12.3 Learned to add new character to the existing
file.

You might also like