SlideShare uma empresa Scribd logo
1 de 28
Baixar para ler offline
1
1901006 – PROGRAMMING IN C
(COMMON TO AGRI, CIVIL, MECH, EEE AND EIE)
UNIT – 3 QUESTION BANK QUESTIONS WITH ANSWER
PART-A
1. Define function. How will you declare it?
A function is a set of instructions which are used to perform a specific or particular task. The general
syntax of function declaration is return_type function_name(argument_list);
Example: int factorial(int n);
2. What are the various parts of functions?
The function has three parts.
i. The Function header or Prototype or declaration
ii. The Function Body or Definition
iii. The Function Invocation or Call
3. Express the difference between function declaration and function definition.
Function Declaration Function Definition
Function declaration is also called as
function prototype. It tells the compiler the
details like name of the function, return
type of the function, memory space
needed etc.
Function definition also called as function
body. It contains executable and non-
executable statements.
Every function must be declared before
calling. It must be place before main( )
function.
It performs a particular task repeatedly.
4. What is function call?
Function call is also called as function invocation. We need to call every function declared already.
Each function is called from the main function.
Example:
Int square (int ); // Function prototype
Void main( )
{
Int n,s;
Printf(“nEnter the value of n”);
Scanf(“%d”, &n);
S = square(n); // Function call
Printf(“n The square of the number is..%d”, s);
2
getch();
}
Int square (int a) // Function definition
{
return a*a;
}
5. Write any two applications of recursive function.
i. Towers of Hanoi Problem
ii. Printing all subsets of array
iii. Merge sort algorithm
6. Differentiate between call by value and call reference.
The main difference between call by value and call by address is that, in call by value, the values of
the actual parameters copy to the formal parameters of the function while in call by address,
the addresses of the actual parameters copy to the formal parameter of the function.
7. Why is scope of variable necessary in function?
A scope is a region of the program, and the scope of variables refers to the area of the program
where the variables can be accessed after its declaration. In C every variable defined in scope. In
functions, we have to use local as well as global variable. Global variables have to be accessed
throughout the program where local variables are having the scope only within that function.
8. Write a function in C to find the square of any number.
// Finding the square of the number
Int square (int ); // Function prototype
void main( )
{
Int n,s;
Printf(“nEnter the value of n”);
Scanf(“%d”, &n);
S = square(n); // Function call
Printf(“n The square of the number is..%d”, s);
getch();
}
Int square (int a) // Function definition
{
return a*a;
}
3
9. Point out the meaning of user-defined function.
A function is a block of code that performs a specific task. C allows you to define functions according
to your need. These functions are known as user-defined functions. For example: Suppose, you need
to create a circle and color it depending upon the radius and color.
A user defined function is a programmed routine that has its parameters set by the user of the
system. User defined functions often are seen as programming shortcuts as they define
functions that perform specific tasks within a larger system, such as a database or spreadsheet
program.
10. What is meant by library function?
Library functions in C language are inbuilt functions which are grouped together and placed in a
common place called library. All C standard library functions are declared in many header files which
are saved as file name. h. Actually, function declaration, definition for macros are given in all header
files.
11. Show the difference in call by value and reference using a simple programming example.
Call By Value:
#include<stdio.h>
Void swap(int, int);
Void main( )
{
Int a=10, b=20;
Printf(“nBefore swapping values are ..%d%d”, a,b);
Swap(a, b);
Printf(“nAfter swapping values are ..%d%d”, a,b);
getch( );
}
Void swap( int x, int y)
{
Int t;
t = x;
x = y;
y = t;
printf(“nSwapping inside values are ..%d%d”, a,b);
}
Output: Before swapping values are …. 10 20
swapping inside values are …. 20 10
After swapping values are …. 10 20
Call By Reference:
#include<stdio.h>
Void swap(int *, int *);
Void main( )
{
Int a=10, b=20;
4
Printf(“nBefore swapping values are ..%d%d”, a,b);
Swap(&a, &b);
Printf(“nAfter swapping values are ..%d%d”, a,b);
getch( );
}
Void swap(int *x, int *y )
{
Int t;
t = *x;
*x = *y;
*y = t;
}
Output: Before swapping values are …. 10 20
After swapping values are …. 20 10
12. When will be the library function used?
Library functions or pre-defined functions are the functions whose functionality has already been
developed by someone and are available to the user for use. We can use library function, when we
perform operations like mathematical operations, string operations and I/O operations.
Example: printf( ), scanf( ) are library functions and are defined in stdio.h header file. In order to use
the library functions, the corresponding header files are included in the program.
13. What will be output of the following?
#include <stdio.h>
Int incr(int i)
{
static int count = 0;
count = count + i;
printf("count=%dn",count);
}
void main()
{
Int i,j;
for (i = 0; i <=4; i++)
j = incr(i);
}
Output: The loop is executed five times. Count = 0, count = 1, count = 3, count = 6, count = 10.
14. Invent the output of the following code:
#include<stdio.h>
int A=2;
int B=3;
int Add()
{
return A + B;
}
5
int main()
{
int answer;
A = 5;
B = 7;
answer = Add();
printf("%dn",answer);
return 0;
}
Output: 12
15. What is a recursive function?
Recursion is a technique that can be used to solve the problems that can be expressed in terms of
similar problems with smaller size. In recursive programming, a function that calls itself is known as a
recursive function.
Example: The factorial of a number n can be expressed in terms of a similar problem of smaller size
as n! = n × (n–1)!
16. Specify the need for function.
Functions provide better readability by modularizing or dividing a complex program into
subprograms that are simpler, manageable, easier to solve as compared to the original program.
Functions enable code reuse. The commonly required functions are developed and kept in standard
libraries for the use in the form of library functions.
The other advantages of functions include:
1. Reduction in code redundancy.
2. Reusability
3. Information hiding,
4. Improved debugging and testing,
5. Improved maintainability.
17. Point out the error in the program
#include<stdio.h>
int main()
{
int a=10;
void f();
a = f();
printf("%dn", a);
return 0;
}
void f()
{
printf("a");
}
Output: Error : Not an allowed type. We can’t assign a void function to an integer.
6
18. What is no argument and no return value in a function?
A function with no input and no output does not accept any input and does not return any result.
Example: #include<stdio.h>
#include<conio.h>
Printsum( );
Void main( )
{
Printsum( );
}
Void Printsum( )
{
Printf(“n Sum of 2 and 3 is…%d”, 2+3);
}
Output is : 5
The above function is not taking any input and does not return any result.
19. Narrate how to apply user-defined function.
User defined functions are the functions that are defined by the user at the time of writing a
program. The user develops the functionality by writing the body of the function. These functions are
sometimes referred to as programmer-defined functions.
Example: int add(int a, int b);
Double area_circle(int r);
20. Mention the advantage of pass by reference.
a. There is no copy of the argument made, hence, it is fast.
b. We can return multiple values from a function.
PART-B
1. Describe about user defined function and predefined function with an example. (13).
Functions in C can be classified into two types.
i. User Defined function
ii. Predefined functions or Library functions.
User Defined Function
User defined functions are the functions that are defined by the user at the time of writing a
program. The user develops the functionality by writing the body of the function. These functions are
sometimes referred to as programmer-defined functions.
Example: int add(int a, int b);
Double area_circle(int r);
Any function in c has three parts:
a. Function Declaration (or) Function Prototype
b. Function Definition
c. Function Call (or) Function Invocation
7
Function declaration is also called as function prototype. It tells the compiler the details like name of
the function, return type of the function, memory space needed etc. Every function must be declared
before calling. It must be place before main( ) function.
Example: double Area_Circumfernce(int r, float PI);
Function definition also called as function body. It contains executable and non-executable
statements. It performs a particular task repeatedly.
Function call is also called as function invocation. We need to call every function declared already.
Each function is called from the main function. We should pass arguments to the function call before
invoke.
Example:
#include<stdio.h>
Void swap(int, int); // Function Prototype or Declaration
Void main( )
{
Int a=10, b=20;
Printf(“nBefore swapping values are ..%d%d”, a,b);
Swap(a, b); // Function Call
Printf(“nAfter swapping values are ..%d%d”, a,b);
getch( );
}
Void swap( int x, int y) // Function Definition
{
Int t;
t = x;
x = y;
y = t;
printf(“nSwapping inside values are ..%d%d”, a,b);
}
Output: Before swapping values are …. 10 20
swapping inside values are …. 20 10
After swapping values are …. 10 20
Predefined functions or Library functions.
Library functions or pre-defined functions are the functions whose functionality has already been
developed by someone and are available to the user for use. We can use library function, when we
perform operations like mathematical operations, string operations and I/O operations.
Example: printf( ), scanf( ) are library functions and are defined in stdio.h header file. In order to use
the library functions, the corresponding header files are included in the program.
The various predefined functions used as mathematical operations are as follows:
8
Function Description
floor ( )
This function returns the nearest integer which is less than or equal to the argument
passed to this function.
round ( )
This function returns the nearest integer value of the float/double/long double argument
passed to this function. If decimal value is from “.1 to .5”, it returns integer value less
than the argument. If decimal value is from “.6 to .9”, it returns the integer value
greater than the argument.
ceil ( )
This function returns nearest integer value which is greater than or equal to the
argument passed to this function.
sin ( ) This function is used to calculate sine value.
cos ( ) This function is used to calculate cosine.
cosh ( ) This function is used to calculate hyperbolic cosine.
exp ( ) This function is used to calculate the exponential “e” to the xth
power.
tan ( ) This function is used to calculate tangent.
tanh ( ) This function is used to calculate hyperbolic tangent.
sinh ( ) This function is used to calculate hyperbolic sine.
log ( ) This function is used to calculate natural logarithm.
log10 ( ) This function is used to calculate base 10 logarithm.
sqrt ( ) This function is used to find square root of the argument passed to this function.
pow ( ) This is used to find the power of the given number.
trunc.(.)
This function truncates the decimal value from floating point value and returns integer
value.
2. Write a code in C to get the largest element of an array using function. Analyze the code with
sample input 25,5,8,89 and 70.(13).
Program:
int main()
{
int array[100], maximum, size, c, location = 1;
printf("Enter the number of elements in arrayn");
scanf("%d", &size);
printf("Enter %d integersn", size);
for (c = 0; c < size; c++)
scanf("%d", &array[c]);
maximum = array[0];
for (c = 1; c < size; c++)
{
if (array[c] > maximum)
{
maximum = array[c];
location = c+1;
}
}
9
printf("Maximum element is present at location %d and it's value is %d.n", location,
maximum);
return 0;
}
Output:
Enter the number of elements in array
5
Enter 5 integers
25 5 8 89 70
Maximum element present at location 4 and its value is 89.
3. Apply a recursive function in C for reverse a sentence. (13).
Program:
#include <stdio.h>
Void reverseSentence();
int main()
{
printf("Enter a sentence: ");
reverseSentence();
return 0;
}
Void reverseSentence()
{
char c;
scanf("%c", &c);
if( c != 'n')
{
reverseSentence();
printf("%c",c);
}
}
Output
Enter a sentence: margorp emosewa
awesome program
4. Discuss about the classification of functions depending upon their inputs and output (parameters).
Depending upon their inputs and outputs, functions are classified as follows:
i. Functions with no input-output.
ii. Functions with inputs and no output.
iii. Functions with inputs and one output.
iv. Functions with inputs and outputs.
10
(i). A function with no input and no output does not accept any input and does not return any
result.
Example: #include<stdio.h>
#include<conio.h>
Printsum( );
Void main( )
{
Printsum( );
}
Void Printsum( )
{
Printf(“n Sum of 2 and 3 is…%d”, 2+3);
}
Output is : 5
The above function is not taking any input and does not return any result.
(ii). A function with inputs and no output accepts any input and does not return any result.
Example: #include<stdio.h>
#include<conio.h>
Void Printsum( int, int);
Void main( )
{
Int a,b;
Printf(“nEnter the values of a and b”);
Scanf(“%d%d”, &a,&b);
Printsum( a,b);
getch();
}
Void Printsum(int x, int y )
{
Printf(“n Sum of %d and %d is…%d”, x,y,x+y);
}
Output is : Enter the values of a and b 5 6
Sum of 5 and b is…11
(iii). A function with inputs and one output accepts any input and does return result.
Example: #include<stdio.h>
#include<conio.h>
Circle_area( int);
Void main( )
{
Int radius;
float area;
Printf(“nEnter the radius of circle”);
Scanf(“%d”, &radius);
area = Circle_area(radius);
11
printf(“n The area of the circle is %f”, area);
getch();
}
Circle_area(int radius )
{
return (3.1428 * radius * radius);
}
Output is : Enter the radius of the circle 2
The area of the circle is..12.00000
(Iv). A function with inputs and outputs.
A function can accept many inputs and return more than one output.
Program
#include<stdio.h>
void swap (int, int);
void main()
{
int a = 10, b = 20;
printf (“Before swap values are %d %dn”, a, b);
swap (a, b);
printf (“After swap values are %d %dn”, a, b);
}
void swap (int x, int y)
{
x = x + y;
y = x – y;
x = x – y;
printf (“In swap function values are %d %dn”, x, y);
}
Output:
Before swap values are 10 20
In swap function values are 20 10
After swap values are 10 20
On the execution of the function call, i.e. swap (a, b);, the values of actual arguments a & b are copied into the
formal parameters x & y. Formal parameters occupy separate memory locations. A change made in the formal
parameters is independent of the actual arguments. On returning from called function, formal parameters are
destroyed and access to actual arguments gives values that are unchanged.
5. Explain in detail about Pass by Value and Pass by reference. (13).
Depending upon whether the values or addresses (i.e. pointers) are passed as arguments to a function, the
argument passing methods in C language are classified as:
1. Pass by Value or Call by Value: In this method, the values of actual arguments are copied to the formal
parameters of the function. The changes made in the values of formal parameters inside the called function
are not reflected back to the calling function.
12
Program
#include<stdio.h>
void swap (int, int);
void main()
{
int a = 10, b = 20;
printf (“Before swap values are %d %dn”, a, b);
swap (a, b);
printf (“After swap values are %d %dn”, a, b);
}
void swap (int x, int y)
{
x = x + y;
y = x – y;
x = x – y;
printf (“In swap function values are %d %dn”, x, y);
}
Output:
Before swap values are 10 20
In swap function values are 20 10
After swap values are 10 20
On the execution of the function call, i.e. swap (a, b);, the values of actual arguments a & b are copied into the
formal parameters x & y. Formal parameters occupy separate memory locations. A change made in the formal
parameters is independent of the actual arguments. On returning from called function, formal parameters are
destroyed and access to actual arguments gives values that are unchanged.
2. Pass by Address or Call by Address or Call by Reference: In this method, the addresses of actual arguments
are passed to the formal parameters of the function. The changes made in the values pointed to by the formal
parameters in the called function are reflected back to the calling function.
#include<stdio.h>
void swap (int*, int*);
void main()
{
int a = 10, b = 20;
printf (“Before swap values are %d %dn”, a, b);
swap (&a, &b);
printf (“After swap values are %d %dn”, a, b);
}
void swap (int *x, int *y)
{
*x = *x + *y;
*y = *x – *y;
*x = *x – *y;
printf(“In swap function values are %d %dn”, *x, *y);
}
13
Output:
Before swap values are 10 20
In swap function values are 20 10
After swap values are 20 10
Addresses of the actual arguments are passed instead of their values. Changes made in the called function are
actually done in the memory locations of the actual arguments. On returning from the called function, the
formal parameters are destroyed but the changes made in the values pointed by the formal parameters are
reflected back to the calling function.
6. Discuss about passing arrays to function. (13).
Arrays can be passed to functions in two different ways:
1. Passing individual elements of an array one by one:
The individual elements of an array can be passed either by value of by reference. If the number of
elements in an array is large, passing the entire array will take a large number of function calls. As the
function calls are time consuming, this method of passing an array to a function will deteriorate the
performance of a program.
#include<stdio.h>
int add (int, int);
void main()
{
int a[10], n, i, s = 0;
printf ("Enter the no. of elements: ");
scanf ("%d", &n);
printf ("Enter elements of array:n");
for (i = 0; i < n; i++)
{
scanf ("%d", &a[i]);
s = add (a[i], s);
}
printf ("Sum is %d", s);
}
int add (int num, int sum)
{
return sum + num;
}
2. Passing entire array at a time is a preferred way of passing arrays to functions. The entire array
is always passed by reference. Passing One-dimensional Arrays to Functions:
The actual argument in the function call should only be the name of an array without any subscript.
The corresponding formal parameter in the function definition must be of array type or pointer type.
If a formal parameter is of array type, it will be implicitly converted to pointer type. The
corresponding parameter type in the function declaration should be of array type or pointer type.
14
#include<stdio.h>
void max_min (int[], int);
void main()
{
int a[10], n, i;
printf ("Enter the no. of elements: ");
scanf ("%d", &n);
printf ("Enter elements of array:n");
for (i = 0; i < n; i++)
scanf ("%d", &a[i]);
max_min (a, n);
printf ("Max is %dn", a[0]);
printf ("Min is %d", a[1]);
}
void max_min (int a[], int n)
{
int i, max = a[0], min = a[0];
for (i = 1; i < n; i++)
{
if (a[i] > max)
max = a[i];
else if (a[i] < min)
min = a[i];
}
a[0] = max;
a[1] = min;
}
Enter the no. of elements: 5
Enter elements of array:
2 4 5 7 1
Max is 7
Min is 1
Passing the entire array at a time is an efficient way of passing a number of values to a function.
7. Explain in detail about recursive function with sample code. (13)
Recursion is a powerful programming technique used to solve the problems that can be expressed in
terms of similar problems of smaller size. A function that calls itself is called recursive function, and
the phenomenon is called recursion. Every recursive function consists of two cases:
1. Base case: It forms the terminating condition of the recursion. There may be more than one base
case in a recursive function. Without the base case, the recursion will never terminate and will be
known as infinite recursion. For example, no == 1 is the base case of the recursive function fact.
15
2. Recursive case: In a recursive case, the problem is defined in terms of itself with a reduced
problem size. For example, when fact (n) is expressed as n * fact (n – 1), the size of the problem is
reduced from n to n – 1.
Program:
// Recursion to find the factorial of a number
#include<stdio.h>
int fact (int);
void main ()
{
int no, f;
printf (“Enter the number: ”);
scanf (“%d”, &no);
f = fact (no);
printf (“Factorial of %d is %d”, n, f);
}
// Definition of recursive function fact
int fact (int n)
{
if (n == 1)
return 1;
else
return n * fact (n – 1);
}
Output:
Enter the number: 5
Factorial of 5 is 120
8. Analyze with example code in C for global and local variables. (13).
Local variables
 The scope of local variables will be within the function only.
 These variables are declared within the function and can’t be accessed outside the function.
 In the below example, m and n variables are having scope within the main function only. These
are not visible to test function.
 Like wise, a and b variables are having scope within the test function only. These are not visible
to main function.
#include<stdio.h>
void test();
int main()
{
int m = 22, n = 44; // m, n are local variables of main function
printf("nvalues : m = %d and n = %d", m, n);
16
test();
}
void test()
{
int a = 50, b = 80; // a, b are local variables of test function
printf("nvalues : a = %d and b = %d", a, b);
}
Output:
values : m = 22 and n = 44
values : a = 50 and b = 80
Global Variables
 The scope of global variables will be throughout the program. These variables can be accessed
from anywhere in the program.
 This variable is defined outside the main function. So that, this variable is visible to main function
and all other sub functions.
#include<stdio.h>
void test();
int m = 22, n = 44;
int a = 50, b = 80;
int main()
{
printf("All variables are accessed from main function");
printf("nvalues: m=%d:n=%d:a=%d:b=%d", m,n,a,b);
test();
}
void test()
{
printf("nnAll variables are accessed from test function");
printf("nvalues: m=%d:n=%d:a=%d:b=%d", m,n,a,b);
}
Output:
All variables are accessed from main function
values : m = 22 : n = 44 : a = 50 : b = 80
All variables are accessed from test function
values : m = 22 : n = 44 : a = 50 : b = 80
9. Write notes on fixed argument functions and variable argument functions. (13)
Based upon the number of arguments a function accepts, functions are classified as follows:
1. Fixed Argument Functions: A function that accepts a fixed number of arguments is called a fixed
argument function. If the fixed argument function does not specify any default argument, invoking a
17
fixed argument function with a lesser number of arguments than expected leads to a compilation
error.
A fixed argument function cannot even be invoked by supplying more number of arguments than
expected. For example, pow function defined in math.h header file expects two arguments of type
double. The following invocations of pow function are invalid.
pow (); //Lesser number of arguments supplied than expected
pow (2.0); //Lesser number of arguments supplied than expected
pow (2.0, 1.5, 1.0); //More number of arguments supplied than expected
2. Variable Argument Functions: A function that accepts a variable number of arguments is called a
variable argument function. For example, printf is a variable argument function, which can accept
one or more arguments. The type of first argument must be char* and there is no constraint about
the type of rest of the arguments. The following calls to printf function are valid:
printf (“Hello”); // Only one argument of type char*
printf (“%d”,2); // Two arguments. The type of the first argument is char* and the second is int
printf (“%s %s”,“Hi”,“!!”); // Three arguments, all of type char*
The number of arguments that can be passed to a variable argument function is not fixed. Hence,
while declaring a variable argument function, it is not possible to list the types of all the arguments
that might be passed to the function during the function call. The solution to this problem is provided
by ellipses (…).
The presence of ellipses tells the compiler that when the function is called, zero or more arguments
may follow and that the type of the arguments is not known. Ellipses used in the declaration of the
variable argument function suspend the type checking.
Program:
#include<stdarg.h>
#include<stdio.h>
int sum(int no_of_arguments,...);
main()
{
int result;
result=sum(3,12,13,14);
printf("The result of addition of 3 numbers is %dn",result);
result=sum(5,10,20,30,40,50);
printf("The result of addition of 5 numbers is %dn",result);
}
int sum(int no_of_arguments,...)
{
int arg,i=0,total=0;
va_list ptr;
18
va_start (ptr,no_of_arguments);
arg=va_arg(ptr,int);
while(i++<no_of_arguments)
{
total+=arg;
arg=va_arg(ptr,int);
}
va_end(ptr);
return total;
}
Output:
The result of addition of 3 numbers is 39
The result of addition of 5 numbers is 150
The variable argument functions are developed with the help of macros va_start, va_arg, va_end,
declared in the header file stdarg.h. This header file also declares a type va_list that holds the
information needed by the macros va_arg and va_end.
The macro va_start takes two parameters ptr and lastfix. The type of the first parameter ptr is va_list
and lastfix is the last fixed parameter supplied to the variable argument function. The last fixed
parameter supplied to the variable argument function sum is no_of_arguments and is of type int. The
macro va_start sets ptr to point to the first of the variable arguments being passed to the function.
The macro va_arg is used to return the arguments in the variable list. The first time va_arg is used, it
returns the first argument in the list. Each successive time va_arg is used, it returns the next
argument in the list. The macro va_arg returns the values of type given to it as its second argument.
The order in which the macros should be called is:
va_start must be called before the first call to va_arg or va_end.
va_end should be called after va_arg has read all the arguments.
10. Write the C program to find the value of sin(x) using the series up to the given accuracy (without
using user defined function) also print sin(x) using library function. (13)
/* Value of Sine using Recursion (Taylor's theorem) */
#include<stdio.h>
float srs(float x,int i);
float term(float x,int i);
int main()
{
float x,y;
int i;
printf("enter the value of xn");
19
scanf("%f",&x);
i=1;
y=srs(x,i);
printf("the sum is equals to %f",y);
return 0;
}
float srs(float x,int i)
{
float sum=0.0;
float t;
t= term(x,i);
if(i%2==0&&t>(-.000001))
{
return 0;
}
else if(i%2!=0&&t<(.000001))
{
return 0;
}
else
{
sum=t+ srs(x,i+1);
}
return sum;
}
float term(float x,int i)
{
float tn;
int h;
tn=x;
for(h=2;h<2*i;h++)
{
tn= (x*tn)/h;
}
if(i%2==0)
{
tn= tn*(-1.0);
return tn;
}
20
else
{
return tn;
}
}
11. Write a C program for Scientific calculator using built-in functions(13)
#include<stdio.h>
#include<conio.h>
#include<math.h>
int main(void) {
int choice, i, a, b;
float x, y, result;
clrscr();
do {
printf(“nSelect your operation (0 to exit):n”);
printf(“1. Additionn2. Subtractionn3. Multiplicationn4. Divisionn”);
printf(“5. Square rootn6. X ^ Yn”);
printf(“15. log10(x)n”);
printf(“17. Sin(X)n18. Cos(X)n19. Tan(X)n20. Cosec(X)n”);
printf(“21. Cot(X)n22. Sec(X)n”);
printf(“Choice: “);
scanf(“%d”, &choice);
if(choice == 0) exit(0);
switch(choice) {
case 1:
printf(“Enter X: “);
scanf(“%f”, &x);
printf(“nEnter Y: “);
scanf(“%f”, &y);
result = x + y;
printf(“nResult: %f”, result);
break;
case 2:
printf(“Enter X: “);
scanf(“%f”, &x);
printf(“nEnter Y: “);
scanf(“%f”, &y);
result = x – y;
printf(“nResult: %f”, result);
break;
case 3:
printf(“Enter X: “);
21
scanf(“%f”, &x);
printf(“nEnter Y: “);
scanf(“%f”, &y);
result = x * y;
printf(“nResult: %f”, result);
break;
case 4:
printf(“Enter X: “);
scanf(“%f”, &x);
printf(“nEnter Y: “);
scanf(“%f”, &y);
result = x / y;
printf(“nResult: %f”, result);
break;
case 5:
printf(“Enter X: “);
scanf(“%f”, &x);
result = sqrt(x);
printf(“nResult: %f”, result);
break;
case 6:
printf(“Enter X: “);
scanf(“%f”, &x);
printf(“nEnter Y: “);
scanf(“%f”, &y);
result = pow(x, y);
printf(“nResult: %f”, result);
break;
case 15:
printf(“Enter X: “);
scanf(“%f”, &x);
result = log10(x);
printf(“nResult: %.2f”, result);
break;
case 17:
printf(“Enter X: “);
scanf(“%f”, &x);
result = sin(x * 3.14159 / 180);
printf(“nResult: %.2f”, result);
break;
case 18:
printf(“Enter X: “);
22
scanf(“%f”, &x);
result = cos(x * 3.14159 / 180);
printf(“nResult: %.2f”, result);
break;
case 19:
printf(“Enter X: “);
scanf(“%f”, &x);
result = tan(x * 3.14159 / 180);
printf(“nResult: %.2f”, result);
break;
case 20:
printf(“Enter X: “);
scanf(“%f”, &x);
result = 1 / (sin(x * 3.14159 / 180));
printf(“nResult: %.2f”, result);
break;
case 21:
printf(“Enter X: “);
scanf(“%f”, &x);
result = 1 / tan(x * 3.14159 / 180);
printf(“nResult: %.2f”, result);
break;
case 22:
printf(“Enter X: “);
scanf(“%f”, &x);
result = 1 / cos(x * 3.14159 / 180);
printf(“nResult: %.2f”, result);
break;
default:
printf(“nInvalid Choice!”);
}
} while(choice);
getch();
return 0;
}
12. Write the C coding for swapping of two numbers using pass by reference.(13)
Pass by Address or Call by Address or Call by Reference: In this method, the addresses of actual
arguments are passed to the formal parameters of the function. The changes made in the values
pointed to by the formal parameters in the called function are reflected back to the calling function.
23
#include<stdio.h>
void swap (int*, int*);
void main()
{
int a = 10, b = 20;
printf (“Before swap values are %d %dn”, a, b);
swap (&a, &b);
printf (“After swap values are %d %dn”, a, b);
}
void swap (int *x, int *y)
{
*x = *x + *y;
*y = *x – *y;
*x = *x – *y;
printf(“In swap function values are %d %dn”, *x, *y);
}
Output:
Before swap values are 10 20
In swap function values are 20 10
After swap values are 20 10
Addresses of the actual arguments are passed instead of their values. Changes made in the called
function are actually done in the memory locations of the actual arguments. On returning from the
called function, the formal parameters are destroyed but the changes made in the values pointed by
the formal parameters are reflected back to the calling function.
13. Write a C program to sort the given N names using function. (13)
#include<stdio.h>
#include<string.h>
int main()
{
int i,j,count;
char str[25][25],temp[25];
puts("How many strings u are going to enter?: ");
scanf("%d",&count);
puts("Enter Strings one by one: ");
for(i=0;i<count;i++)
gets(str[i]);
for(i=0;i<count-1;i++)
{
for(j=i+1;j<count;j++)
{
24
if(strcmp(str[i],str[j])>0)
{
strcpy(temp,str[i]);
strcpy(str[i],str[j]);
strcpy(str[j],temp);
}
}
}
printf("Order of Sorted Strings:");
for(i=0;i<=count;i++)
puts(str[i]);
return 0;
}
14. Explain about any 4 library functions in c. (13).
Function Description
floor ( )
This function returns the nearest integer which is less than or equal to the argument
passed to this function.
round ( )
This function returns the nearest integer value of the float/double/long double argument
passed to this function. If decimal value is from “.1 to .5”, it returns integer value less
than the argument. If decimal value is from “.6 to .9”, it returns the integer value greater
than the argument.
ceil ( )
This function returns nearest integer value which is greater than or equal to the
argument passed to this function.
sin ( ) This function is used to calculate sine value.
cos ( ) This function is used to calculate cosine.
cosh ( ) This function is used to calculate hyperbolic cosine.
exp ( ) This function is used to calculate the exponential “e” to the xth
power.
tan ( ) This function is used to calculate tangent.
tanh ( ) This function is used to calculate hyperbolic tangent.
sinh ( ) This function is used to calculate hyperbolic sine.
log ( ) This function is used to calculates natural logarithm.
log10 ( ) This function is used to calculates base 10 logarithm.
sqrt ( ) This function is used to find square root of the argument passed to this function.
pow ( ) This is used to find the power of the given number.
trunc.(.)
This function truncates the decimal value from floating point value and returns integer
value.
25
PART-C
1. Develop a C program for binary search using recursive function.(15)
Recursion is programming technique where a function calls itself to solve a smaller problem that is of
the same type as the original problem. The recursive call (calling itself) continues until the function
can produce a result trivially without making any more calls.
In the program below, the function binarysearch takes four parameters - the array to be searched,
the lowest position of the search range, highest position of the search range, and the element to be
searched.
The first time you call the binary search function with the entire range of the array. So you set the
lowest position to 0 and highest position to the length of the array minus one. With each recursive
call the search range becomes smaller and smaller until you find the search element.
#include<stdio.h>
int binarysearch(int a[], int low, int high, int x)
{
int mid = (low + high) / 2;
if (low > high)
return -1;
if (a[mid] == x)
return mid;
if (a[mid] < x)
return binarysearch(a, mid + 1, high, x);
else
return binarysearch(a, low, mid-1, x);
}
int main(void)
{
int a[100];
int len, pos, search_item;
printf("Enter the length of the arrayn");
scanf("%d", &len);
printf("Enter the array elementsn");
for (int i=0; i<len; i++)
scanf("%d", &a[i]);
printf("Enter the element to searchn");
scanf("%d", &search_item);
pos = binarysearch(a,0,len-1,search_item);
if (pos < 0 )
printf("Cannot find the element %d in the array.n", search_item);
else
printf("The position of %d in the array is %d.n", search_item, pos+1);
return 0;
}
26
2. Examine with example program to display all prime numbers between two intervals using
functions.
#include <stdio.h>
int isPrime(int num);
void printPrimes(int n, int m);
int main()
{
int n,m;
printf("Enter the lower and upper limit to list primes: ");
scanf("%d%d", &n, &m);
printPrimes(n,m);
return 0;
}
void printPrimes(int n, int m)
{
printf("All prime number between %d to %d are: ", n,m);
while(n<= m)
{
// Print if current number is prime.
if(isPrime(n))
{
printf("%d, ", n);
}
n++;
}
}
intisPrime(int num)
{
int i;
for(i=2; i<=num/2; i++)
{
if(num % i == 0)
{
return 0;
}
}
return 1;
}
Output
Enter the lower and upper limit to list primes 20 50
Prime numbers between 20 and 50 are: 23 29 31 37 41 43 47
27
3. Develop a C program for towers of Hanoi using recursive function.(15)
This C Program uses recursive function & solves the tower of hanoi. The tower of hanoi is a
mathematical puzzle. It consists of three rods, and a number of disks of different sizes which can slide
onto any rod. The puzzle starts with the disks in a neat stack in ascending order of size on one rod,
the smallest at the top. We have to obtain the same stack on the third rod.
Here is the source code of the C program for solving towers of hanoi.
#include <stdio.h>
void towers(int, char, char, char);
int main()
{
int num;
printf("Enter the number of disks : ");
scanf("%d", &num);
printf("The sequence of moves involved in the Tower of Hanoi are :n");
towers(num, 'A', 'C', 'B');
return 0;
}
void towers(int num, char frompeg, char topeg, char auxpeg)
{
if (num == 1)
{
printf("n Move disk 1 from peg %c to peg %c", frompeg, topeg);
return;
}
towers(num - 1, frompeg, auxpeg, topeg);
printf("n Move disk %d from peg %c to peg %c", num, frompeg, topeg);
towers(num - 1, auxpeg, topeg, frompeg);
}
Output:
Enter the number of disks : 3
The sequence of moves involved in the Tower of Hanoi are :
Move disk 1 from peg A to peg C
Move disk 2 from peg A to peg B
Move disk 1 from peg C to peg B
Move disk 3 from peg A to peg C
Move disk 1 from peg B to peg A
Move disk 2 from peg B to peg C
Move disk 1 from peg A to peg C
28
4. Illustrate a C program for cube of a number using pass by reference.(15)
Program
#include<stdio.h>
int cube (int*);
void main()
{
int a, b;
printf (“n Enter the number”);
scanf (“%d”, &a);
b = cube (&a);
printf (“The cube of the number is %dn”, b);
}
Int cube (int *x)
{
return (*x * *x * *x);
}
Output:
Enter the number…5
The cube of the number is ..125
**********

Mais conteúdo relacionado

Mais procurados

Mais procurados (19)

Function C programming
Function C programmingFunction C programming
Function C programming
 
Functions in c
Functions in cFunctions in c
Functions in c
 
Function
FunctionFunction
Function
 
Presentation on function
Presentation on functionPresentation on function
Presentation on function
 
Function in C Language
Function in C Language Function in C Language
Function in C Language
 
Function in C program
Function in C programFunction in C program
Function in C program
 
Functions in C
Functions in CFunctions in C
Functions in C
 
C function
C functionC function
C function
 
lets play with "c"..!!! :):)
lets play with "c"..!!! :):)lets play with "c"..!!! :):)
lets play with "c"..!!! :):)
 
C function presentation
C function presentationC function presentation
C function presentation
 
C language for Semester Exams for Engineers
C language for Semester Exams for Engineers C language for Semester Exams for Engineers
C language for Semester Exams for Engineers
 
User defined functions in C programmig
User defined functions in C programmigUser defined functions in C programmig
User defined functions in C programmig
 
C and C++ functions
C and C++ functionsC and C++ functions
C and C++ functions
 
Functions in c
Functions in cFunctions in c
Functions in c
 
Functions
FunctionsFunctions
Functions
 
Functions in c language
Functions in c language Functions in c language
Functions in c language
 
Pointers and call by value, reference, address in C
Pointers and call by value, reference, address in CPointers and call by value, reference, address in C
Pointers and call by value, reference, address in C
 
User defined functions
User defined functionsUser defined functions
User defined functions
 
Function in C and C++
Function in C and C++Function in C and C++
Function in C and C++
 

Semelhante a Unit 3 (1)

function in in thi pdf you will learn what is fu...
function in  in thi pdf you will learn   what                           is fu...function in  in thi pdf you will learn   what                           is fu...
function in in thi pdf you will learn what is fu...
kushwahashivam413
 

Semelhante a Unit 3 (1) (20)

unit_2.pptx
unit_2.pptxunit_2.pptx
unit_2.pptx
 
CH.4FUNCTIONS IN C_FYBSC(CS).pptx
CH.4FUNCTIONS IN C_FYBSC(CS).pptxCH.4FUNCTIONS IN C_FYBSC(CS).pptx
CH.4FUNCTIONS IN C_FYBSC(CS).pptx
 
unit_2 (1).pptx
unit_2 (1).pptxunit_2 (1).pptx
unit_2 (1).pptx
 
unit3 part2 pcds function notes.pdf
unit3 part2 pcds function notes.pdfunit3 part2 pcds function notes.pdf
unit3 part2 pcds function notes.pdf
 
Unit_5Functionspptx__2022_12_27_10_47_17 (1).pptx
Unit_5Functionspptx__2022_12_27_10_47_17 (1).pptxUnit_5Functionspptx__2022_12_27_10_47_17 (1).pptx
Unit_5Functionspptx__2022_12_27_10_47_17 (1).pptx
 
Unit-III.pptx
Unit-III.pptxUnit-III.pptx
Unit-III.pptx
 
Functionincprogram
FunctionincprogramFunctionincprogram
Functionincprogram
 
Presentation on Function in C Programming
Presentation on Function in C ProgrammingPresentation on Function in C Programming
Presentation on Function in C Programming
 
Functions IN CPROGRAMMING OF ENGINEERING.pptx
Functions IN CPROGRAMMING OF ENGINEERING.pptxFunctions IN CPROGRAMMING OF ENGINEERING.pptx
Functions IN CPROGRAMMING OF ENGINEERING.pptx
 
USER DEFINED FUNCTIONS IN C.pdf
USER DEFINED FUNCTIONS IN C.pdfUSER DEFINED FUNCTIONS IN C.pdf
USER DEFINED FUNCTIONS IN C.pdf
 
C FUNCTIONS
C FUNCTIONSC FUNCTIONS
C FUNCTIONS
 
VIT351 Software Development VI Unit1
VIT351 Software Development VI Unit1VIT351 Software Development VI Unit1
VIT351 Software Development VI Unit1
 
Preprocessor directives
Preprocessor directivesPreprocessor directives
Preprocessor directives
 
Presentation 2 (1).pdf
Presentation 2 (1).pdfPresentation 2 (1).pdf
Presentation 2 (1).pdf
 
Functions
Functions Functions
Functions
 
Lecture 1_Functions in C.pptx
Lecture 1_Functions in C.pptxLecture 1_Functions in C.pptx
Lecture 1_Functions in C.pptx
 
Chap 5 c++
Chap 5 c++Chap 5 c++
Chap 5 c++
 
Function
FunctionFunction
Function
 
Ch4 functions
Ch4 functionsCh4 functions
Ch4 functions
 
function in in thi pdf you will learn what is fu...
function in  in thi pdf you will learn   what                           is fu...function in  in thi pdf you will learn   what                           is fu...
function in in thi pdf you will learn what is fu...
 

Mais de Sowri Rajan (11)

Unit 5 dwqb ans
Unit 5 dwqb ansUnit 5 dwqb ans
Unit 5 dwqb ans
 
Unit 2
Unit 2Unit 2
Unit 2
 
Unit 1
Unit 1Unit 1
Unit 1
 
Unit 5 quesn b ans5
Unit 5 quesn b ans5Unit 5 quesn b ans5
Unit 5 quesn b ans5
 
Unit 5 quesn b ans5
Unit 5 quesn b ans5Unit 5 quesn b ans5
Unit 5 quesn b ans5
 
Unit 4 qba
Unit 4 qbaUnit 4 qba
Unit 4 qba
 
Unit 4 qba
Unit 4 qbaUnit 4 qba
Unit 4 qba
 
Unitii string
Unitii stringUnitii string
Unitii string
 
Unitii classnotes
Unitii classnotesUnitii classnotes
Unitii classnotes
 
Uniti classnotes
Uniti classnotesUniti classnotes
Uniti classnotes
 
Program flowchart
Program flowchartProgram flowchart
Program flowchart
 

Último

Call Girls in Ramesh Nagar Delhi 💯 Call Us 🔝9953056974 🔝 Escort Service
Call Girls in Ramesh Nagar Delhi 💯 Call Us 🔝9953056974 🔝 Escort ServiceCall Girls in Ramesh Nagar Delhi 💯 Call Us 🔝9953056974 🔝 Escort Service
Call Girls in Ramesh Nagar Delhi 💯 Call Us 🔝9953056974 🔝 Escort Service
9953056974 Low Rate Call Girls In Saket, Delhi NCR
 
AKTU Computer Networks notes --- Unit 3.pdf
AKTU Computer Networks notes ---  Unit 3.pdfAKTU Computer Networks notes ---  Unit 3.pdf
AKTU Computer Networks notes --- Unit 3.pdf
ankushspencer015
 
Call for Papers - African Journal of Biological Sciences, E-ISSN: 2663-2187, ...
Call for Papers - African Journal of Biological Sciences, E-ISSN: 2663-2187, ...Call for Papers - African Journal of Biological Sciences, E-ISSN: 2663-2187, ...
Call for Papers - African Journal of Biological Sciences, E-ISSN: 2663-2187, ...
Christo Ananth
 

Último (20)

Water Industry Process Automation & Control Monthly - April 2024
Water Industry Process Automation & Control Monthly - April 2024Water Industry Process Automation & Control Monthly - April 2024
Water Industry Process Automation & Control Monthly - April 2024
 
Unit 1 - Soil Classification and Compaction.pdf
Unit 1 - Soil Classification and Compaction.pdfUnit 1 - Soil Classification and Compaction.pdf
Unit 1 - Soil Classification and Compaction.pdf
 
Call Girls in Ramesh Nagar Delhi 💯 Call Us 🔝9953056974 🔝 Escort Service
Call Girls in Ramesh Nagar Delhi 💯 Call Us 🔝9953056974 🔝 Escort ServiceCall Girls in Ramesh Nagar Delhi 💯 Call Us 🔝9953056974 🔝 Escort Service
Call Girls in Ramesh Nagar Delhi 💯 Call Us 🔝9953056974 🔝 Escort Service
 
data_management_and _data_science_cheat_sheet.pdf
data_management_and _data_science_cheat_sheet.pdfdata_management_and _data_science_cheat_sheet.pdf
data_management_and _data_science_cheat_sheet.pdf
 
Booking open Available Pune Call Girls Koregaon Park 6297143586 Call Hot Ind...
Booking open Available Pune Call Girls Koregaon Park  6297143586 Call Hot Ind...Booking open Available Pune Call Girls Koregaon Park  6297143586 Call Hot Ind...
Booking open Available Pune Call Girls Koregaon Park 6297143586 Call Hot Ind...
 
Call Girls Pimpri Chinchwad Call Me 7737669865 Budget Friendly No Advance Boo...
Call Girls Pimpri Chinchwad Call Me 7737669865 Budget Friendly No Advance Boo...Call Girls Pimpri Chinchwad Call Me 7737669865 Budget Friendly No Advance Boo...
Call Girls Pimpri Chinchwad Call Me 7737669865 Budget Friendly No Advance Boo...
 
Double Revolving field theory-how the rotor develops torque
Double Revolving field theory-how the rotor develops torqueDouble Revolving field theory-how the rotor develops torque
Double Revolving field theory-how the rotor develops torque
 
(INDIRA) Call Girl Meerut Call Now 8617697112 Meerut Escorts 24x7
(INDIRA) Call Girl Meerut Call Now 8617697112 Meerut Escorts 24x7(INDIRA) Call Girl Meerut Call Now 8617697112 Meerut Escorts 24x7
(INDIRA) Call Girl Meerut Call Now 8617697112 Meerut Escorts 24x7
 
PVC VS. FIBERGLASS (FRP) GRAVITY SEWER - UNI BELL
PVC VS. FIBERGLASS (FRP) GRAVITY SEWER - UNI BELLPVC VS. FIBERGLASS (FRP) GRAVITY SEWER - UNI BELL
PVC VS. FIBERGLASS (FRP) GRAVITY SEWER - UNI BELL
 
University management System project report..pdf
University management System project report..pdfUniversity management System project report..pdf
University management System project report..pdf
 
Call Girls Wakad Call Me 7737669865 Budget Friendly No Advance Booking
Call Girls Wakad Call Me 7737669865 Budget Friendly No Advance BookingCall Girls Wakad Call Me 7737669865 Budget Friendly No Advance Booking
Call Girls Wakad Call Me 7737669865 Budget Friendly No Advance Booking
 
Call for Papers - International Journal of Intelligent Systems and Applicatio...
Call for Papers - International Journal of Intelligent Systems and Applicatio...Call for Papers - International Journal of Intelligent Systems and Applicatio...
Call for Papers - International Journal of Intelligent Systems and Applicatio...
 
UNIT - IV - Air Compressors and its Performance
UNIT - IV - Air Compressors and its PerformanceUNIT - IV - Air Compressors and its Performance
UNIT - IV - Air Compressors and its Performance
 
(INDIRA) Call Girl Bhosari Call Now 8617697112 Bhosari Escorts 24x7
(INDIRA) Call Girl Bhosari Call Now 8617697112 Bhosari Escorts 24x7(INDIRA) Call Girl Bhosari Call Now 8617697112 Bhosari Escorts 24x7
(INDIRA) Call Girl Bhosari Call Now 8617697112 Bhosari Escorts 24x7
 
Roadmap to Membership of RICS - Pathways and Routes
Roadmap to Membership of RICS - Pathways and RoutesRoadmap to Membership of RICS - Pathways and Routes
Roadmap to Membership of RICS - Pathways and Routes
 
AKTU Computer Networks notes --- Unit 3.pdf
AKTU Computer Networks notes ---  Unit 3.pdfAKTU Computer Networks notes ---  Unit 3.pdf
AKTU Computer Networks notes --- Unit 3.pdf
 
ONLINE FOOD ORDER SYSTEM PROJECT REPORT.pdf
ONLINE FOOD ORDER SYSTEM PROJECT REPORT.pdfONLINE FOOD ORDER SYSTEM PROJECT REPORT.pdf
ONLINE FOOD ORDER SYSTEM PROJECT REPORT.pdf
 
Thermal Engineering Unit - I & II . ppt
Thermal Engineering  Unit - I & II . pptThermal Engineering  Unit - I & II . ppt
Thermal Engineering Unit - I & II . ppt
 
Call Girls Walvekar Nagar Call Me 7737669865 Budget Friendly No Advance Booking
Call Girls Walvekar Nagar Call Me 7737669865 Budget Friendly No Advance BookingCall Girls Walvekar Nagar Call Me 7737669865 Budget Friendly No Advance Booking
Call Girls Walvekar Nagar Call Me 7737669865 Budget Friendly No Advance Booking
 
Call for Papers - African Journal of Biological Sciences, E-ISSN: 2663-2187, ...
Call for Papers - African Journal of Biological Sciences, E-ISSN: 2663-2187, ...Call for Papers - African Journal of Biological Sciences, E-ISSN: 2663-2187, ...
Call for Papers - African Journal of Biological Sciences, E-ISSN: 2663-2187, ...
 

Unit 3 (1)

  • 1. 1 1901006 – PROGRAMMING IN C (COMMON TO AGRI, CIVIL, MECH, EEE AND EIE) UNIT – 3 QUESTION BANK QUESTIONS WITH ANSWER PART-A 1. Define function. How will you declare it? A function is a set of instructions which are used to perform a specific or particular task. The general syntax of function declaration is return_type function_name(argument_list); Example: int factorial(int n); 2. What are the various parts of functions? The function has three parts. i. The Function header or Prototype or declaration ii. The Function Body or Definition iii. The Function Invocation or Call 3. Express the difference between function declaration and function definition. Function Declaration Function Definition Function declaration is also called as function prototype. It tells the compiler the details like name of the function, return type of the function, memory space needed etc. Function definition also called as function body. It contains executable and non- executable statements. Every function must be declared before calling. It must be place before main( ) function. It performs a particular task repeatedly. 4. What is function call? Function call is also called as function invocation. We need to call every function declared already. Each function is called from the main function. Example: Int square (int ); // Function prototype Void main( ) { Int n,s; Printf(“nEnter the value of n”); Scanf(“%d”, &n); S = square(n); // Function call Printf(“n The square of the number is..%d”, s);
  • 2. 2 getch(); } Int square (int a) // Function definition { return a*a; } 5. Write any two applications of recursive function. i. Towers of Hanoi Problem ii. Printing all subsets of array iii. Merge sort algorithm 6. Differentiate between call by value and call reference. The main difference between call by value and call by address is that, in call by value, the values of the actual parameters copy to the formal parameters of the function while in call by address, the addresses of the actual parameters copy to the formal parameter of the function. 7. Why is scope of variable necessary in function? A scope is a region of the program, and the scope of variables refers to the area of the program where the variables can be accessed after its declaration. In C every variable defined in scope. In functions, we have to use local as well as global variable. Global variables have to be accessed throughout the program where local variables are having the scope only within that function. 8. Write a function in C to find the square of any number. // Finding the square of the number Int square (int ); // Function prototype void main( ) { Int n,s; Printf(“nEnter the value of n”); Scanf(“%d”, &n); S = square(n); // Function call Printf(“n The square of the number is..%d”, s); getch(); } Int square (int a) // Function definition { return a*a; }
  • 3. 3 9. Point out the meaning of user-defined function. A function is a block of code that performs a specific task. C allows you to define functions according to your need. These functions are known as user-defined functions. For example: Suppose, you need to create a circle and color it depending upon the radius and color. A user defined function is a programmed routine that has its parameters set by the user of the system. User defined functions often are seen as programming shortcuts as they define functions that perform specific tasks within a larger system, such as a database or spreadsheet program. 10. What is meant by library function? Library functions in C language are inbuilt functions which are grouped together and placed in a common place called library. All C standard library functions are declared in many header files which are saved as file name. h. Actually, function declaration, definition for macros are given in all header files. 11. Show the difference in call by value and reference using a simple programming example. Call By Value: #include<stdio.h> Void swap(int, int); Void main( ) { Int a=10, b=20; Printf(“nBefore swapping values are ..%d%d”, a,b); Swap(a, b); Printf(“nAfter swapping values are ..%d%d”, a,b); getch( ); } Void swap( int x, int y) { Int t; t = x; x = y; y = t; printf(“nSwapping inside values are ..%d%d”, a,b); } Output: Before swapping values are …. 10 20 swapping inside values are …. 20 10 After swapping values are …. 10 20 Call By Reference: #include<stdio.h> Void swap(int *, int *); Void main( ) { Int a=10, b=20;
  • 4. 4 Printf(“nBefore swapping values are ..%d%d”, a,b); Swap(&a, &b); Printf(“nAfter swapping values are ..%d%d”, a,b); getch( ); } Void swap(int *x, int *y ) { Int t; t = *x; *x = *y; *y = t; } Output: Before swapping values are …. 10 20 After swapping values are …. 20 10 12. When will be the library function used? Library functions or pre-defined functions are the functions whose functionality has already been developed by someone and are available to the user for use. We can use library function, when we perform operations like mathematical operations, string operations and I/O operations. Example: printf( ), scanf( ) are library functions and are defined in stdio.h header file. In order to use the library functions, the corresponding header files are included in the program. 13. What will be output of the following? #include <stdio.h> Int incr(int i) { static int count = 0; count = count + i; printf("count=%dn",count); } void main() { Int i,j; for (i = 0; i <=4; i++) j = incr(i); } Output: The loop is executed five times. Count = 0, count = 1, count = 3, count = 6, count = 10. 14. Invent the output of the following code: #include<stdio.h> int A=2; int B=3; int Add() { return A + B; }
  • 5. 5 int main() { int answer; A = 5; B = 7; answer = Add(); printf("%dn",answer); return 0; } Output: 12 15. What is a recursive function? Recursion is a technique that can be used to solve the problems that can be expressed in terms of similar problems with smaller size. In recursive programming, a function that calls itself is known as a recursive function. Example: The factorial of a number n can be expressed in terms of a similar problem of smaller size as n! = n × (n–1)! 16. Specify the need for function. Functions provide better readability by modularizing or dividing a complex program into subprograms that are simpler, manageable, easier to solve as compared to the original program. Functions enable code reuse. The commonly required functions are developed and kept in standard libraries for the use in the form of library functions. The other advantages of functions include: 1. Reduction in code redundancy. 2. Reusability 3. Information hiding, 4. Improved debugging and testing, 5. Improved maintainability. 17. Point out the error in the program #include<stdio.h> int main() { int a=10; void f(); a = f(); printf("%dn", a); return 0; } void f() { printf("a"); } Output: Error : Not an allowed type. We can’t assign a void function to an integer.
  • 6. 6 18. What is no argument and no return value in a function? A function with no input and no output does not accept any input and does not return any result. Example: #include<stdio.h> #include<conio.h> Printsum( ); Void main( ) { Printsum( ); } Void Printsum( ) { Printf(“n Sum of 2 and 3 is…%d”, 2+3); } Output is : 5 The above function is not taking any input and does not return any result. 19. Narrate how to apply user-defined function. User defined functions are the functions that are defined by the user at the time of writing a program. The user develops the functionality by writing the body of the function. These functions are sometimes referred to as programmer-defined functions. Example: int add(int a, int b); Double area_circle(int r); 20. Mention the advantage of pass by reference. a. There is no copy of the argument made, hence, it is fast. b. We can return multiple values from a function. PART-B 1. Describe about user defined function and predefined function with an example. (13). Functions in C can be classified into two types. i. User Defined function ii. Predefined functions or Library functions. User Defined Function User defined functions are the functions that are defined by the user at the time of writing a program. The user develops the functionality by writing the body of the function. These functions are sometimes referred to as programmer-defined functions. Example: int add(int a, int b); Double area_circle(int r); Any function in c has three parts: a. Function Declaration (or) Function Prototype b. Function Definition c. Function Call (or) Function Invocation
  • 7. 7 Function declaration is also called as function prototype. It tells the compiler the details like name of the function, return type of the function, memory space needed etc. Every function must be declared before calling. It must be place before main( ) function. Example: double Area_Circumfernce(int r, float PI); Function definition also called as function body. It contains executable and non-executable statements. It performs a particular task repeatedly. Function call is also called as function invocation. We need to call every function declared already. Each function is called from the main function. We should pass arguments to the function call before invoke. Example: #include<stdio.h> Void swap(int, int); // Function Prototype or Declaration Void main( ) { Int a=10, b=20; Printf(“nBefore swapping values are ..%d%d”, a,b); Swap(a, b); // Function Call Printf(“nAfter swapping values are ..%d%d”, a,b); getch( ); } Void swap( int x, int y) // Function Definition { Int t; t = x; x = y; y = t; printf(“nSwapping inside values are ..%d%d”, a,b); } Output: Before swapping values are …. 10 20 swapping inside values are …. 20 10 After swapping values are …. 10 20 Predefined functions or Library functions. Library functions or pre-defined functions are the functions whose functionality has already been developed by someone and are available to the user for use. We can use library function, when we perform operations like mathematical operations, string operations and I/O operations. Example: printf( ), scanf( ) are library functions and are defined in stdio.h header file. In order to use the library functions, the corresponding header files are included in the program. The various predefined functions used as mathematical operations are as follows:
  • 8. 8 Function Description floor ( ) This function returns the nearest integer which is less than or equal to the argument passed to this function. round ( ) This function returns the nearest integer value of the float/double/long double argument passed to this function. If decimal value is from “.1 to .5”, it returns integer value less than the argument. If decimal value is from “.6 to .9”, it returns the integer value greater than the argument. ceil ( ) This function returns nearest integer value which is greater than or equal to the argument passed to this function. sin ( ) This function is used to calculate sine value. cos ( ) This function is used to calculate cosine. cosh ( ) This function is used to calculate hyperbolic cosine. exp ( ) This function is used to calculate the exponential “e” to the xth power. tan ( ) This function is used to calculate tangent. tanh ( ) This function is used to calculate hyperbolic tangent. sinh ( ) This function is used to calculate hyperbolic sine. log ( ) This function is used to calculate natural logarithm. log10 ( ) This function is used to calculate base 10 logarithm. sqrt ( ) This function is used to find square root of the argument passed to this function. pow ( ) This is used to find the power of the given number. trunc.(.) This function truncates the decimal value from floating point value and returns integer value. 2. Write a code in C to get the largest element of an array using function. Analyze the code with sample input 25,5,8,89 and 70.(13). Program: int main() { int array[100], maximum, size, c, location = 1; printf("Enter the number of elements in arrayn"); scanf("%d", &size); printf("Enter %d integersn", size); for (c = 0; c < size; c++) scanf("%d", &array[c]); maximum = array[0]; for (c = 1; c < size; c++) { if (array[c] > maximum) { maximum = array[c]; location = c+1; } }
  • 9. 9 printf("Maximum element is present at location %d and it's value is %d.n", location, maximum); return 0; } Output: Enter the number of elements in array 5 Enter 5 integers 25 5 8 89 70 Maximum element present at location 4 and its value is 89. 3. Apply a recursive function in C for reverse a sentence. (13). Program: #include <stdio.h> Void reverseSentence(); int main() { printf("Enter a sentence: "); reverseSentence(); return 0; } Void reverseSentence() { char c; scanf("%c", &c); if( c != 'n') { reverseSentence(); printf("%c",c); } } Output Enter a sentence: margorp emosewa awesome program 4. Discuss about the classification of functions depending upon their inputs and output (parameters). Depending upon their inputs and outputs, functions are classified as follows: i. Functions with no input-output. ii. Functions with inputs and no output. iii. Functions with inputs and one output. iv. Functions with inputs and outputs.
  • 10. 10 (i). A function with no input and no output does not accept any input and does not return any result. Example: #include<stdio.h> #include<conio.h> Printsum( ); Void main( ) { Printsum( ); } Void Printsum( ) { Printf(“n Sum of 2 and 3 is…%d”, 2+3); } Output is : 5 The above function is not taking any input and does not return any result. (ii). A function with inputs and no output accepts any input and does not return any result. Example: #include<stdio.h> #include<conio.h> Void Printsum( int, int); Void main( ) { Int a,b; Printf(“nEnter the values of a and b”); Scanf(“%d%d”, &a,&b); Printsum( a,b); getch(); } Void Printsum(int x, int y ) { Printf(“n Sum of %d and %d is…%d”, x,y,x+y); } Output is : Enter the values of a and b 5 6 Sum of 5 and b is…11 (iii). A function with inputs and one output accepts any input and does return result. Example: #include<stdio.h> #include<conio.h> Circle_area( int); Void main( ) { Int radius; float area; Printf(“nEnter the radius of circle”); Scanf(“%d”, &radius); area = Circle_area(radius);
  • 11. 11 printf(“n The area of the circle is %f”, area); getch(); } Circle_area(int radius ) { return (3.1428 * radius * radius); } Output is : Enter the radius of the circle 2 The area of the circle is..12.00000 (Iv). A function with inputs and outputs. A function can accept many inputs and return more than one output. Program #include<stdio.h> void swap (int, int); void main() { int a = 10, b = 20; printf (“Before swap values are %d %dn”, a, b); swap (a, b); printf (“After swap values are %d %dn”, a, b); } void swap (int x, int y) { x = x + y; y = x – y; x = x – y; printf (“In swap function values are %d %dn”, x, y); } Output: Before swap values are 10 20 In swap function values are 20 10 After swap values are 10 20 On the execution of the function call, i.e. swap (a, b);, the values of actual arguments a & b are copied into the formal parameters x & y. Formal parameters occupy separate memory locations. A change made in the formal parameters is independent of the actual arguments. On returning from called function, formal parameters are destroyed and access to actual arguments gives values that are unchanged. 5. Explain in detail about Pass by Value and Pass by reference. (13). Depending upon whether the values or addresses (i.e. pointers) are passed as arguments to a function, the argument passing methods in C language are classified as: 1. Pass by Value or Call by Value: In this method, the values of actual arguments are copied to the formal parameters of the function. The changes made in the values of formal parameters inside the called function are not reflected back to the calling function.
  • 12. 12 Program #include<stdio.h> void swap (int, int); void main() { int a = 10, b = 20; printf (“Before swap values are %d %dn”, a, b); swap (a, b); printf (“After swap values are %d %dn”, a, b); } void swap (int x, int y) { x = x + y; y = x – y; x = x – y; printf (“In swap function values are %d %dn”, x, y); } Output: Before swap values are 10 20 In swap function values are 20 10 After swap values are 10 20 On the execution of the function call, i.e. swap (a, b);, the values of actual arguments a & b are copied into the formal parameters x & y. Formal parameters occupy separate memory locations. A change made in the formal parameters is independent of the actual arguments. On returning from called function, formal parameters are destroyed and access to actual arguments gives values that are unchanged. 2. Pass by Address or Call by Address or Call by Reference: In this method, the addresses of actual arguments are passed to the formal parameters of the function. The changes made in the values pointed to by the formal parameters in the called function are reflected back to the calling function. #include<stdio.h> void swap (int*, int*); void main() { int a = 10, b = 20; printf (“Before swap values are %d %dn”, a, b); swap (&a, &b); printf (“After swap values are %d %dn”, a, b); } void swap (int *x, int *y) { *x = *x + *y; *y = *x – *y; *x = *x – *y; printf(“In swap function values are %d %dn”, *x, *y); }
  • 13. 13 Output: Before swap values are 10 20 In swap function values are 20 10 After swap values are 20 10 Addresses of the actual arguments are passed instead of their values. Changes made in the called function are actually done in the memory locations of the actual arguments. On returning from the called function, the formal parameters are destroyed but the changes made in the values pointed by the formal parameters are reflected back to the calling function. 6. Discuss about passing arrays to function. (13). Arrays can be passed to functions in two different ways: 1. Passing individual elements of an array one by one: The individual elements of an array can be passed either by value of by reference. If the number of elements in an array is large, passing the entire array will take a large number of function calls. As the function calls are time consuming, this method of passing an array to a function will deteriorate the performance of a program. #include<stdio.h> int add (int, int); void main() { int a[10], n, i, s = 0; printf ("Enter the no. of elements: "); scanf ("%d", &n); printf ("Enter elements of array:n"); for (i = 0; i < n; i++) { scanf ("%d", &a[i]); s = add (a[i], s); } printf ("Sum is %d", s); } int add (int num, int sum) { return sum + num; } 2. Passing entire array at a time is a preferred way of passing arrays to functions. The entire array is always passed by reference. Passing One-dimensional Arrays to Functions: The actual argument in the function call should only be the name of an array without any subscript. The corresponding formal parameter in the function definition must be of array type or pointer type. If a formal parameter is of array type, it will be implicitly converted to pointer type. The corresponding parameter type in the function declaration should be of array type or pointer type.
  • 14. 14 #include<stdio.h> void max_min (int[], int); void main() { int a[10], n, i; printf ("Enter the no. of elements: "); scanf ("%d", &n); printf ("Enter elements of array:n"); for (i = 0; i < n; i++) scanf ("%d", &a[i]); max_min (a, n); printf ("Max is %dn", a[0]); printf ("Min is %d", a[1]); } void max_min (int a[], int n) { int i, max = a[0], min = a[0]; for (i = 1; i < n; i++) { if (a[i] > max) max = a[i]; else if (a[i] < min) min = a[i]; } a[0] = max; a[1] = min; } Enter the no. of elements: 5 Enter elements of array: 2 4 5 7 1 Max is 7 Min is 1 Passing the entire array at a time is an efficient way of passing a number of values to a function. 7. Explain in detail about recursive function with sample code. (13) Recursion is a powerful programming technique used to solve the problems that can be expressed in terms of similar problems of smaller size. A function that calls itself is called recursive function, and the phenomenon is called recursion. Every recursive function consists of two cases: 1. Base case: It forms the terminating condition of the recursion. There may be more than one base case in a recursive function. Without the base case, the recursion will never terminate and will be known as infinite recursion. For example, no == 1 is the base case of the recursive function fact.
  • 15. 15 2. Recursive case: In a recursive case, the problem is defined in terms of itself with a reduced problem size. For example, when fact (n) is expressed as n * fact (n – 1), the size of the problem is reduced from n to n – 1. Program: // Recursion to find the factorial of a number #include<stdio.h> int fact (int); void main () { int no, f; printf (“Enter the number: ”); scanf (“%d”, &no); f = fact (no); printf (“Factorial of %d is %d”, n, f); } // Definition of recursive function fact int fact (int n) { if (n == 1) return 1; else return n * fact (n – 1); } Output: Enter the number: 5 Factorial of 5 is 120 8. Analyze with example code in C for global and local variables. (13). Local variables  The scope of local variables will be within the function only.  These variables are declared within the function and can’t be accessed outside the function.  In the below example, m and n variables are having scope within the main function only. These are not visible to test function.  Like wise, a and b variables are having scope within the test function only. These are not visible to main function. #include<stdio.h> void test(); int main() { int m = 22, n = 44; // m, n are local variables of main function printf("nvalues : m = %d and n = %d", m, n);
  • 16. 16 test(); } void test() { int a = 50, b = 80; // a, b are local variables of test function printf("nvalues : a = %d and b = %d", a, b); } Output: values : m = 22 and n = 44 values : a = 50 and b = 80 Global Variables  The scope of global variables will be throughout the program. These variables can be accessed from anywhere in the program.  This variable is defined outside the main function. So that, this variable is visible to main function and all other sub functions. #include<stdio.h> void test(); int m = 22, n = 44; int a = 50, b = 80; int main() { printf("All variables are accessed from main function"); printf("nvalues: m=%d:n=%d:a=%d:b=%d", m,n,a,b); test(); } void test() { printf("nnAll variables are accessed from test function"); printf("nvalues: m=%d:n=%d:a=%d:b=%d", m,n,a,b); } Output: All variables are accessed from main function values : m = 22 : n = 44 : a = 50 : b = 80 All variables are accessed from test function values : m = 22 : n = 44 : a = 50 : b = 80 9. Write notes on fixed argument functions and variable argument functions. (13) Based upon the number of arguments a function accepts, functions are classified as follows: 1. Fixed Argument Functions: A function that accepts a fixed number of arguments is called a fixed argument function. If the fixed argument function does not specify any default argument, invoking a
  • 17. 17 fixed argument function with a lesser number of arguments than expected leads to a compilation error. A fixed argument function cannot even be invoked by supplying more number of arguments than expected. For example, pow function defined in math.h header file expects two arguments of type double. The following invocations of pow function are invalid. pow (); //Lesser number of arguments supplied than expected pow (2.0); //Lesser number of arguments supplied than expected pow (2.0, 1.5, 1.0); //More number of arguments supplied than expected 2. Variable Argument Functions: A function that accepts a variable number of arguments is called a variable argument function. For example, printf is a variable argument function, which can accept one or more arguments. The type of first argument must be char* and there is no constraint about the type of rest of the arguments. The following calls to printf function are valid: printf (“Hello”); // Only one argument of type char* printf (“%d”,2); // Two arguments. The type of the first argument is char* and the second is int printf (“%s %s”,“Hi”,“!!”); // Three arguments, all of type char* The number of arguments that can be passed to a variable argument function is not fixed. Hence, while declaring a variable argument function, it is not possible to list the types of all the arguments that might be passed to the function during the function call. The solution to this problem is provided by ellipses (…). The presence of ellipses tells the compiler that when the function is called, zero or more arguments may follow and that the type of the arguments is not known. Ellipses used in the declaration of the variable argument function suspend the type checking. Program: #include<stdarg.h> #include<stdio.h> int sum(int no_of_arguments,...); main() { int result; result=sum(3,12,13,14); printf("The result of addition of 3 numbers is %dn",result); result=sum(5,10,20,30,40,50); printf("The result of addition of 5 numbers is %dn",result); } int sum(int no_of_arguments,...) { int arg,i=0,total=0; va_list ptr;
  • 18. 18 va_start (ptr,no_of_arguments); arg=va_arg(ptr,int); while(i++<no_of_arguments) { total+=arg; arg=va_arg(ptr,int); } va_end(ptr); return total; } Output: The result of addition of 3 numbers is 39 The result of addition of 5 numbers is 150 The variable argument functions are developed with the help of macros va_start, va_arg, va_end, declared in the header file stdarg.h. This header file also declares a type va_list that holds the information needed by the macros va_arg and va_end. The macro va_start takes two parameters ptr and lastfix. The type of the first parameter ptr is va_list and lastfix is the last fixed parameter supplied to the variable argument function. The last fixed parameter supplied to the variable argument function sum is no_of_arguments and is of type int. The macro va_start sets ptr to point to the first of the variable arguments being passed to the function. The macro va_arg is used to return the arguments in the variable list. The first time va_arg is used, it returns the first argument in the list. Each successive time va_arg is used, it returns the next argument in the list. The macro va_arg returns the values of type given to it as its second argument. The order in which the macros should be called is: va_start must be called before the first call to va_arg or va_end. va_end should be called after va_arg has read all the arguments. 10. Write the C program to find the value of sin(x) using the series up to the given accuracy (without using user defined function) also print sin(x) using library function. (13) /* Value of Sine using Recursion (Taylor's theorem) */ #include<stdio.h> float srs(float x,int i); float term(float x,int i); int main() { float x,y; int i; printf("enter the value of xn");
  • 19. 19 scanf("%f",&x); i=1; y=srs(x,i); printf("the sum is equals to %f",y); return 0; } float srs(float x,int i) { float sum=0.0; float t; t= term(x,i); if(i%2==0&&t>(-.000001)) { return 0; } else if(i%2!=0&&t<(.000001)) { return 0; } else { sum=t+ srs(x,i+1); } return sum; } float term(float x,int i) { float tn; int h; tn=x; for(h=2;h<2*i;h++) { tn= (x*tn)/h; } if(i%2==0) { tn= tn*(-1.0); return tn; }
  • 20. 20 else { return tn; } } 11. Write a C program for Scientific calculator using built-in functions(13) #include<stdio.h> #include<conio.h> #include<math.h> int main(void) { int choice, i, a, b; float x, y, result; clrscr(); do { printf(“nSelect your operation (0 to exit):n”); printf(“1. Additionn2. Subtractionn3. Multiplicationn4. Divisionn”); printf(“5. Square rootn6. X ^ Yn”); printf(“15. log10(x)n”); printf(“17. Sin(X)n18. Cos(X)n19. Tan(X)n20. Cosec(X)n”); printf(“21. Cot(X)n22. Sec(X)n”); printf(“Choice: “); scanf(“%d”, &choice); if(choice == 0) exit(0); switch(choice) { case 1: printf(“Enter X: “); scanf(“%f”, &x); printf(“nEnter Y: “); scanf(“%f”, &y); result = x + y; printf(“nResult: %f”, result); break; case 2: printf(“Enter X: “); scanf(“%f”, &x); printf(“nEnter Y: “); scanf(“%f”, &y); result = x – y; printf(“nResult: %f”, result); break; case 3: printf(“Enter X: “);
  • 21. 21 scanf(“%f”, &x); printf(“nEnter Y: “); scanf(“%f”, &y); result = x * y; printf(“nResult: %f”, result); break; case 4: printf(“Enter X: “); scanf(“%f”, &x); printf(“nEnter Y: “); scanf(“%f”, &y); result = x / y; printf(“nResult: %f”, result); break; case 5: printf(“Enter X: “); scanf(“%f”, &x); result = sqrt(x); printf(“nResult: %f”, result); break; case 6: printf(“Enter X: “); scanf(“%f”, &x); printf(“nEnter Y: “); scanf(“%f”, &y); result = pow(x, y); printf(“nResult: %f”, result); break; case 15: printf(“Enter X: “); scanf(“%f”, &x); result = log10(x); printf(“nResult: %.2f”, result); break; case 17: printf(“Enter X: “); scanf(“%f”, &x); result = sin(x * 3.14159 / 180); printf(“nResult: %.2f”, result); break; case 18: printf(“Enter X: “);
  • 22. 22 scanf(“%f”, &x); result = cos(x * 3.14159 / 180); printf(“nResult: %.2f”, result); break; case 19: printf(“Enter X: “); scanf(“%f”, &x); result = tan(x * 3.14159 / 180); printf(“nResult: %.2f”, result); break; case 20: printf(“Enter X: “); scanf(“%f”, &x); result = 1 / (sin(x * 3.14159 / 180)); printf(“nResult: %.2f”, result); break; case 21: printf(“Enter X: “); scanf(“%f”, &x); result = 1 / tan(x * 3.14159 / 180); printf(“nResult: %.2f”, result); break; case 22: printf(“Enter X: “); scanf(“%f”, &x); result = 1 / cos(x * 3.14159 / 180); printf(“nResult: %.2f”, result); break; default: printf(“nInvalid Choice!”); } } while(choice); getch(); return 0; } 12. Write the C coding for swapping of two numbers using pass by reference.(13) Pass by Address or Call by Address or Call by Reference: In this method, the addresses of actual arguments are passed to the formal parameters of the function. The changes made in the values pointed to by the formal parameters in the called function are reflected back to the calling function.
  • 23. 23 #include<stdio.h> void swap (int*, int*); void main() { int a = 10, b = 20; printf (“Before swap values are %d %dn”, a, b); swap (&a, &b); printf (“After swap values are %d %dn”, a, b); } void swap (int *x, int *y) { *x = *x + *y; *y = *x – *y; *x = *x – *y; printf(“In swap function values are %d %dn”, *x, *y); } Output: Before swap values are 10 20 In swap function values are 20 10 After swap values are 20 10 Addresses of the actual arguments are passed instead of their values. Changes made in the called function are actually done in the memory locations of the actual arguments. On returning from the called function, the formal parameters are destroyed but the changes made in the values pointed by the formal parameters are reflected back to the calling function. 13. Write a C program to sort the given N names using function. (13) #include<stdio.h> #include<string.h> int main() { int i,j,count; char str[25][25],temp[25]; puts("How many strings u are going to enter?: "); scanf("%d",&count); puts("Enter Strings one by one: "); for(i=0;i<count;i++) gets(str[i]); for(i=0;i<count-1;i++) { for(j=i+1;j<count;j++) {
  • 24. 24 if(strcmp(str[i],str[j])>0) { strcpy(temp,str[i]); strcpy(str[i],str[j]); strcpy(str[j],temp); } } } printf("Order of Sorted Strings:"); for(i=0;i<=count;i++) puts(str[i]); return 0; } 14. Explain about any 4 library functions in c. (13). Function Description floor ( ) This function returns the nearest integer which is less than or equal to the argument passed to this function. round ( ) This function returns the nearest integer value of the float/double/long double argument passed to this function. If decimal value is from “.1 to .5”, it returns integer value less than the argument. If decimal value is from “.6 to .9”, it returns the integer value greater than the argument. ceil ( ) This function returns nearest integer value which is greater than or equal to the argument passed to this function. sin ( ) This function is used to calculate sine value. cos ( ) This function is used to calculate cosine. cosh ( ) This function is used to calculate hyperbolic cosine. exp ( ) This function is used to calculate the exponential “e” to the xth power. tan ( ) This function is used to calculate tangent. tanh ( ) This function is used to calculate hyperbolic tangent. sinh ( ) This function is used to calculate hyperbolic sine. log ( ) This function is used to calculates natural logarithm. log10 ( ) This function is used to calculates base 10 logarithm. sqrt ( ) This function is used to find square root of the argument passed to this function. pow ( ) This is used to find the power of the given number. trunc.(.) This function truncates the decimal value from floating point value and returns integer value.
  • 25. 25 PART-C 1. Develop a C program for binary search using recursive function.(15) Recursion is programming technique where a function calls itself to solve a smaller problem that is of the same type as the original problem. The recursive call (calling itself) continues until the function can produce a result trivially without making any more calls. In the program below, the function binarysearch takes four parameters - the array to be searched, the lowest position of the search range, highest position of the search range, and the element to be searched. The first time you call the binary search function with the entire range of the array. So you set the lowest position to 0 and highest position to the length of the array minus one. With each recursive call the search range becomes smaller and smaller until you find the search element. #include<stdio.h> int binarysearch(int a[], int low, int high, int x) { int mid = (low + high) / 2; if (low > high) return -1; if (a[mid] == x) return mid; if (a[mid] < x) return binarysearch(a, mid + 1, high, x); else return binarysearch(a, low, mid-1, x); } int main(void) { int a[100]; int len, pos, search_item; printf("Enter the length of the arrayn"); scanf("%d", &len); printf("Enter the array elementsn"); for (int i=0; i<len; i++) scanf("%d", &a[i]); printf("Enter the element to searchn"); scanf("%d", &search_item); pos = binarysearch(a,0,len-1,search_item); if (pos < 0 ) printf("Cannot find the element %d in the array.n", search_item); else printf("The position of %d in the array is %d.n", search_item, pos+1); return 0; }
  • 26. 26 2. Examine with example program to display all prime numbers between two intervals using functions. #include <stdio.h> int isPrime(int num); void printPrimes(int n, int m); int main() { int n,m; printf("Enter the lower and upper limit to list primes: "); scanf("%d%d", &n, &m); printPrimes(n,m); return 0; } void printPrimes(int n, int m) { printf("All prime number between %d to %d are: ", n,m); while(n<= m) { // Print if current number is prime. if(isPrime(n)) { printf("%d, ", n); } n++; } } intisPrime(int num) { int i; for(i=2; i<=num/2; i++) { if(num % i == 0) { return 0; } } return 1; } Output Enter the lower and upper limit to list primes 20 50 Prime numbers between 20 and 50 are: 23 29 31 37 41 43 47
  • 27. 27 3. Develop a C program for towers of Hanoi using recursive function.(15) This C Program uses recursive function & solves the tower of hanoi. The tower of hanoi is a mathematical puzzle. It consists of three rods, and a number of disks of different sizes which can slide onto any rod. The puzzle starts with the disks in a neat stack in ascending order of size on one rod, the smallest at the top. We have to obtain the same stack on the third rod. Here is the source code of the C program for solving towers of hanoi. #include <stdio.h> void towers(int, char, char, char); int main() { int num; printf("Enter the number of disks : "); scanf("%d", &num); printf("The sequence of moves involved in the Tower of Hanoi are :n"); towers(num, 'A', 'C', 'B'); return 0; } void towers(int num, char frompeg, char topeg, char auxpeg) { if (num == 1) { printf("n Move disk 1 from peg %c to peg %c", frompeg, topeg); return; } towers(num - 1, frompeg, auxpeg, topeg); printf("n Move disk %d from peg %c to peg %c", num, frompeg, topeg); towers(num - 1, auxpeg, topeg, frompeg); } Output: Enter the number of disks : 3 The sequence of moves involved in the Tower of Hanoi are : Move disk 1 from peg A to peg C Move disk 2 from peg A to peg B Move disk 1 from peg C to peg B Move disk 3 from peg A to peg C Move disk 1 from peg B to peg A Move disk 2 from peg B to peg C Move disk 1 from peg A to peg C
  • 28. 28 4. Illustrate a C program for cube of a number using pass by reference.(15) Program #include<stdio.h> int cube (int*); void main() { int a, b; printf (“n Enter the number”); scanf (“%d”, &a); b = cube (&a); printf (“The cube of the number is %dn”, b); } Int cube (int *x) { return (*x * *x * *x); } Output: Enter the number…5 The cube of the number is ..125 **********