C Solution PDF
C Solution PDF
C Solution PDF
(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);
}
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;
}
}
}
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;
}
}
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.
#include <stdio.h>
struct student
{
char name[50];
int roll;
};
#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");
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;
++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()
{
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.
{ {
}std; }*std
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.
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);
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();
}
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();
}
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:
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.
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;
}
}
}
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]);
}
}
int a;
pt=&a; //pt holds address of integer variable a;
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};
#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];
Explanation:
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);
}
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++)
{
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.
0 beginning of file
1 current position
2 End of file
Example: fseek(p,10L,0)
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:
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.
"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.
"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...");
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);
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.
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;
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
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
}
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;
}
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();
}