Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
17 views

C Fundamentals

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

C Fundamentals

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

UNIT IV - FUNCTIONS AND POINTERS

1. Define Functions.
A function is a set(block) of instructions that are used to perform specified task
which repeatedly occurs in main program. It is a self-contained block of program
statements that performs a particular task.
2. How function works?

Main Program Definition - Function1

Declaration – Function1 .
.
Call Function1 .
. .
.
.
Call Function1
.
.
.
Call Function1
.
.

3. Give some needs of Functions.


1. It makes programs easier to understand and maintain by breaking large program
into easily manageable blocks.
2. The main program consists of a series of function calls rather than countless lines
of code.
3. It is possible to execute as many times as necessary from different points in the
main program.
4. Well-written functions may be reused in multiple programs.
5. Different programmers working on one large project can divide the workload by
writing different functions.
6. It makes debugging and testing easier.
4. List some Advantages of functions
1. The length of source program can be reduced by reducing redundancy.
2. It enables reusing codes.
3. Better readability.
4. Provides way to hide information if necessary.
5. Improved debugging and testing.
6. Easy to understand and maintain.
5. Classification of Functions
Based upon who develops the function, functions are classified as:
1. Library Functions
2. User-defined Functions
6. What are Library Functions?
Library functions are the functions whose functionality has already been
developed by someone and are available to the user for use. There are two aspects of
working with library functions:
1. Declaration of Library functions.
2. Use(call) of Library functions.
7. List some Mathematical Library functions and their uses.
S. No Function Function Declaration Purpose

1. sqrt double sqrt(double x); To find the square root of a


given number.

2. log double log(double x); To return natural logarithm of


x

3. exp double exp(double x); To return a values of e raised


to the xth power.

4. pow double pow(double x, To return x raised to the


double y); power of y.

8. Write a program to find power and sqrt of a given number.


#include<stdio.h>
#include<math.h>
#include<conio.h>
void main()
{
double x;
printf("\nEnter value for x:");
scanf("\n%lf",&x);
printf("\n%lf Power 5 = %lf",x,pow(x,5));
printf("\nSquare Root of %lf = %lf",x,sqrt(x));
getch();
}
Output:
Enter value for x:4
4.000000 Power 5 = 1024.000000
Square Root of 4.000000 = 2.000000

9. Write a program to round up a value

//To roundup a value


#include<stdio.h>
#include<math.h>
#include<conio.h>
void main()
{
double x;
printf("\nEnter value for x:");
scanf("%lf",&x);
printf("\nSmallest integer greater than or equal to %lf = %2.1lf",x,ceil(x));
printf("\nLargest integer less than or equal to %lf = %2.1lf",x,floor(x));
getch();
}

Output:
Enter value for x:2.3
Smallest integer greater than or equal to 2.300000 = 3.0
Largest integer less than or equal to 2.300000 = 2.0

10. Categorize Library Functions based on number of arguments.


Based on number of arguments a functions accepts, library functions are
classifieds into two,
1. Fixed argument functions
2. Variable argument functions

11.What is Fixed argument functions?


A function that accepts fixed number of arguments is called a fixed argument
function. Variation in the number of argument at function call makes compilation error.
For example, the declaration of function pow is,
double pow(double x, double y);
Invoking the pow function with following values leads to error.
pow(2);
The following statement produces correct output.
pow(2,3);

12. What is Variable argument functions?


A function that accepts variable number of arguments is called variable argument
function.
For example, printf function accepts one or more arguments. The type of first
argument must be char*, and the rest will be of any type. The following printf statements
are valid:
 printf(“Welcome”);
 printf(“%d”,x);
13. What is the role of ellipses?
Ellipses(…) are used to declare variable argument functions. 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.
For example, the variable argument function printf’s declaration is,
int printf(const char*…);

It says that, the function printf must have a string argument at first, and the rest
will be of any type.
14. What are User-defined functions?
The functions defined by the users according to their requirements are called user-
defined functions or programmer-defined functions.
The statements to perform a particular task, which is repeatedly used in the main
function, can be created as user-defined functions. These functions are useful to break
down a large program in to a number of smaller functions.
15. Give syntax for function declaration.
The general form of a function declaration statement is as follows:

<return_type> <function_name>(<parameter_list or type_of_parameters);

16. Give syntax function definition.


The general form of a function is:

<return_type> <function_name>(<formal_argument_list>)
{
// Body of function
}

17. Give syntax for function invocation/call.


The general form of the function call statement is as follows:

<function_name><actual_arguments>

18. Write a program to find sum of two numbers using user defined functions.
//To find sum of two integers
#include<stdio.h>
#include<conio.h>
void main()
{
int x,y,sum;
int add(int,int);
clrscr();
printf("\nEnter two integers:");
scanf("%d%d",&x,&y);
sum=add(x,y);
printf("\nSum = %d",sum);
getch();
}
int add(int x,int y)
{
return(x+y);
}
Output
Enter two integers:2 3
Sum = 5
19. How will you classify the user-defined functions?
Depending upon their inputs and outputs, userdefined-functions are classified as,
1. Functions with no input-output
2. Function with inputs and no output
3. Function with inputs and one output
4. Function with inputs and outputs
20. Write a program to swap two numbers without using third variable.
#include<stdio.h>
int main()
{
int x,y;
void swap(int,int);
printf("Enter two numbers:");
scanf("%d%d",&x,&y);
printf("\n\nBefore Swapping:\n\nx = %d\n\ny = %d",x,y);
swap(x,y);
return 0;
}
void swap(int a, int b)
{
a=a+b;
b=a-b;
a=a-b;
printf("\n\nAfter Swapping:\n\nx = %d\n\ny = %d\n\n",a,b);
}

Output
Enter two numbers: 4 7
Before Swapping:
x=4
y=7
After Swapping:
x=7
y=4
21. Define call by reference.
The method of passing arguments by address or reference is also known as call by
address or call by reference. Here, the addresses of the actual arguments are passed to the
formal parameters of the function.
If the arguments are passed by reference, changes in the formal parameters also
make changes on actual parameters.
22. Write a program to swap two numbers by Passing Arguments as
Address/Reference
#include<stdio.h>
int main()
{
int x,y;
void swap(int*,int*);
printf("Enter two numbers:");
scanf("%d%d",&x,&y);
printf("\n\nBefore Swapping:\n\nx = %d\n\ny = %d",x,y);
swap(&x,&y);
printf("\n\nAfter Swapping:\n\nx = %d\n\ny = %d\n\n",x,y);
return 0;
}
void swap(int *a, int *b)
{
*a=*a+*b;
*b=*a-*b;
*a=*a-*b;
}
Enter two numbers: 2 7

Before Swapping:
x=2
y=7

After Swapping:
x=7
y=2

23. Write a program to find minimum value in the array using Array as argument
for function.
#include<stdio.h>
#include<conio.h>
void main()
{
int a[10],i,min;
int findmin(int[]); //OR int findmin(int*);
clrscr();
printf("Enter 10 integers:");
for(i=0;i<10;i++)
scanf("%d",&a[i]);
min=findmin(a); //Argument as Array Name “a”
printf("Minimum value in the array is: %d",min);
getch();
}
int findmin(int x[]) // Parameter with Array specification
{
int temp,i;
temp=x[0];
for(i=1;i<10;i++)
{
if(temp>x[i])
temp=x[i];
}
return temp;
}

Output
Enter 10 integers:
34
65
78
12
09
23
56
78
89
54
Minimum value in the array is: 9
24. Write a program to find minimum value in a two dimensional array.
#include<stdio.h>
#include<conio.h>
void main()
{
int a[2][2],i,j,min;
int findmin(int[][2]);
clrscr();
printf("Enter 10 integers:");
for(i=0;i<2;i++)
{
for(j=0;j<2;j++)
scanf("%d",&a[i][j]);
}
min=findmin(a);
printf("Minimum value in the 2-D array is: %d",min);
getch();
}
int findmin(int x[][2])
{
int temp,i,j;
temp=x[0][0];
for(i=1;i<2;i++)
{
for(j=0;j<2;j++)
if(temp>x[i][j])
temp=x[i][j];
}
return temp;
}

Output
Enter 10 integers:
45 78
12 54
Minimum value in the 2-D array is: 12
25. What is the purpose of Default Argument?
It is possible to pass argument values (as constant) at function call. In such case,
we need to use formal variable to receive that constant value.
 During function declaration, the argument can be made default by using
initialization syntax within the parameter list.
 A function declaration can specify default arguments for all or subset of
parameters.
 Default argument function can be called with or without parameters.
 If argument is not provided, it considers default value. Otherwise, considers
passed value.
 Default argument (Default value) should not be specified in the function
definition.
26. Write a program to find area of circle using default arguments.
#include<stdio.h>
#include<conio.h>
void main()
{
int r;
float area(int r,float pi=3.14); // pi value 3.14 is default
argument
clrscr();
printf("Enter radius:");
scanf("%d",&r);
printf("Area of Circle : %2.2f",area(r));
getch();
}
float area(int r,float pi)
{
return(pi*r*r);
}

Output
Enter radius: 2
Area of Circle : 12.56
27. What is Recursion?
 When function is defined in terms of itself then it is called as “Recursion
Function”.
 Recursive function is a function which contains a call to itself.
 A function calls itself is known as recursive function.

28. What is needed for implementing recursion?


 Decomposition into smaller problems of same type
 Recursive calls must reduce problem size
 Necessity of base case
 Base case must be reached.
29. What is a base case?
 An instance of a problem the solution of which requires no further
recursive calls is known as a base case.
 It acts as a terminating condition.
 It is the building block to the complete solution.
30. Write a program to find factorial of a given number using recursive funcitions.
#include<stdio.h>
int main()
{
int n;
int factorial(int);
printf("Enter the number:");
scanf("%d",&n);
printf("Factorial of %d is %d",n,factorial(n));
return 0;
}
int factorial(int n)
{
if(n==0)
return 1;
else
return(n*factorial(n-1));
}

Output
Enter the number: 5
Factorial of 5 is 120
31. Give Pattern of Recursive Calls.
Recursive calls are classified as,
1. Linear Recursion
2. Binary Recursion
3. N-ary Recursion

32. Give example for Linear Recursion.


Factorial(5) = 5 * factorial (4)

4 * factorial (3)

3 * factorial (2)

2 * factorial (1)

1 * factorial (0)
33. Give example for Binary Recursion
Binary recursion calls itself twice. Binary recursion is used in solving some of the
important computing problems like:
1. Tower of Honai problem
2. Sorting by merge sort
3. Searching by binary search
4. Fibonacci series generation, etc.

34. Write a program to solve tower of hanai proble.


#include<stdio.h>
#include<conio.h>
void main()
{
void move(int,int,int,int);
int disks=3;
clrscr();
printf("Follow these moves:\n");
move(disks,1,3,2);
}
void move(int count,int start,int finish, int temp)
{
if(count>0)
{
move(count-1,start,temp,finish);
printf("%d from %d to %d ",count,start,finish);
move(count-1,temp,finish,start);
}
}
Follow these moves:
1 from 1 to 3
2 from 1 to 2
1 from 3 to 2
3 from 1 to 3
1 from 2 to 1
2 from 2 to 3
1 from 1 to 3
35. Write a program to display Fibonacci Series using recursive functions.
#include<stdio.h>
int main()
{
int n,i;
int fib(int);
printf("Enter the number of terms:");
scanf("%d",&n);
printf("Fibonacci sequence for %d terms is : \n",n);
for(i=1;i<=n;++i)
printf(" %d\n",fib(i));
return 0;
}
int fib(int n)
{
if(n<=2)
return 1;
else
return(fib(n-1)+fib(n-2)); //Binary Recursion
}

Output
Enter the number of terms: 6
Fibonacci sequence for 10 terms is :
1
1
2
3
5
8
36. Is it possible to create Pointers to Functions
Yes. Function Pointers are pointers, i.e. variables, which point to an address of a
function. The running programs get a certain space in the main memory. Both, the
executable compiled program code and the used variables, are put inside this memory.
A function can take many types of arguments including the address of another
function. Function pointer can be a clever way to bind a function to a specific algorithm
at runtime.
37. What is Pointer?
A pointer is a variable that holds the address of a variable or a function. Every
pointer variable occupies same amount of memory space to store the variables belongs
int, float, char or any other type.

P X

Here, P is a pointer, which points the variable X.


Syntax

Storage_Access_specifier type_qualifier type_modifier type_specifier* identifier = value

Example
int *ptr; // Pointer to a integer variable
float *ptr; // Pointer to a float variable
char *ptr; // Pointer to a character variable
38. What is Void Pointer?
A void pointer is a special type of pointer, it can point any type ie, an integer, a
float or string of characters. Its limitation is that pointed data cannot be referenced
directly using *. Type casting should be done to display that pointed value.

39. Give example for void pointer.


#include<stdio.h>
void main()
{
int a;
float b;
void *p;
clrscr();

a=10;
b=10.2;

p=&a;
printf("\nInteger a = %d",*(int *)p);

p=&b;
printf("\nFloat b = %f",*(float *)p);
getch();
}

Output
Integer a = 10
Float b = 10.200000
40. What is Null Pointer?
A null pointer is a special pointer value that points nowhere. To make pointer as
null pointer, initialize it with zero. That represents the null pointer is not intended to point
to an accessible memory location.
Example
#include<stdio.h>
void main()
{
int a;
float b;
void *p=0;
clrscr();

a=10;
b=10.2;

p=&a;
printf("\nInteger a = %d",*(int *)p);

p=&b;
printf("\nFloat b = %f",*(float *)p);
getch();
}

41. Is it possible to create Pointer to Pointer?


It is possible to make a pointer to point to another pointer. It can be declared using
double indirection operator (ie., **);

Pointer p2 Pointer p1 Variable x

Address of p1 Address of x X

42. Give the use of Pointers.


One of the usage of pointers is calling the function with Address or Reference of
the variable.
Calling functions using value method make process on local variables of
functions. It won’t affect the actual argument values. To make changes on actual
arguments Call by Address method is used.
43. List some Advantages of writing functions in C programming.
1. Modular and Structural programming can be done
 We can divide c program in smaller modules.
 We can call module whenever require
2. It follows Top-Down execution approach, so main can be kept very small.
 Every C program starts from main function.
 Every function is called directly or indirectly through main
3. Individual functions can be easily built, tested.
 As we have developed C application in modules we can test each
and every module.
4. Program development become easy
5. Frequently used functions can be put together in the customized library.
 We can put frequently used functions in our custom header file.
6. A function can call other functions & also itself
 Function can call other function.
7. It is easier to understand and maintain.
44. What is dangling pointer?
In C, a pointer may be used to hold the address of dynamically allocated memory.
After this memory is freed with the free() function, the pointer itself will still contain the
address of the released block. This is referred to as a dangling pointer. Using the pointer
in this state is a serious programming error. Pointer should be assigned NULL after
freeing memory to avoid this bug
45.What is the output of the following program?
Main()
{
Int a=8,b=4,c,*p1=&a,*p2=&b;
C=*p1**p2-*p1/*p2+9;
Printf(“%d”,c);
}

Part B

1. What is function? Explain Library functions with eg.


Functions
A function is a set(block) of instructions that are used to perform specified task
which repeatedly occurs in main program. It is a self-contained block of program
statements thatMain
performs a particular task.
Program

Declaration – Function1
Working Principle
Call Function1
.
. Definition - Function1
.
Call Function1 .
. .
. .
. .
Call Function1
.
.
 The function “Function1” defined as a section of a program performing a specific
job.
 Function1 is declared and called inside main program.
 While Function1 call, program control moves to Definition of Function1 and
again returns to main function after execution of Function1.
Need of Functions
1. It makes programs easier to understand and maintain by breaking large
program into easily manageable blocks.
2. The main program consists of a series of function calls rather than countless
lines of code.
3. It is possible to execute as many times as necessary from different points in
the main program.
4. Well-written functions may be reused in multiple programs.
5. Different programmers working on one large project can divide the workload
by writing different functions.
6. It makes debugging and testing easier.
Advantage of functions
1. The length of source program can be reduced by reducing redundancy.
2. It enables reusing codes.
3. Better readability.
4. Provides way to hide information if necessary.
5. Improved debugging and testing.
6. Easy to understand and maintain.
Classification of Functions
Based upon who develops the function, functions are classified as:
1. Library Functions
2. User-defined Functions
Library Functions:
Library functions are the functions whose functionality has already been
developed by someone and are available to the user for use. There are two aspects of
working with library functions:
1) Declaration of Library functions.
2) Use(call) of Library functions.
Use of Library Functions
The role and usage of some of the common library functions are listed below.
Library of Mathematical Functions
It defines some common mathematical functions. The declarations of thes
functions are available in the header file math.h.
Exponential, logarithmic and power functions.
S. No Function Function Declaration Purpose

1. Sqrt double sqrt(double x); To find the square root of a


given number.

2. log double log(double x); To return natural logarithm of


x

3. exp double exp(double x); To return a values of e raised


to the xth power.

4. pow double pow(double x, To return x raised to the


double y); power of y.

Example
//To display power and square root of a given number
#include<stdio.h>
#include<math.h>
#include<conio.h>
void main()
{
double x;
printf("\nEnter value for x:");
scanf("\n%lf",&x);
printf("\n%lf Power 5 = %lf",x,pow(x,5));
printf("\nSquare Root of %lf = %lf",x,sqrt(x));
getch();
}
Output:
Enter value for x:4
4.000000 Power 5 = 1024.000000
Square Root of 4.000000 = 2.000000

Library Functions based on number of arguments


Based on number of arguments a functions accepts, library functions are
classifieds into two,
1) Fixed argument functions
2) Variable argument functions
Fixed argument functions
A function that accepts fixed number of arguments is called a fixed argument
function. Variation in the number of argument at function call makes compilation error.
For example, the declaration of function pow is,
double pow(double x, double y);
Invoking the pow function with following values leads to error.
pow(2);
The following statement produces correct output.
pow(2,3);
Variable argument functions
A function that accepts variable number of arguments is called variable argument
function.
For example, printf function accepts one or more arguments. The type of first
argument must be char*, and the rest will be of any type. The following printf statements
are valid:
 printf(“Welcome”);
 printf(“%d”,x);
Example
#include<stdio.h>
void main()
{
int r;
float pi,area;
pi=3.14;
printf(“Enter radius:”); //printf with one argument
scanf(“%d”,&r);
area=pi*r*r;
printf(“Area of Circle:%d”,area); //printf with two arguments
}
Role of ellipses
Ellipses(…) are used to declare variable argument functions. 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.
For example, the variable argument function printf’s declaration is,
int printf(const char*…);

It says that, the function printf must have a string argument at first, and the rest
will be of any type.
2. What are userdefined functions? Explain with example.
User-defined functions
The functions defined by the users according to their requirements are called user-
defined functions or programmer-defined functions.
The statements to perform a particular task, which is repeatedly used in the main
function, can be created as user-defined functions. These functions are useful to break
down a large program in to a number of smaller functions.
There are three major components associated with the user-defined function.

1. Function declaration or Function prototype – That identifies a function with a


name, list of arguments and the type of data returned.
2. Function definition – That consist of function header identifying the function
followed by the body of the function(executable code).
3. Function call / invocation / use – That invokes the function by either passing or
not passing some parameters.
Function Declaration
 All the function need to be declared or defined before they are used.
 Function declaration statement ends with semicolon.
 No function can be declared inside the body of another function.

The general form of a function declaration statement is as follows:

<return_type> <function_name>(<parameter_list or type_of_parameters);

Examples for valid function declaration statements


1. add(); - Return type and parameter list are not specified.
2. int add(); - Return type is int and parameter list is not specified.
3. add(int,int); - Return type not specified and parameter type is int.
4. int add(int a, int b); - Return type is int and parameter_list type is int.
Parameter names are a and b.
5. int add(int, int a); - Return type is int and parameters are of combination
of abstract and complete parameter declarations type.
Examples for invalid function declaration statements
1. int add(int x, float x); - Both the parameter names are same.
2. int add&div(); - Function name contains special character.
3. int add(a,b); - Specifying the type of parameters is missing.
4. int add(int a,b); - Type of second parameter is missing.
5. int add(int a,int b) - Declaration is not terminated with semicolon.
Function Defintion
The collection of C statements that describes the specific task done by the function
is called a function definition or function implementation.
It is the process of specifying and establishing the user defined function by
specifying all of its elements and characteristics.
Function definition consists two parts:
1. Header of the function
2. Body of the function
Header of a Funciton
Function header is similar to the function declaration but does not require the
semicolon at the end. The list of variables in the function header is referred as formal
parameter list. Header of a function is not terminated with a semicolon.
The general form of a function is:
Example for valid function headers
1. int add(int a, int b) - Return type and parameter types are integer.
2. void add(int a) - Return type is void and parameter type is int.
3. void add(int a, float b) - Parameter types are int and float.

Example for invalid function headers


1. int add(int a,int b); - Ends with semicolon.
2. int add(int) - Parameter name is not specified.
3. int add(int a int b) - Parameters not separated with comma.
Body of a Funciton
 The body of a function consists of a set of statements enclosed within braces.
 It can have both executable and non-executable statements.
 Non-executable statements are local variable declaration.
 Executable statements are the actual process of body of a function.
 A function body can optionally have return statement.
 Return statement returns result of computation to the calling function.
Example 1:
int add(int a, int b) //Function Header
{
return (a+b); //Executable statement in function body
}

Example 2:
void add(int a, int b) // Function Header
{
int c;
c=a+b; // Executable statements
cout<<”Sum:”<<c;
}

Function Invocation/Call/Use
All function, within the standard library or user-written, are called from within this
main() function. While functions call, the program control passes to that of the function
definition. Once the function completes its task, the program control is passed back to the
calling environment(ie., main() function).
The general form of the function call statement is as follows:

<function_name><actual_arguments>

 function_name - Name of the function declared or defined.


 actual_arguments - The actual input values to be passed to the function.
 The actual argument name at function call and formal argument name at
function definition may differ.
 In function call, no need to specify the data type of arguments.
 Argument or parameter variables are separated by comma at function call.

Example for valid function call statements


1. Sum=add(x,y); - Sum is int type variable. Add is function name. x,y are
actual parameters.
2. Add(x,y); - Its return type is void. x, y are actual arguments.
Example for invalid function call statements
1. Sum=add(x y); - Comma separator is not used.
2. Add(x,y) - Semicolon missing.
Example
//To find sum of two integers
#include<stdio.h>
#include<conio.h>
void main()
{
int x,y,sum;
int add(int,int);
clrscr();
printf("\nEnter two integers:");
scanf("%d%d",&x,&y);
sum=add(x,y);
printf("\nSum = %d",sum);
getch();
}
int add(int x,int y)
{
return(x+y);
}

Output
Enter two integers:2 3
Sum = 5

3. List all the different function prototypes and explain in detail.

Depending upon their inputs and outputs, userdefined-functions are classified as,
1) Functions with no input-output
2) Function with inputs and no output
3) Function with inputs and one output
4) Function with inputs and outputs
Functions with no input-output
It does not accept any input and does not return any result. It means that functions
with no arguments and valueless return type.
 Value less return type is void.

Main()
{
Fn_name();
.
.
} Control transferred to function
Control returned back
to main
Fn_name()
{
.
.
.
}
Example
//To display sum of two numbers
#include<stdio.h>
#include<conio.h>
void main()
{
clrscr();
void add(); //Function Declaration
add(); //Function Call
getch();
}
void add()
{
int x,y;
printf("Enter two integers:"); //Function Definition
scanf("%d%d",&x,&y);
printf("\nSum = %d",x+y);
}
Output
Enter two integers:5 7
Sum = 12
Functions with input and no output
It accepts input and does not return any result. It means that inputs passed as
arguments and return type is valueless.

Main()
{
void Fn_name(arg_list);
.
.
} Control transferred to
Control returned back function
to main
Fn_name(parameter_list)
{
.
.
.
}
Example
//To display sum of two numbers
#include<stdio.h>
#include<conio.h>
void main()
{
int x,y;
void add(int,int); //Function Declaration
clrscr();
printf("Enter two integers:");
scanf("%d%d",&x,&y);
add(x,y); //Function Call
getch();
}
void add(int x,int y)
{
printf("\nSum = %d",x+y); //Function Definition
}

Output
Enter two integers: 3 4
Sum = 7
Functions with input and one output
It accepts input and returns output. It means that inputs passed as arguments and
return type is based on output to be returned. There are two forms of return statements:
o When a function does not return any value return or return 0; statement is used.
o To return any output from called function to calling function, return statement
with variable name or expression is used.
 It cannot be placed inside the body of void function.
 If results of evaluation and return type are not same, return
statement implicitly converts result type to the return type.
 A function can return only one value. But, it is possible to specify
more than one return statement in the same function.
 The return statement can return only one value from the called
function to the calling function.
 Return statement can be present anywhere in the user-defined
function.
 Parenthesis used around the expression in a return statement is
optional.
Main()
{
ret_type Fn_name(arg_list);
.
.
} Control transferred to
Control returned back function
to main
ret_type Fn_name(para_list)
{
.
.
return;
}
Example
//To display sum of two numbers
#include<stdio.h>
#include<conio.h>
void main()
{
int x,y,sum;
int add(int,int); //Function Declaration
clrscr();
printf("Enter two integers:");
scanf("%d%d",&x,&y);
sum=add(x,y); //Function Call
printf("\nSum = %d",sum);
getch();
}
int add(int x,int y)
{
return(x+y); //Function Definition
}

Output
Enter two integers: 3 4
Sum = 7
4. Illustrate the difference between parameters and arguments with example.
Formal vs Actual parameters

What is parameter?
 A parameter is a special kind of variable, used in a function to refer pieces
of data provided as input to the function. These pieces of data are called
arguments.
 In C programming Function passing parameter is optional.
 We can call function without passing parameter.
Parameter vs arguments
 The names given in the function definition are called parameters.
 The values supplied in the function call are called arguments.

Formal vs Actual parameters


 Parameter written in function definition is called “Formal Parameter”.
 Parameter written in function call is called “Actual Parameter”.
Example
#include<stdio.h>
int add(int,int);
void main()
{
int a,b,c;
clrscr();
a=10;b=5;
c=add(a,b); // Actual Arguments
printf("\nThe sum=%d",c);
getch();
}
void add(int a,int b) // Parameters
{
int c;
c=a+b;
return(c);
}

5. Write a program to swap two numbers using user defined function.


#include<stdio.h>
int main()
{
int x,y;
void swap(int,int);
printf("Enter two numbers:");
scanf("%d%d",&x,&y);
printf("\n\nBefore Swapping:\n\nx = %d\n\ny = %d",x,y);
swap(x,y);
return 0;
}
void swap(int a, int b)
{
a=a+b;
b=a-b;
a=a-b;
printf("\n\nAfter Swapping:\n\nx = %d\n\ny = %d\n\n",a,b);
}
Output

Enter two numbers: 4 7

Before Swapping:
x=4
y=7

After Swapping:
x=7
y=4

6. Is it possible to pass arrays to functions? Explain with example.


Passing Arrays to Functions
Arrays can also be passed to functions. There are two ways to pass arrays to
functions.
1. Passing one-dimensional arrays to Functions
2. Passing two-dimensional arrays to Functions
Passing One-Dimensional Array to Functions
Rules
1. The parameter in the function declaration must be of array type or pointer type.
2. The actual argument in the function call should only be the name of the array.
3. The formal parameter in the function definition must be of array type or pointer
type.
Example
#include<stdio.h>
#include<conio.h>
void main()
{
int a[10],i,min;
int findmin(int[]); //OR int findmin(int*);
clrscr();
printf("Enter 10 integers:");
for(i=0;i<10;i++)
scanf("%d",&a[i]);
min=findmin(a); //Argument as Array Name “a”
printf("Minimum value in the array is: %d",min);
getch();
}
int findmin(int x[]) // Parameter with Array specification
{
int temp,i;
temp=x[0];
for(i=1;i<10;i++)
{
if(temp>x[i])
temp=x[i];
}
return temp;
}

Output
Enter 10 integers:
34
65
78
12
09
23
56
78
89
54
Minimum value in the array is: 9
Passing Two-Dimensional Arrays to Functions
Rules
1. It is mandatory to specify the column specifier of formal parameter and actual
argument.
2. The corresponding parameter type in the function declaration should be a
matching array type or pointer type.
Example
#include<stdio.h>
#include<conio.h>
void main()
{
int a[2][2],i,j,min;
int findmin(int[][2]);
clrscr();
printf("Enter 10 integers:");
for(i=0;i<2;i++)
{
for(j=0;j<2;j++)
scanf("%d",&a[i][j]);
}
min=findmin(a);
printf("Minimum value in the 2-D array is: %d",min);
getch();
}
int findmin(int x[][2])
{
int temp,i,j;
temp=x[0][0];
for(i=1;i<2;i++)
{
for(j=0;j<2;j++)
if(temp>x[i][j])
temp=x[i][j];
}
return temp;
}

Output
Enter 10 integers:
45 78
12 54
Minimum value in the 2-D array is: 12

7. What is default argument? Give example.


Default Arguments
It is possible to pass argument values (as constant) at function call. In such case,
we need to use formal variable to receive that constant value.
 During function declaration, the argument can be made default by using
initialization syntax within the parameter list.
 A function declaration can specify default arguments for all or subset of
parameters.
 Default argument function can be called with or without parameters.
 If argument is not provided, it considers default value. Otherwise, considers
passed value.
 Default argument (Default value) should not be specified in the function
definition.
Example

#include<stdio.h>
#include<conio.h>
void main()
{
int r;
float area(int r,float pi=3.14); // pi value 3.14 is default
argument
clrscr();
printf("Enter radius:");
scanf("%d",&r);
printf("Area of Circle : %2.2f",area(r));
getch();
}
float area(int r,float pi)
{
return(pi*r*r);
}
Output
Enter radius: 2
Area of Circle : 12.56

8. What is Recursion? In which situations it is useful? Explain with example.


Recursion
 When function is defined in terms of itself then it is called as “Recursion
Function”.
 Recursive function is a function which contains a call to itself.
 A function calls itself is known as recursive function.

What is needed for implementing recursion?


 Decomposition into smaller problems of same type
 Recursive calls must reduce problem size
 Necessity of base case
 Base case must be reached.

What is a base case?


 An instance of a problem the solution of which requires no further
recursive calls is known as a base case.
 It acts as a terminating condition.
 It is the building block to the complete solution.

Example

Factorial (n) =

n * Factorial (n-1)

#include<stdio.h>
int main()
{
int n;
int factorial(int);
printf("Enter the number:");
scanf("%d",&n);
printf("Factorial of %d is %d",n,factorial(n));
return 0;
}
int factorial(int n)
{
if(n==0)
return 1;
else
return(n*factorial(n-1));
}

Output
Enter the number: 5
Factorial of 5 is 120
Execution
Warning!
1. Recursive function must have at least one terminating condition that can be
satisfied.
2. Otherwise, the recursive function will call itself repeatably until the run time stack
overflows.

9. Explain the Pattern of Recursive Calls with suitable example.

Recursive calls are classified as,


1) Linear Recursion
2) Binary Recursion
3) N-ary Recursion
Linear Recursion
There is only one recursive call within its body.

How it works

Main Factorial(5) Factorial(4) Factorial(3) Factorial(2) Factorial(5)

arg 5 arg 4 arg 3 arg 2 arg 1

Temp= return return return return return


factorial(5) n*factorial n*factorial n*factorial n*factorial n*factorial
(n-1); (n-1); (n-1); (n-1); (n-1);

return(120) return(5*24) return(4*6); return(3*2); return(2*1); return(1);

Factorial(5) = 5 * factorial (4)


4 * factorial (3)

3 * factorial (2)

2 * factorial (1)

1 * factorial (0)

 An initial argument value is 5.


 In return statement, it multiplies 5 with 5-1 and 5-1 multiplies with 5-2 etc.
 When it reaches 1, stops execution and returns the result.

10. Write a program to solve Tower or Hanoi proble.

#include<stdio.h>
#include<conio.h>
void main()
{
void move(int,int,int,int);
int disks=3;
clrscr();
printf("Follow these moves:\n");
move(disks,1,3,2);
}
void move(int count,int start,int finish, int temp)
{
if(count>0)
{
move(count-1,start,temp,finish);
printf("%d from %d to %d ",count,start,finish);
move(count-1,temp,finish,start);
}
}

Follow these moves:


1 from 1 to 3
2 from 1 to 2
1 from 3 to 2
3 from 1 to 3
1 from 2 to 1
2 from 2 to 3
1 from 1 to 3

11. What is pointer? Explain with example.


Pointers

A pointer is a variable that holds the address of a variable or a function. Every


pointer variable occupies same amount of memory space to store the variables belongs
int, float, char or any other type.

P X

Here, P is a pointer, which points the variable X.

Syntax

Storage_Access_specifier type_qualifier type_modifier type_specifier* identifier = value

 Storage_Access_specifier, type_qualifier and type_modifier are optional.


 Type_specifier and identifier are mandatory.

Example

int *ptr; // Pointer to a integer variable


float *ptr; // Pointer to a float variable
char *ptr; // Pointer to a character variable

 ‘*’ operator is called as “Value at address operator”, “indirection operator” or


“Dereferencing” operator.
 These pointer variables can be used to store corresponding type variable’s
address.
 That is, integer pointer can be used to refer integer variable’s address.
 Every pointer takes same amount of memory to store any type of variable.

To initialize pointer valriable,


Syntax

Pointer_variable_name=&Variable_Name;
Example
p=&x;

Example

#include<stdio.h>
#include<conio.h>
void main()
{
int x;
int *ptr;
printf("Enter value for x:");
scanf("%d",&x);
ptr=&x;
printf("\n\nx = %d",x);
printf("\n\n&x = %u",&x);
printf("\n\nptr = %u",ptr);
printf("\n\n*ptr = %d",*ptr);
getch();
}
Output

x = 23
&x = 65524
ptr = 65524
*ptr = 23

12. Is null pointer is useful? Give example.


Null Pointer
A null pointer is a special pointer value that points nowhere. To make pointer as
null pointer, initialize it with zero. That represents the null pointer is not intended to point
to an accessible memory location.
Example
#include<stdio.h>
void main()
{
int a;
float b;
void *p=0;
clrscr();

a=10;
b=10.2;

p=&a;
printf("\nInteger a = %d",*(int *)p);

p=&b;
printf("\nFloat b = %f",*(float *)p);
getch();
}

Output
Integer a = 10
Float b = 10.200000

13. Explain the use of pointers to swap two values with example.
Example
#include<stdio.h>
int main()
{
int x,y;
void swap(int*,int*);
printf("Enter two numbers:");
scanf("%d%d",&x,&y);
printf("\n\nBefore Swapping:\n\nx = %d\n\ny = %d",x,y);
swap(&x,&y);
printf("\n\nAfter Swapping:\n\nx = %d\n\ny = %d\n\n",x,y);
return 0;
}
void swap(int *a, int *b)
{
*a=*a+*b;
*b=*a-*b;
*a=*a-*b;
}

Enter two numbers: 2 7

Before Swapping:
x=2
y=7

After Swapping:
x=7
y=2

 In function call, the actual arguments are passed as reference of variable or


address of variable. (swap(&x,&y);
 In function definition the address of x is assigned to pointer variable a and address
of y is assigned to pointer variable b.
 After completion of exchange or swap process, the function returns the exchanged
values to the actual arguments also.
 Thats why, the statemet,
“printf("\n\nAfter Swapping:\n\nx = %d\n\ny = %d\n\n",x,y);”
in main function returns swapped values.
14. Write a C program to exchange the values of two variables using pass by reference.

#include<stdio.h>
#include<conio.h>

void swap(int *num1, int *num2);

void main()
{
int x, y;

printf("\nEnter First number : ");


scanf("%d", &x);

printf("\nEnter Second number : ");


scanf("%d", &y);

printf("\nBefore Swaping x = %d and y = %d", x, y);


swap(&x, &y); // Function Call - Pass By Reference

printf("\nAfter Swaping x = %d and y = %d", x, y);


getch();
}

void swap(int *num1, int *num2)


{
int temp;
temp = *num1;
*num1 = *num2;
*num2 = temp;
}

Output:

Enter First number : 12


Enter Second number : 21

Before Swaping x = 12 and y = 21


After Swaping x = 21 and y = 12

15. Write a C program to find the sum of the digits using recursive
function.

#include <stdio.h>

int sum (int a);

int main()
{
int num, result;
printf("Enter the number: ");
scanf("%d", &num);
result = sum(num);
printf("Sum of digits in %d is %d\n", num, result);
return 0;
}

int sum (int num)


{
if (num != 0)
{
return (num % 10 + sum (num / 10));
}
else
{
return 0;
}
}

OUTPUT:

$ cc pgm25.c
$ a.out
Enter the number: 2 3 4 5
Sum of digits in 2 3 4 5 is 14

16.Write a C program using pointers to read in an array of integers and


print its elements in reverse order.

#include<stdio.h>
#include<conio.h>
#define MAX 30

void main()
{
int size, i, arr[MAX];
int *ptr;
clrscr();

ptr = &arr[0];

printf("\nEnter the size of array : ");


scanf("%d", &size);

printf("\nEnter %d integers into array: ", size);


for (i = 0; i < size; i++)
{
scanf("%d", ptr);
ptr++;
}

ptr = &arr[size - 1];

printf("\nElements of array in reverse order are :");

for (i = size - 1; i >= 0; i--) {


printf("\nElement%d is %d : ", i, *ptr);
ptr--;
}

getch();
}
OUTPUT:

Enter the size of array :5


Enter 5 integers into array: 11 22 33 44 55
Elements of array in reverse order are:
Element 4 is : 55
Element 4 is : 44
Element 4 is : 33
Element 4 is : 22
Element 4 is : 11

17. Write a C program to arrange the number in ascending order.

#include <stdio.h>

void main()
{
int i, j, a, n, number[30];

printf("Enter the value of N \n");


scanf("%d", &n);
printf("Enter the numbers \n");
for (i = 0; i < n; ++i)
scanf("%d", &number[i]);
for (i = 0; i < n; ++i)
{
for (j = i + 1; j < n; ++j)
{
if (number[i] > number[j])
{
a = number[i];
number[i] = number[j];
number[j] = a;
}
}
}
printf("The numbers arranged in ascending order are given below \
n");
for (i = 0; i < n; ++i)
printf("%d\n", number[i]);
}

OUTPUT:
$ cc pgm66.c
$ a.out
Enter the value of N
6
Enter the numbers
3
78
90
456
780
200
The numbers arranged in ascending order are given below
3
78
90
200
456
780

18.Write a C program to subtract two matrices and display the resultant


matrix.

#include<stdio.h>
int main()
{
int i, j, mat1[10][10], mat2[10][10], mat3[10][10];
int row1, col1, row2, col2;

printf("\nEnter the number of Rows of Mat1 : ");


scanf("%d", &row1);
printf("\nEnter the number of Cols of Mat1 : ");
scanf("%d", &col1);

printf("\nEnter the number of Rows of Mat2 : ");


scanf("%d", &row2);
printf("\nEnter the number of Columns of Mat2 : ");
scanf("%d", &col2);

/* Before accepting the Elements Check if no of


rows and columns of both matrices is equal */
if (row1 != row2 || col1 != col2)
{
printf("\nOrder of two matrices is not same ");
exit(0);
}

//Accept the Elements in Matrix 1


for (i = 0; i < row1; i++) {
for (j = 0; j < col1; j++) {
printf("Enter the Element a[%d][%d] : ", i, j);
scanf("%d", &mat1[i][j]);
}
}

//Accept the Elements in Matrix 2


for (i = 0; i < row2; i++)
for (j = 0; j < col2; j++) {
printf("Enter the Element b[%d][%d] : ", i, j);
scanf("%d", &mat2[i][j]);
}

//Subtraction of two matrices


for (i = 0; i < row1; i++)
for (j = 0; j < col1; j++) {
mat3[i][j] = mat1[i][j] - mat2[i][j];
}

//Print out the Resultant Matrix


printf("\nThe Subtraction of two Matrices is : \n");
for (i = 0; i < row1; i++) {
for (j = 0; j < col1; j++) {
printf("%d\t", mat3[i][j]);
}
printf("\n");
}

return (0);
}

OUTPUT:
Enter the number of Rows of Mat1 :3
Enter the number of Columns of Mat1 : 3

Enter the number of Rows of Mat2 : 3


Enter the number of Columns of Mat2 : 3

Enter the Element a[0][0] : 2


Enter the Element a[0][1] : 4
Enter the Element a[0][2] : 6
Enter the Element a[1][0] : 4
Enter the Element a[1][1] : 2
Enter the Element a[1][2] : 2
Enter the Element a[2][0] : 2
Enter the Element a[2][1] : 4
Enter the Element a[2][2] : 2

Enter the Element b[0][0] : 1


Enter the Element b[0][1] : 2
Enter the Element b[0][2] : 3
Enter the Element b[1][0] : 2
Enter the Element b[1][1] : 1
Enter the Element b[1][2] : 1
Enter the Element b[2][0] : 1
Enter the Element b[2][1] : 2
Enter the Element b[2][2] : 1

The Subtraction of two Matrices is :


1 2 3
2 1 1
1 2 1

You might also like