C Solution PDF

Download as pdf or txt
Download as pdf or txt
You are on page 1of 41

Final Assessment 2073

(Solution)
1. Why are functions advantageous? Write a program with a user defined
function that find out the nth Fibonacci number. The value of ‘n’ should be
read from the user in the main() function.(USE RECURSION)
A function is a routine or a set of instruction or code that performs a specific task
and can be processed independently.
Advantages of Functions:
 Functions allow the divide and conquer strategy to be used for the
development of programs.
 Functions help avoid duplication of effort and code in programs.
 Modular and structural programming can be done
 It follows top-down execution approach, so main can be kept very small
 Individual functions can be easily built, tested
 Program development become easy
 A function can call other functions and also itself
 Frequently used functions can be put together in the customized library
 It is easier to understand the program topic
 The functions developed for one program can be used, if required, in
another with little or no modification. This further reduces program
development time and cost.
Program Code:

#include<stdio.h>
#include<conio.h>
void main ()
{
int n,term ;
printf("Enter Number to Compute nth Fibonacci Series");
scanf("%d",&n);
term=fib(n);
printf("\n%dth term of fibonacci series number is %d",n, term);
getch();
}
int fib(int n)
{
if ( n ==0 )
return 0;
else if(n==1)
return 1;
else
return fib(n-1) + fib(n-2);
}

Himal Chand Thapa


2. What are formal and actual arguments? Write a program with a function
that accepts the radius of a circle and calculates the area and
circumference. Print the area and circumference in the main() function.
Arguments written in function definition is called “formal arguments” where as
arguments written in function call is called “actual arguments”

void main()
{
int a,b,c;
c=display(a,b); //calling program
}
void display(int x,int y) //called function
{
------------
------------
}
x,y are “formal argument” and a,b are “actual argument”
The major difference between actual and formal arguments is that actual arguments are
the source of information; calling programs pass actual arguments to called functions.
The called functions access the information using corresponding formal arguments.
Program Code:
#include<stdio.h>
#include<conio.h>
void cal_area_peri(float *area,float *peri,int r);
void main()
{
float area,peri,r;
clrscr()
printf(“Enter radius of circle:”);
scanf(“%f”,&r);
cal_area_peri(&area,&peri,r);
printf(“Area of Circle=%f”,area);
printf(“Perimeter of circle=%f”,peri);
getch();
}
void cal_area_peri(float *area,float *peri,int r)
{
*area=3.14*r*r;
*peri=2*3.14*r;
}

3. Write a program to read a word from main function, pass it to a function


that will converts all of its characters into uppercase it the last character is
in lowercase and into lowercase if the last character is in uppercase.
Display the converted string from main() function.

Himal Chand Thapa


#include<stdio.h>
#include<string.h>
void convert(char str[]);
void main()
{
char str[10];
clrscr();
printf("enter string");
gets(str);
convert(str);
printf("Strint after conversion:\n");
printf("%s",str);
getch();
}
void convert(char str[])
{
int i,l;
l=strlen(str);
if(str[l-1]>='a'&&str[l-1]<='z')
{
for(i=0;str[i]!='\0';i++)
{
if(str[i]>='a'&&str[i]<='z')
{
str[i]=str[i]-32;
}

}
}
else
if(str[l-1]>='A'&&str[l-1]<='Z')
{
for(i=0;str[i]!='\0';i++)
{
if(str[i]>='A'&&str[i]<='Z')
{
str[i]=str[i]+32;
}
}

Himal Chand Thapa


}
}

4. A multi-national company has hired 3 sales person for marketing/selling its


3 products in Kathmandu. Each sales person sells each of these products.
Write a program to read number of each product sold by all sales persons.
Calculate total sales of each item and total sales of each sales person. Use
Array.
#include<stdio.h>
#include<conio.h>
void main()
{
int sales[3][3],i,j,sum,each_product_sell[3],each_person_sell[3];
clrscr();
printf("Enter the sales :");
for(i=0;i<3;i++)
{
for(j=0;j<3;j++)
{
scanf("%d",&sales[i][j]);
}
}
//to calculate total sales of each product
for(i=0;i<3;i++)
{
sum=0;
for(j=0;j<3;j++)
{
sum=sum+sales[i][j];
}
each_product_sell[i]=sum;
}
//to calculate total sales made by each person
for(i=0;i<3;i++)
{
sum=0;
for(j=0;j<3;j++);
{
sum=sum+sales[j][i];
}

Himal Chand Thapa


each_person_sell[i]=sum;
}

printf("\nTotals Sells by each person:\n");


for(i=0;i<3;i++)
{
printf("%d\t",each_person_sell[i]);
}
printf("\nTotal sells of each product:\n");
for(i=0;i<3;i++)
{
printf("%d\t",each_product_sell[i]);
}
getch();
}
5. How you pass structure member to function? Explain with example. Create
a structure Date containing three members (years, month and day). Create
another structure person containing four members (name, address,
telephone and birthday).For member birthday, create a variable of structure
Date within person. Using these structures, write a program t input records
of 5 persons and display the data in alphabetical order of name.

In C, structure can be passed to functions by two methods:

Passing by value (passing actual value as argument)

Passing by reference (passing address of an argument)

A structure variable can be passed to the function as an argument as a normal variable.

If structure is passed by value, changes made to the structure variable inside the
function definition do not reflect in the originally passed structure variable.

Example: pass by value:

#include <stdio.h>
struct student
{
char name[50];
int roll;
};

void display(struct student stu);


Himal Chand Thapa
void main()
{
struct student stud;
printf("Enter student's name: ");
scanf("%s", &stud.name);
printf("Enter roll number:");
scanf("%d", &stud.roll);
display(stud); // passing structure variable stud as argument
getch();
}
void display(struct student stu)
{
printf("Output\nName: %s",stu.name);
printf("\nRoll: %d",stu.roll);
}

The memory address of a structure variable is passed to function while passing it by


reference.

If structure is passed by reference, changes made to the structure variable inside


function definition reflect in the originally passed structure variable.

Example: pass by reference

#include <stdio.h>
struct distance
{
int feet;
float inch;
};
void add(struct distance d1,struct distance d2, struct distance *d3);

void main()
{
struct distance dist1, dist2, dist3;

printf("First distance\n");
printf("Enter feet: ");
scanf("%d", &dist1.feet);
printf("Enter inch: ");
scanf("%f", &dist1.inch);

printf("Second distance\n");

Himal Chand Thapa


printf("Enter feet: ");
scanf("%d", &dist2.feet);
printf("Enter inch: ");
scanf("%f", &dist2.inch);

add(dist1, dist2, &dist3); //passing structure variables dist1 and dist2 by value
whereas passing structure variable dist3 by reference
printf("\nSum of distances = %d\'-%.1f\"", dist3.feet, dist3.inch);
getch();
}
void add(struct distance d1,struct distance d2, struct distance *d3)
{
//Adding distances d1 and d2 and storing it in d3
d3->feet = d1.feet + d2.feet;
d3->inch = d1.inch + d2.inch;

if (d3->inch >= 12)


{
d3->inch -= 12; //if inch is greater or equal to 12, converting it to feet.

++d3->feet;
}
}
Program Code:
#include<stdio.h>
#include<conio.h>
#include<string.h>
struct date
{
int year,month,day;
};
struct person
{
char name[50];
char address[50];
char telephone[20];
struct date birthday;
}p[5],temp;
void main()
{

Himal Chand Thapa


int i,j;
clrscr();
printf("Enter Details:\n");
for(i=0;i<5;i++)
{
printf("Enter name:");
scanf("%s",p[i].name);
printf("Enter address:");
scanf("%s",p[i].address);
printf("Enter telephone:");
scanf("%s",p[i].telephone);
printf("Enter year:");
scanf("%d",&p[i].birthday.year);
printf("Enter month:");
scanf("%d",&p[i].birthday.month);
printf("Enter day:");
scanf("%d",&p[i].birthday.day);
}
for(i=0;i<5;i++)
{
for(j=0;j<2;j++)
{
if(strcmp(p[j].name,p[j+1].name)>0)
{
temp=p[j];
p[j]=p[j+1];
p[j+1]=temp;
}
}
}
printf("\nName\tAddress\tTelephone\tYear-Month-Day\n");
for(i=0;i<5;i++)
{
printf("%s\t%s\t%s\t%d-%d-
%d\n",p[i].name,p[i].address,p[i].telephone,p[i].birthday.year,p[i].birt
hday.month,p[i].birthday.day);
}
getch();
}

Himal Chand Thapa


6. Explain dot and arrow operators for accessing the members of a structure.

Whenever we declare structure variable then member can be accessed using the
dot operator. But when pointer to a structure is used then arrow operator is used.
Both dot and arrow operator serves same function to access member of
structure.

struct student struct student

{ {

char name[20]; char name[20];

int roll; int roll;

}std; }*std

Access structure Example 1 Example 2


member

Name is accessed using std.name std->name

Roll number is accessed std.roll Std->roll


using

From above example we know that arrow operator is used to access the structure
members when we use pointer variable to access it.In case if we want to access the
members of structure using ordinary structure variable then we can use dot operator.

7. Define array of pointer and pointer to array. Write a program to find third
largest number in an array supplied to a user defined function using the
concept of pointers.

Himal Chand Thapa


Array of pointer would be nothing but a collection of address. The address
present in the array of pointers can be address of isolated variables or address of
array elements or any other address. All rules that apply to an ordinary array
apply in to the array of pointers as well.

Example:

void main()
{
int *arr[4]; // array of integer pointers
int i=20,j=30,k=40,l=70,m;
arr[0]=&i;
arr[1]=&j;
arr[2]=&k;
arr[3]=&l;
for(i=0;i<3;i++)
{
printf(“%d\t”,*arr(i)):
}
}
The way we can have a pointer to integer, or a pointer to a float, we can have a
pointer to an array.
Example
The declaration int (*q)[4] means that q is a pointer to an array of 4 integers.
Pointer to an array is very useful while passing a 2d array to function.
Program code:
#include<stdio.h>
#include<conio.h>
void third_largest(int,int *);
void main()
{
int i,num[50];
clrscr();
printf("Enter elements of array:");
for(i=0;i<10;i++)
{
scanf("%d",&num[i]);
}
third_largest(10,num);

Himal Chand Thapa


printf("Third largest element=%d",*(num+7));
getch();
}
void third_largest(int x,int *n) //in place of *n you can declare n[] why?
{
int i,j,temp;
for(i=0;i<x;i++)
{
for(j=0;j<x-1;j++)
{
if(*(n+j)>*(n+j+1))
{
temp=*(n+j);
*(n+j)=*(n+j+1);
*(n+j+1)=temp;
}
} } }

8. Write a program in C to read the following information for 96 students


name, roll number marks obtained(in 100). Record all data in “hcoe.txt” file.
The program should print roll number and name of student who have
obtained marks greater than or equal to 60.
#include<stdio.h>
#include<conio.h>
struct student
{
char name[50];
int rollno;
int marks;
};
void main()
{
struct student s[10],st[10];
int i;
FILE *fp;
clrscr();
printf("Enter name rollno and marks of student:");
for(i=0;i<10;i++)
{
scanf("%s%d%d",s[i].name,&s[i].rollno,&s[i].marks);

Himal Chand Thapa


}

fp=fopen("hcoe.txt","wb");
if(fp==NULL)
{
printf("File can not be created!!!");
exit();
}
fwrite(&s,sizeof(s),10,fp); //writing to file
fclose(fp);

fp=fopen("hcoe.txt","rb");
if(fp==NULL)
{
printf("File can not be created!!!");
exit();
}

fread(&st,sizeof(st),10,fp); //reading from file

printf("\nName\tRollno\tmarks\n");
for(i=0;i<10;i++)
{
if(st[i].marks>=60)
{
printf("%s\t%d\t%d\n",st[i].name,st[i].rollno,st[i].marks);
}
}
fclose(fp);
getch();
}

Final Re-Assessment 2073 (Set-A)


(Solution)
1. a) Define term actual and formal arguments. In how many ways we can
pass arguments to a function? Explain with example

Arguments written in function definition is called “formal arguments” where as


arguments written in function call is called “actual arguments”

void main()
Himal Chand Thapa
{
int a,b,c;
c=display(a,b); //calling program
}
void display(int x,int y) //called function
{
------------
------------
}
x, y are “formal argument” and a, b are “actual argument”
The major difference between actual and formal arguments is that actual arguments are
the source of information; calling programs pass actual arguments to called functions.
The called functions access the information using corresponding formal arguments.
In c language we can pass arguments to function in two ways:
i. call by reference
- while passing parameter using call by reference, we are passing the
actual address of the variable to the called function.
- Any updates made inside the called function will modify the original copy
since we are directly modifying the content of the exact memory location.
Example:

ii. call by value

- While passing parameters using call by value, xerox copy of original


parameter is created and passed to the called function.
- Any update made inside method will no affect the original value of variable
in calling function.
Example:

b) Write a program to calculate sum of digits of a given number entered by the


user using recursive function.
#include<stdio.h>
#include<conio.h>
int sum_of_digits(int n);
void main()
{
int num,sum;
clrscr();
printf("Enter the number:");
scanf("%d",&num);
sum=sum_of_digits(num);
printf("Sum of digits=%d",sum);

Himal Chand Thapa


getch();
}
int sum_of_digits(int n)
{
if(n==0)
return n;
else
return (n%10+sum_of_digits(n/10));
}

Write a program to find highest common factor of two given number using
recursive function.
#include<stdio.h>
#include<conio.h>
int hcf(int m,int n);
void main()
{
int n1,n2,h;
clrscr();
printf("Enter two number:");
scanf("%d%d",&n1,&n2);
h=hcf(n1,n2);
printf("hcf of given number=%d",h);
getch();
}
int hcf(int m,int n)
{
if(m==0)
return n;
else if(n==0)
return m;
else
return (hcf(n,m%n));
}
2. a) Explain how array can be passed to function? Write a program using a
function that returns the largest number from an array of numbers that is
passed to the functions.
Array elements can be passed to a function by calling the function by value and
function by reference.

Himal Chand Thapa


Program code:
#include<stdio.h>
#include<conio.h>
int largest(int num[],int);
void main()
{
int num[10],i,x;
clrscr();
printf("Enter the element of array:");
for(i=0;i<10;i++)
{
scanf("%d",&num[i]);
}
x=largest(num,10);
printf("Largest numberin array=%d",x);
getch();
}
int largest(int num[],int n)
{ int i,j,temp;
for(i=0;i<n;i++)
{
for(j=0;j<n-1;j++)
{
if(num[j]>num[j+1])
{
temp=num[j];
num[j]=num[j+1];
num[j+1]=temp;
}
}
}
return num[n-1];
}

Or(by using pointer)


#include<stdio.h>
#include<conio.h>
void largest(int *num,int);
void main()
{

Himal Chand Thapa


int num[10],i,x;
clrscr();
printf("Enter the element of array:");
for(i=0;i<10;i++)
{
scanf("%d",&num[i]);
}
largest(num,10);
printf("Largest numberin array=%d",*(num+9));
getch();
}
void largest(int *num,int n)
{ int i,j,temp;
for(i=0;i<n;i++)
{
for(j=0;j<n-1;j++)
{
if(*(num+j)>*(num+j+1))
{
temp=*(num+j);
*(num+j)=*(num+j+1);
*(num+j+1)=temp;
}
}
}
}
b) Compare array and pointer with example. Write a program to read a 3*3 matrix.
Find the minimum integer value of a matrix, replace the diagonal elements by the
minimum element and display it using pointer.
There is close relationship between array and pointer. The pointer can be used to
access array elements, accessing the whole array using pointer arithmetic, makes the
accessing faster. The basic difference between a pointer and an array is, an array is a
collection of variables of similar data type whereas the pointer is a variable that stores
the address of another variable.
Basis for comparison Array Pointer
Declaration int a[5]; int *p;
Working Stores the value of the Stores the address of the
variable of homogenous another variable of same
data ty data type as the pointer
variables data type
generation An array of pointers can be A pointer to an array can be

Himal Chand Thapa


generated generated.
Example: int *a[5]; Example:
Int *p,a[5];
p=a;

Program code:
#include<stdio.h>
#include<conio.h>
void main()
{
int num[3][3],i,j,min;
clrscr();
printf("Enter the element of array:");
for(i=0;i<3;i++)
{
for(j=0;j<3;j++)
{
scanf("%d",&num[i][j]);
}
}
min=num[0][0];
for(i=0;i<3;i++) //finding minimum element of matrix
{
for(j=0;j<3;j++)
{
if(num[i][j]<min)
{
min=num[i][j];
}
}
}
for(i=0;i<3;i++) //replacing diagonal element by minimum element
{
for(j=0;j<3;j++)
{
if(i==j)
{
num[i][j]=min;
}
}
}

Himal Chand Thapa


printf("Matrix element:\n");
for(i=0;i<3;i++)
{
for(j=0;j<3;j++)
{
printf("%d\t",*(*(num+i)+j));
}
printf("\n");
}
getch();
}
What do you mean by void pointer? Write a program to multiply two 3*3 matrix.
Two matrix are input from main() function and pass to a user defined function.
The result is also displayed from main function.
A void pointer is a pointer that has no associated data type with it. A void pointer can
hold address of any type and can be type casted to any type.
Example:
int a=7;
char b=’g’;
void *p=&a; // void pointer holds address of integer
p=&b; // void pointer holds address of character

Note: void pointer doesn’t have any data type associated with it. It can store address of
any type of variable.
Program code:
#include<stdio.h>
#include<conio.h>
void product(int mat1[][3],int mat2[][3],int prod[][3]);
void main()
{
int mat1[3][3],mat2[3][3],prod[3][3],i,j,min;
clrscr();
printf("Enter the element of first matrix:");
for(i=0;i<3;i++)
{
for(j=0;j<3;j++)
{
scanf("%d",&mat1[i][j]);
}
}

Himal Chand Thapa


printf("Enter the element of second matrix:");
for(i=0;i<3;i++)
{
for(j=0;j<3;j++)
{
scanf("%d",&mat2[i][j]);
}
}
product(mat1,mat2,prod);
printf("Product of first and second matrix:\n");
for(i=0;i<3;i++)
{
for(j=0;j<3;j++)
{
printf("%d\t",prod[i][j]);
}
printf("\n");
}
getch();
}
void product(int mat1[][3],int mat2[][3],int prod[][3])
{
int i,j,sum=0,k;
for(i=0;i<3;i++)
{
for(j=0;j<3;j++)
{
sum=0;
for(k=0;k<3;k++)
{
sum=sum+mat1[i][k]*mat2[k][j];
}
prod[i][j]=sum;
}
}
}
3. a) What is pointer? What type of arithmetic operations can be implemented in
pointer? Write down the relationship of array and pointer with appropriate syntax
and example.
A pointer is a variable whose value is the address of another variable.

Himal Chand Thapa


Pointer declaration:
int *pt; // here pt is integer pointer variable

int a;
pt=&a; //pt holds address of integer variable a;

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 do numeric value.
Valid pointer arithmetic operations:
a) Adding a number to pointer
b) Subtracting a number to pointer
c) Incrementing a pointer
d) Decrementing a pointer
e) Subtracting two pointers
f) Comparison on two pointers
Invalid pointer arithmetic operations:
a) Addition of two pointers
b) Division of two pointers
c) Multiplication of two pointers
Relationship between pointer and array:
A pointer variable is used to store the address of another variable while an array is used
to group related data items of same data type. The name of the array is a pointer to the
first element of the array. That means it holds the address of the first element of the
array.
The name of the array is a constant pointer which contains the memory address of the
first element of array.
Example:
Int a[10];
Int *ptr;
In above statement, we declare an array ‘a’ of 10 integers and a pointer to an integer
ptr. This pointer may contain a memory address of an integer.
ptr=arr;
In fact when we write num[i], the C compiler internally converts it to *(num+i). This
means that all the following notations are same:
num[i];
*(num+i);
*(i+num);
i[num];

Himal Chand Thapa


b) What is string? Define fgets() and fputs() with example. Write a program to
concatenate two strings given by user without using library function.
String is one dimensional array of characters terminated by null character ‘\0’.
Example:
char name[8]={‘r’,’a’,’m’,’a’,’y’,’a’,’n’,’\0’};
or
char name[8]=”ramayan”;
fgets():
it is used to read string from file.
Syntax:
fgets (string, int_value, file_pointer_variable);
here int_value denotes the number of character in a string.
fputs():
it is used to write a string to a file.
Syntax:
fputs(string, file_ptr_variable)
program code:
#include<stdio.h>
#include<conio.h>
void main()
{
char str1[50],str2[20];
int i,length=0,j;
clrscr();
printf("Enter first string:");
gets(str1);
printf("Enter second string:");
gets(str2);
for(i=0;str1[i]!='\0';i++)
{
length++;
}
printf("length=%d\n",length);
for(j=0;str2[j]!='\0';j++)
{
str1[length+j]=str2[j];
}
str1[length+j]='\0';
printf( "string after conactenation:\n");
puts(str1);

Himal Chand Thapa


getch();
}

b) How is one dimensional and two dimensional arrays created and initialized in C?
Explain with example. Write a program to reverse a string given by user without using
library function.
One dimensional Array:
Array declaration (creation) syntax
data_type arr_name [arr_size];
example:
int age [5];
Array initialization syntax:
data_type arr_name [arr_size]=(value1, value2, value3,….);
Example:
int age[5]={0, 1, 2, 3, 4};

Two dimensional Array:


Array declaration(creation) syntax:
data_type arr_name [num_of_rows][num_of_column];
int matrix[3][4];
Array initialization syntax:
int matrix[2][2] = {5,6,7,5};

#include<stdio.h>
#include<conio.h>
void main()
{
char str[20],temp;
int i,length=0;
clrscr();
printf("Enter first string:");
gets(str);
for(i=0;str[i]!='\0';i++)
{
length++;
}

for(i=0;i<length/2;i++)
{
temp=str[i];
str[i]=str[length-i-1];

Himal Chand Thapa


str[length-i-1]=temp;
}
printf( "Reverse string is:\n");
puts(str);
getch();
}
4. a) Why should we prefer structure over array? Explain about “array within
structure” and “array of structure “with example.
We should prefer structure over array because of following reason:
 Structure can store heterogeneous values (Different Data types) where as Array
stores values of homogeneous types(Similar Data type)
 Structure can even hold the value of an array. But the reverse is not possible.
 Can define an array of structures.
Array of structure:
Structure is collection of different data type. An object of structure represents a single record in
memory, if we want more than one record of structure type, we have to create an array of
structure or object.
In another word Structure is used to store the information of One particular object but if we
need to store more than one such objects then Array of Structure is used.
Example:
struct bookinfo
{
char bookname[50];
int pages;
int prices;
}book[100];

Explanation:

1. Here Book structure is used to Store the information of one Book.


2. In case if we need to store the Information of 100 books then Array of Structure is
used.
3. book[0] stores the Information of 1st Book , book[1] stores the information of 2nd
Book and So on We can store the information of 100 books.

Array within structure:


structure is collection of different data type. Like normal data type, It can also store an
array as well. That is we can declare member of structure as array.
Syntax for array within structure
Struct struct_name
{
Datatype var1; //structure normal member

Himal Chand Thapa


Datatype marks[size]; //structure member declared as array( array within structure)
……………
…………..
Datatype varN;
};

b) Create a structure named student that has name, roll and marks as
members Assume appropriate types and size of members. Use this
structure to read and display records of 10 students. Create two functions:
one is to read information of students and other to display the information.
#include<stdio.h>
#include<conio.h>
struct student
{
char name[50];
int roll;
int marks;
};
void read(struct student s[]);
void display(struct student s[]);

void main()
{
struct student s[10];
clrscr();
read(s);
display(s);
getch();
}
void read(struct student s[])
{
int i;
for(i=0;i<10;i++)
{
printf("Enter name:");
scanf("%s",s[i].name);
printf("Enter rollno:");
scanf("%d",&s[i].roll);
printf("Enter marks:");
scanf("%d",&s[i].marks);
}

Himal Chand Thapa


}
void display(struct student s[])
{
int i;
printf("\nName\tRollno\tMarks\n");
for(i=0;i<10;i++)
{
printf("%s\t%d\t%d\n",s[i].name,s[i].roll,s[i].marks);
}
}

Write a program to read name and age of 10 different students as the two
members of structure named “students”. Display the name and corresponding
age of the students sorted in alphabetical order.
#include<stdio.h>
#include<conio.h>
#include<string.h>
struct student
{
char name[50];
int age;
};
void main()
{
int i,j;
struct student s[10],temp;
clrscr();
for(i=0;i<10;i++)
{
printf("Enter name:");
scanf("%s",s[i].name);
printf("Enter age:");
scanf("%d",&s[i].age);
}
for(i=0;i<10;i++)
{
for(j=0;j<9;j++)
{

Himal Chand Thapa


if(strcmp(s[j].name,s[j+1].name)>0)
{
temp=s[j];
s[j]=s[j+1];
s[j+1]=temp;
}
}
}
printf("\nName\tAge\n");
for(i=0;i<10;i++)
{
printf("%s\t%d\n",s[i].name,s[i].age);
}
getch();
}

5. a) what is random access file in C? Explain file operation and file opening modes.
Random access refers to the ability to access data at random that the file can be
accessed at any point . C supports following functions for random access file
processing.

 fseek()
 ftell()
 rewind()

fseek():
This function is used for seeking the pointer position in the file at the specified byte.
Syntax: fseek( file pointer, displacement, pointer position);
Where
file pointer ---- It is the pointer which points to the file.
displacement ---- It is positive or negative.This is the number of bytes which are skipped
backward (if negative) or forward( if positive) from the current position.This is attached with
L because this is a long integer.

Pointer position:
This sets the pointer position in the file.

Value pointer position

0 beginning of file
1 current position
2 End of file

Example: fseek(p,10L,0)

Himal Chand Thapa


0 means pointer positions is on beginning of the file from this statement pointer position
is skipped 10 bytes from the beginning of the file.

fseek( p,5L,1)

1 means current position of the pointer position. From this statement pointer position is
skipped 5 bytes forward from the current position.

fseek(p,-5L,1)

From this statement pointer position is skipped 5 bytes backward from the current
position.

ftell()
This function returns the value of the current pointer position in the file. The value is
count from the beginning of the file.
Syntax: ftell(fptr);
Where fptr is a file pointer.
rewind()
This function is used to move the file pointer to the beginning of the given file.
Syntax: rewind(fptr);
Where fptr is a file pointer.
File operation:

The basic file operations are

 fopen - open a file- specify how its opened (read/write) and type (binary/text)
 fclose - close an opened file
 fread - read from a file
 fwrite - write to a file
 fseek - move a file pointer to somewhere in a file.
 ftell - tell you where the file pointer is located.

File opening modes:


When you open a file, you must specify how it is to be opened. This means whether to
create it from new overwrite it and whether it's text or binary, read or write and if you
want to append to it. This is done using one or more file mode specifiers which are
single letters "r", "b", "w", "a" and +.

"r" - Opens the file for reading. This fails if the file does not exist or cannot be found.

"w" - Opens the file as an empty file for writing. If the file exists, its contents are
destroyed.

Himal Chand Thapa


"a" - Opens the file for writing at the end of the file (appending) without removing the
EOF marker before writing new data to the file; this creates the file first if it doesn't exist.

Adding + to the file mode creates three new modes:

"r+" Opens the file for both reading and writing. (The file must exist.)

"w+" Opens the file as an empty file for both reading and writing. If the file exists, its
contents are destroyed.
"a+" Opens the file for reading and appending; the appending operation includes the
removal of the EOF marker before new data is written to the file and the EOF marker is
restored after writing is complete; creates the file first if it doesn't exist.

b) Write a program to read name and phone number of 10 students. Write them on
a file and close it. Reopen the file and display the data on it.

#include<stdio.h>
#include<conio.h>
struct student
{
char name[50];
char phone_no[20];
};
void main()
{
FILE *fp;
struct student s[3],st[3];
int i;
clrscr();
printf("Enter student information:\n");
for(i=0;i<3;i++)
{
printf("Enter name:");
scanf("%s",s[i].name);
printf("Enter phone number:");
scanf("%s",s[i].phone_no);
}
fp=fopen("myfile.txt","wb");
if(fp==NULL)
{
printf("File can't be created...");

Himal Chand Thapa


exit(0);
}
fwrite(&s,sizeof(s),3,fp);
fclose(fp);
fp=fopen("myfile.txt","rb");
if(fp==NULL)
{
printf("File can't be created...");
exit(0);
}
fread(&st,sizeof(st),3,fp);
printf("Name\tPhone_NO\n");
for(i=0;i<3;i++)
{
printf("\n%s\t%s\n",st[i].name,st[i].phone_no);
}
fclose(fp);
getch();
}
WAP to take contents of a file and copies them into another file character by
character and display the content
#include<stdio.h>
#include<conio.h>
void main()
{
char ch,ch1;
FILE *fp,*fp1;
clrscr();
fp=fopen("a.txt","r");
fp1=fopen("b.txt","w");
do
{
ch=fgetc(fp);
fputc(ch,fp1);
}while(ch!=EOF);
fclose(fp);
fclose(fp1);
fp1=fopen("b.txt","r");
do
{

Himal Chand Thapa


ch1=fgetc(fp1);
printf("%c",ch1);
}while(ch1!=EOF);
fclose(fp1);
getch();
}
Set B
1. a) What are storage classes? Differentiate between library function an d user
defined functions with example.
In C language, each variable has a storage class which decides scope, visibility and
lifetime of that variable. The following storage classes are most oftenly used in C
programming,
 Automatic variables
 External variables(Global variables)
 Static variables
 Register variables
Automatic variables:
A variable declared inside a function without any storage class specification, is by
default an automatic variable. They are created when a function is called and are
destroyed automatically when the function exits. Automatic variables can also be
called local variables because they are local to a function. By default they are
assigned garbage value by the compiler.
int a;
Or
auto int a;
External variables:
A variable that is declared outside any function is a Global variable. Global variables
remain available throughout the entire program. One important thing to remember about
global variable is that their values can be changed by any function in the program.

Himal Chand Thapa


Static variables:
A static variable tells the compiler to persist the variable until the end of program.
Instead of creating and destroying a variable every time when it comes into and goes
out of scope, static is initialized only once and remains into existence till the end of
program.
They are assigned 0 (zero) as default value by the compiler.
Register variable:
Register variable inform the compiler to store the variable in register instead of
memory. Register variable has faster access than normal variable. Frequently used
variables are kept in register. Only few variables can be placed inside register.
NOTE : We can never get the address of such variables.
Syntax:
register int num;
Built in function(Library function):
 Built in functions are the functions that are provided by C library.
 Defined in a special header file.
 These functions perform file access, mathematical computations, graphics,
memory management etc.
 To use built in function appropriate header files should be included.
 Example of built in function and corresponding header file
Header files Built in function defined
stdio.h printf(),scanf(),gets(),fclose()puts() etc
conio.h clrscr(),getch() etc.
math.h pow(),sqrt(),log(),sin() etc.
string.h strlen(),strcpy,strcmp() etc

User defined function:


 The functions which are developed by user at the time of writing a program are
called user defined functions. So, user defined functions are functions created
and developed by user.
 User defined function has three parts: functions declaration (function prototype),
function call and function definition.
 A function declaration tells the compiler about a function's name, return type,
and parameters. A function definition provides the actual body of the function.
 To use a function, you will have to call that function to perform the defined task.
 user-defined functions can be categorized as:
o Function with no arguments and no return value
o Function with no arguments and a return value
o Function with arguments and no return value
o Function with arguments and a return value.

Himal Chand Thapa


Example:
#include<stdio.h>
#include<conio.h>
int larger(int a,int b); // function declaration

void main()
{
int i,j,k;
clrscr();
i=99;
j=112;
k=larger(i,j); // function call (Arguments used here are called actual arguments)
printf("%d",k);
getch();
}

int larger(int a,int b) // function declaration(Arguments here used are called formal arguments)
{
if(a>b)
return a;
else
return b;
}
b) WAP to check whether a given number is Armstrong number or not using
recursive function.
#include<stdio.h>
#include<conio.h>
int armstrong(int a);
void main()
{
int n,temp;
clrscr();
printf("Enter number:");
scanf("%d",&n);
temp=armstrong(n);
if(temp==n)
printf("%d is an armstrong number",n);
else
printf("%d is not an armstrong number",n);

Himal Chand Thapa


getch();
}
int armstrong(int a)
{
int sum=0;
if(a==0)
return a;
else
{
return ((a%10)*(a%10)*(a%10))+armstrong(a/10);
}
}
WAP to find sum of natural number up to n using recursive function.
#include<stdio.h>
#include<conio.h>
int sum(int a);
void main()
{
int n,temp;
clrscr();
printf("Enter number:");
scanf("%d",&n);
temp=sum(n);
printf("Sum=%d",temp);
getch();
}
int sum(int a)
{
if(a==0)
return a;
else
{
return (a+sum(a-1));
}
}
2. a) Differentiate call by value and call by reference. WAP that passes an
array to function and find largest and smallest elements of an array and
display the result there. And also display sum of largest and smallest
element in main().
#include<stdio.h>

Himal Chand Thapa


#include<conio.h>
int sum(int a[]);
void main()
{
int i,n[10],s;
clrscr();
printf("Enter array element:\n");
for(i=0;i<10;i++)
{
scanf("%d",&n[i]);
}
s=sum(n);
printf("Sum=%d",s);
getch();
}
int sum(int a[])
{
int i,j,temp;
for(i=0;i<10;i++)
{
for(j=0;j<9;j++)
{
if(a[j]>a[j+1])
{
temp=a[j];
a[j]=a[j+1];
a[j+1]=temp;
}
}
}
printf("Largest numberin array=%d\n",a[9]);
printf("Smallest number in array=%d\n",a[0]);
return (a[0]+a[9]);
}
3. Explain string, array of string and multidimensional array with example. What do
you mean by dereferencing of a pointer? Explain with example.
String:
 C Strings are array of characters ended with null character (‘\0’).
 This null character indicates the end of the string.
 Strings are always enclosed by double quotes. Whereas, character is enclosed by
single quotes in C.

Himal Chand Thapa


 To hold the null character at the end of the array, the size of the character
array containing the string is one more than the number of characters .
Example:
char greeting[6]={‘H’, ’e’, ’l’, ’l’, ’0’, ’\0’};
Or
char greeting[]=”Hello”;

array of string:
A string is an array of characters; so, an array of strings is an array of arrays of
characters.
The maximum size is the same for all the strings stored in a two dimensional
array. We can declare a two dimensional character array of MAX strings of
size SIZE as follows:
char names[MAX][SIZE];

Example:
char name[5][20]; //may be used to store a list of 5 names, each of
length not more than 20 characters.

Initialization of array of string:


Char name[5][20]={“Yash”, “Dolma”, “Himalaya”, “Neenu”, “Himanshu”};

Dereferencing a pointer:
 Asterisk(*) indirection operator is used along with pointer variable while
Dereferencing the pointer variable.
 Asterisk Operator is also called as value at operator
 When used with Pointer variable, it refers to variable being pointed to,this is
called as Dereferencing of Pointers
 Dereferencing Operation is performed to access or manipulate data contained in
memory location pointed to by a pointer
 Any Operation performed on the de-referenced pointer directly affects the value
of variable it pointes to.

Example:
int x=5,a;
int *ptr;
ptr=&x;
a=*ptr;

WAP to sort string in ascending order


#include<stdio.h>
#include<conio.h>
#include<string.h>
void main()
{

Himal Chand Thapa


char name[4][10],temp[10];
int i,j;
clrscr();
printf("Enter names:");
for(i=0;i<4;i++)
{
scanf("%s",name[i]);
}
for(i=0;i<4;i++)
{
for(j=0;j<3;j++)
{
if(strcmp(name[j],name[j+1])>0)
{
strcpy(temp,name[j]);
strcpy(name[j],name[j+1]);
strcpy(name[j+1],temp);
}
}
}
printf("Sorted string:\n");
for(i=0;i<4;i++)
{
printf("%s\t",name[i]);
}
getch();
}

b) Explain different string handling function along with their syntax. WAP to test
whether a given string is palindrome or not.
String handling functions in C language are defined in string.h header file. Hence you
need to include this header file whenever you use these string handling functions in
your program.All these functions take either character pointer or character arrays as
arguments. Following are some of the string handling functions supported by C.

1. strlen()
2. strcpy()
3. strncpy()
4. strcat()
5. strcmp() etc..
strlen()
strlen() function returns the length of the string. strlen() function returns integer value.

strcpy()
strcpy() function is used to copy one string to another. The Destination_String should be

Himal Chand Thapa


a variable and Source_String can either be a string constant or a variable.
Syntax:
strcpy(Destination_String,Source_String);

strcat()
strcat() is used to concatenate two strings.
The Destination_String should be a variable and Source_String can either be a string
constant or a variable.
Syntax:
strcat(Destination_String, Source_String);

strcmp()
strcmp() function is use two compare two strings. strcmp() function does a case
sensitive comparison between two strings. The Destination_String and Source_String
can either be a string constant or a variable.
Syntax:
int strcmp(string1, string2);
This function returns integer value after comparison.
Value returned is 0 if two strings are equal.
If the first string is alphabetically greater than the second string then, it returns a positive
value.
If the first string is alphabetically less than the second string then, it returns a negative
value

other are:
strlwr() converts string to lowercase
strupr() converts string to uppercase
strrev() reverse the given string

4. a) Explain how pointer can be used in C? Write down its advantage. WAP to
find the sum of two numbers using user defined function. Use concept of
pointer.
Pointers are used (in the C language) in three different ways:
 To create dynamic data structures.
 To pass and handle variable parameters passed to functions.
 To access information stored in arrays.
Advantage of pointer:
 Pointers provide direct access to memory
 Pointers provide a way to return more than one value to the functions
 Reduces the storage space and complexity of the program

Himal Chand Thapa


 Reduces the execution time of the program
 Provides an alternate way to access array elements
 Pointers can be used to pass information back and forth between the calling
function and called function.
 Pointers allow us to perform dynamic memory allocation and de-allocation.
 Pointers helps us to build complex data structures like linked list, stack, queues,
trees, graphs etc.
 Addresses of objects can be extracted using pointers
 Passing on arrays by pointers saves lot of memory because we are passing on
only the address of array instead of all the elements of an array, which would
mean passing on copies of all the elements and thus taking lot of memory space.
Disadvantage of pointer:
 Dynamically allocated block needs to be freed explicitly. Otherwise, it would lead
to memory leak.
 Pointers are slower than normal variables.
 If pointers are updated with incorrect values, it might lead to memory corruption.
Program Code:
#include<stdio.h>
#include<conio.h>
int sum(int *a,int *b);
void main()
{
int x,y,s;
clrscr();
printf("Enter two numbers:");
scanf("%d%d",&x,&y);
s=sum(&x,&y);
printf("Sum=%d",s);
getch();
}
int sum(int *a,int *b)
{
int c;
c=*a+*b;
return c;
}
b) Define a structure to hold the roll no of a student and marks obtained by him in 5
subjects. Declare an array to hold the data of 20 students. Pass this to function that
displays the marks of student who has a highest total marks.
#include<stdio.h>
#include<conio.h>

Himal Chand Thapa


struct student
{
int rollno;
int marks[3];
int totalmarks;
}s[5];
void process(struct student s[5]);
void main()
{
clrscr();
process(s);
getch();
}
void process(struct student s[5])
{
int i,j,roll,sum,max;
struct student temp;
for(i=0;i<5;i++)
{
printf("Enter rollno:");
scanf("%d",&s[i].rollno);
printf("Enter marks in six subject:");
sum=0;
for(j=0;j<3;j++)
{
scanf("%d",&s[i].marks[j]);
sum=sum+s[i].marks[j];
}
s[i].totalmarks=sum;

}
for(i=0;i<5;i++)
{
for(j=0;j<4;j++)
{
if(s[j].totalmarks<s[j+1].totalmarks)
{
temp=s[j];
s[j]=s[j+1];
s[j+1]=temp;
}

Himal Chand Thapa


}
}
printf("\nRollno\tTotal marks\n");
printf("%d\t%d",s[0].rollno,s[0].totalmarks);
}

5. WAP that reads two matrix of order mxn and pxq using function
readMatrix(). The program should contain a function processMatrix() that
takes the matrices and multiplies them. The result of multiplication must be
displayed using a function showMatrix().

#include<stdio.h>
#include<conio.h>
void readMatrix (int [][10],int,int );
void processMatrix (int a[][10],int b[][10],int mul[][10],int r,int c,int c1);
void showMatrix (int c[][10],int r,int c1);
void main()
{
int r,c,r1, c1,a[10][10],b[10][10],mul[10][10];
clrscr();
printf("Enter number of row and column for matrixA:");
scanf("%d%d",&r,&c);
printf("Enter number of row and column for matrixB:");
scanf("%d%d",&r1,&c1);
if(c==r1)
{
readMatrix(a,r,c);
readMatrix(b,c,c1);
processMatrix(a,b,mul,r,c,c1);
showMatrix(mul,c,c1);
}
else
printf("Multiplication can't be performed...");
getch();
}

void readMatrix(int a[][10],int r,int c)


{

Himal Chand Thapa


int i,j;
printf("Enter Matrix:\n");
for(i=0;i<r;i++)
{
for(j=0;j<c;j++)
{
scanf("%d",&a[i][j]);
}
}
}

void processMatrix(int a[][10],int b[][10],int mul[][10],int r,int c,int c1)


{
int i,j,k;
for(i=0;i<r;i++)
{
for(j=0;j<c1;j++)
{
mul[i][j]=0;
for(k=0;k<c;k++)
{
mul[i][j]+=a[i][k]*b[k][j];
}
}
}
}

void showMatrix(int c[][10],int r,int c1)


{
int i,j;
for(i=0;i<r;i++)
{
for(j=0;j<c1;j++)
{
printf("%d\t",c[i][j]);
}
printf("\n");
}
}

Himal Chand Thapa

You might also like