UNIT 3 PC NOTES
UNIT 3 PC NOTES
UNIT 3 PC NOTES
Modular programming
MAIN PROGRAM
FUNCTION 1 FUNCTION 2
FUNCTION n
Modularity can on different levels :
Libraries in Projects
Function in files, etc
1
3.2 FUNCTION
A function is a sub program which contains one or more statements to do a particular
task
In C, we can divide a large program into the basic building blocks.
The function contains the set of programming statements enclosed by {}.
A function can be called multiple times to provide reusability and modularity.
In other words, we can say that the collection of functions creates a program.
The function is also known as procedure or subroutine in other programminglanguages.
Syntax
Example
int max (int n1, int n2); // Function name declaration with return data type void main()
{
int a=5,b=10; int
big;
big=max(a,b); // Function call
printf(“the big value is %d “,big)
}
int max (int n1, int n2) // max () is the name of a function
{
int x;
if ( n1 > n2)
x = n1; // return n1 when n1 is greater than n2. else
x = n2; // return n2 when n2 is greater than n1. return
x;
}
Advantage of Using Function
2
3.3 TYPES OF FUNCTIONS
There are two types of functions in C programming
a. Built in functions or Library Functions: Functions such as scanf(), printf(),gets(),etc
b. User-defined functions: Functions are created by the C programmer
a) BUILT-IN FUNCTION OR LIBRARY FUNCTIONS
Library functions are built-in functions that are grouped together and placed in a common
location called library.
Each function here performs a specific operation.
We can use this library functions to get the pre-defined output.
All C standard library functions are declared by using many header files.
These library functions are created at the time of designing the compilers.
We include the header files in our C program by using #include<filename.h>.
Whenever the program is run and executed, the related files are included in theC program.
Math functions
Functions
S.No (Syntax) Meaning Example
1 sqrt(x) Returns the squareroot of x (√x) sqrt(25)
2 log(x) Logex log(75)
3 abs(x) |x | abs(-5)
4 fabs(x) |x | fabs(4.65)
5 exp(x) E x exp(5.3)
6 pow(x, y) Xy pow(3, 2)
7 ceil(x) Rounding x to the next biggest integer value ceil(5.6)
8 floor(x) used to convert a floating point number to its floor(5.6)
immediately smaller integer
9 fmod(x, y) Returns the remainder of x/y fmod(7,3)
11 rand( ) Generates a positive random number rand( )
12 sin(x) sin value of x sin(30)
13 cos(x) cos value of x cos(60)
14 tan(x) tan value of x tan(90)
15 cbrt(x) Returns the cube root of x
String functions
S.N Function & Purpose
1) strlen(string_name) returns the length of string name. Ex:
strlen(“Welcome”)
output : 7
2) strcpy(destination, source) copies the contents of source string todestination string.
Ex: strcpy(s1,”welcome”)
output: s1=welcome
3) strcat(first_string, second_string) concats or joins first string with second string. The result
of the string is stored in first string.
Ex: strcat(“Wel”,”come”) output:
Welcome
4) strcmp(first_string, second_string) compares the first string with second string. If both
strings are same, it returns 0.
Ex:strcmp(“Welcome”,”Welcome”)output: 0
3
5) strrev(string) returns reverse string. Ex.
strrev(“Welcome”)
output: emocleW
6) strlwr(string) returns string characters in lowercase. Ex.
strlwr(“Welcome”)
output: welcome
7) strupr(string) returns string characters in uppercase. Ex.
strlwr(“Welcome”)
output: WELCOME
2 Function definition : The function definition consists of a function header followed by the body
of the function
Syntax
return_Type function_name(dt parameter_1, dt parameter_2, .......................... )
{
Statements / Body of the function
}
3. Function call: The calling statement consists of function name with the parameters Syntax:
function_name(argument_list);
Example: Here is an example to find the sum of two numbers. a user-defined function add() is created
to perform this task
#include <stdio.h>
4
int add(int x,int y); //function declaration
int main()
{
int i,j,sum;
printf("Please enter 2 numbers for find sum\n");
sum=add(i,j); //function call
scanf("%d %d",&i,&j);
printf("The result of sum is :%d",sum);
return 0;
getch();
}
int add(int x, int y) //function definition
{
int result;
result=x+y;
return result;
}
Syntax
function_name();
(or)
function_name(parameter types);
(or)
var_name= function_name();(or)
var_name= function_name(parameters)
3.8 RECURSION
The process of calling the function by itself again and again until some condition is
satisfied is called recursive function.
Recursive programs must have at least one if statement to terminate recursion,
otherwise infinite loop will be created.
Each recursive call is made with a new, independent set of arguments
Allows very simple solution for very complex problems
Recursive solution consists of two cases:
o base case : Base case is the smallest instance of problem, which can be easily solved
and there is no need to further express the problem in terms of itself. For example, in
factorial of a number, base case is if n==1, fact=1.
o recursive case: The problem is defined in terms of itself, while reducingthe 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.
Advantages of recursion
Recursive functions make the code look clean and elegant with less no. ofstatements
A complex task can be broken down into simpler sub-problems using recursion.
Useful for branching processes
Disadvantages of recursion
Sometimes the logic behind recursion is hard to follow through.
Recursive calls are expensive (inefficient) as they take up a lot of memory and time.
8
Recursive functions are hard to debug.
9
if (num[Middle] > key)
return b_search(num, Left, Middle-1, key);
else
return b_search(num, Middle+1, Right, key);
}
return -1; // If the element is not found
}
int main(){
int size = 0, key = 0, found = 0;
printf("Enter the size of the array: ");
scanf("%d", & size);
int num[size];
printf("Enter the elements of the array in ascending order: ");
for (int i = 0; i < size; i++) {
scanf("%d", & num[i]);
}
printf("Enter the element to be searched: ");
scanf("%d", & key);
found = b_search(num, 0, size - 1, key);
if (found == -1)
printf("Element is not present in the array");
else
printf("Element found at index %d", found);
return 0;
}
Output :
Enter the size of the array: 6
Enter the elements of the array in ascending order: 2 3 4 5 6 7
Enter the element to be searched: 3
Element found at index 1
3.10 POINTERS
A pointer is a variable that stores the memory address of another variable.
A pointer variable has the data type of the data it is pointing to. It is created with the *
operator. ie if the pointer has the address of an integer value, the data type of pointer is also int.
The address of the variable is assigned to the pointer.
A pointer can be incremented/decremented, i.e., to point to the next/ previous memory
location.
The purpose of pointer is to save memory space and achieve faster execution time. For
example
Declaration of Pointer:
Syntax: data type *ptr_var;
Ex. int *ip;
float *fp;
Inititalization of pointers :
In pointers, initialization is done by assigning the address of a variable to a pointer
variable. This is achieved by ampersand ‘&’ operator. This is called address of
operator
Syntax : data_type * ptr, var;
ptr = &var;
Example : int *p, a;
p = &a;
Using pointer p, we can assess the content of variable a
10
Pointers to pointers
Pointer variable contains the address of another variable. Another pointer variable can store
the address of a pointer variable. This variable is called pointer topointer
Syntax = data type **ptr_var;
Example : int **p;
Example:
#include<stdio.h>
void main()
{
int a=5, *p1, *p2;
p1=&a;
p2 = &p1;
printf(“Direct Access, a=%d\n”,a);
printf(“Indirect Access through pointer p1, a=%d\n”,*p1); printf(“Indirect Access
through pointer p2, a=%d\n”,**p2);
}
Output
11
Direct Access a =5
Indirect Access through pointer p1, a =5
Indirect Access through pointer p2, a =5
Every pointer variable takes the same amount of memory space irrespective of whether
it is a pointer to int, float, char, or any other type
1. Increment/Decrement of a Pointer
Increment operation of a pointer : It is a condition that also comes under addition. When a pointer
is incremented, it actually increments by the number equal to the size of the data type for which it is
a pointer.
For Example: If an integer pointer that stores address 1000 is incremented, then it will increment by
4(size of an int), for a 32 bit computer and the new address will pointto 1004.
Decrement operation of a pointer : It is a condition that also comes under subtraction. When a
pointer is decremented, it actually decrements by the number equal to the size of the data type for
which it is a pointer.
For Example: If an integer pointer that stores address 1000 is decremented, then it will decrement
by 4(size of an int), and the new address will point to 996.
Note : pointers are incremented and decremented by the size of the data typethey point to
// pointer Increment / decrement operation
#include <stdio.h>
int main()
{
int a = 2; int
*p = &a;
printf("p = %u\n", p);
12
p++;
printf("p++ = %u\n", p); // +4 bytes for 32 bit integers
p--;
printf("p-- = %u\n", p); // -4 bytes
return 0;
}
Sample output
p = 3620
p++ = 3624
p-- = 3620
13
4. Subtraction of Two Pointers
The subtraction of two pointers is possible only when they have the same data type. The result is
generated by calculating the difference between the addresses of the two pointers and dividing by
the size of the data type.
For Example: Two integer pointers say ptr1(address:1000) and ptr2(address:1004) are
subtracted. The difference between addresses is 4 bytes. Since the size of int is 4 bytes, therefore the
difference between ptr2 and ptr1 is given by (4/4) = 1.
//Example of Subtraction of Two Pointer
#include <stdio.h> int
main()
{
int x = 6; // Integer variable declaration
int N = 4;
int *ptr1, *ptr2;
ptr1 = &N; // stores address of N
ptr2 = &x; // stores address of x
printf(" ptr1 = %u, ptr2 = %u \n", ptr1, ptr2);
x = ptr2 – ptr1;
printf("Subtraction of ptr2 & ptr1 is %d\n", x);
return 0;
}
Sample output:
ptr1 = 1016, ptr2 = 1020
Subtraction of ptr2 & ptr1 is 1
if (p2==p3)
printf("\n They point to same variable");
else
printf("\n They point to different variable");
return(0);
}
Output:
7012 7008 7012
p1 is greater than p2
They point to different variable
14
Illegal pointer operations:
1 Addition of two pointers are not allowed
2 Only integers can be added to pointer. It is not valid to add a float or a double valueto a pointer
3 Multiplication and division operators cannot be applied on pointers. 4
Bitwise operators cannot be applied on pointers.
5 A pointer variable cannot be assigned a non-address value (except Zero)
int *p ;
p=a or p =&a[0][0] assigning base address to the pointer
Pointer can be used to access the elements of 2 dimensional array using thefollowing formula:
a[i][j] = *(p + i x col_size + j)
Example:
To find value in a[1] [2], following steps are carried out :
= *(1234 + 1*3+2) // 1234 is the pointer value ie &a[0][0]
= *(1234 + 3+2)
= *(1234 + 5*4) // 4 is Scale factor
15
// Program for pointer to two dimensional array
#include<stdio.h>
void main ( )
{
int a[3][3]={1,2,3,4,5,6,7,8,9};
int i,j;
int *p;
p = &a[0][0];
printf ("elements of 2d array are \n");
for (i=0; i<3; i++)
{
for (j=0; j<3; j++)
{
printf ("%d ", *(p+i*3+j));
}
printf ("\n ");
} }
Output:
16
elements of 2d array are 1
2 3
4 5 6
7 8 9
c. Array of Pointers:
An array of pointers is a collection of addresses.
The addresses in the array of pointers could be the addresses of different variables
All the pointers in an array must be of the same data type.
Example program
#include<stdio.h>
void main()
{
int a=10, b=20, c=30;
int* arr[3];
arr[0]=&a; arr[1]=&b;
arr[2]=&c;
printf("The values of variables are:\n");
printf("%d\t%d\t%d",a,b,c);
printf("\n the pointer variable values are %d\t%d\t%d\n",*arr[0],*arr[1],*arr[2]);
printf("\n the address are %u\t%u\t%u\n",arr[0],arr[1],arr[2]);
}
Output
The values of variables are 10 20 30
the pointer variable values are 10 20 30
the address are 4000 4400 5400
Explanation:
arr is an array of integer pointers and holds the addresses of variables a, b and c
All the variables are of the same type.
Example 2:
#include<stdio.h>
void main ( )
{
int a[3]={10,20,30};
int i,*ptr[3];
for(i=0;i<3;i++)
ptr[i]=&a[i];
printf("Values in array = ");
for (i=0;i<3;i++)
printf(" %d \t",*ptr[i]);
}
Output:
Values in array = 10 20 30
3.14 Void pointer and Null Pointer
Void Pointer : A void pointer is the one who does not have any data type with it. It is also called as a
general purpose pointer. It can hold the addresses of any data type
17
Syntax :
void *<ptr_name>;
Example :
void *p;
int a; char c;
p = &a; //p changes to integer pointer as address of integer is assigned to it
p = &c; //p changes to character pointer as address of character is assigned to it
Null Pointer : A pointer that is assigned a NULL is called NULL pointer. It is a good practice to
assign a NULL to a pointer if it does not have an exact address to be assigned.
Syntax :
<data type> *ptr = NULL;
Eg :
# include <stdio.h> int
main()
{
int *p = NULL;
printf(“The value of pointer p is %u \n”,p);return
0;
}
Output :
The value of pointer p is 0
The difference between NULL pointer and void pointer is that NULL pointer is a value and
void pointer is a type
3.15 Pointer for strings
Strings are character arrays terminated by null character. Pointer to a single string may be declared in
the same way as the pointer to a one-dimensional array.
char Name[] = “AAA”; char
*ptrname ; ptrname = Name;
Though the declaration and initialization of a pointer to a string is similar to that of a pointer to an
array, the difference lies in the input/output. String may be taken as a single object for input and
output and its characters may also be treated like elements of an array.
// Program to Illustrate pointer to strings
#include <stdio.h>
#include<conio.h>
void main()
{
char *cities[] = {"Chennai", "Delhi","Mumbai"};int i;
clrscr();
for(i = 0; i < 3; i++)
printf("%s\n", cities[i]);
getch();
}
Output :
Chennai
Delhi
Mumbai
Note :Pointers are very helpful in handling character array with rows of varying lengthFor Eg :
Char *name[2] = {“Ram”,”Seetha Raman”, }; will
occupy lesser space than
char name[2][15] = {“Ram”,”Seetha Raman”, };
18
3.16 Function Pointer in C (or) Pointer to Function
In C, like normal data pointers (int *, char *, etc), we can have pointers to functions. Following is a
simple example that shows declaration and function call using function pointer.
#include <stdio.h>
void fun(int a) // A normal function with an int parameter and void return type
{
printf("Value of a is %d\n", a);
}
int main(){
void (*fun_ptr)(int);
fun_ptr = &fun;
(*fun_ptr)(10); // Calling fun() using fun_ptr
return 0;
}
Output:
Value of a is 10
Unlike normal pointers, a function pointer points to code, not data. Typically a function pointer
stores the start of executable code.
Example Program:
#include<stdio.h>
void swap(int,int);
void main()
{ int a,b;
printf("Enter a and b values:");
scanf("%d %d",&a,&b);
printf("Before swap(), a=%d\tb=%d\n",a,b);
swap(a,b);
printf("\nAfter swap(), a=%d\tb=%d\n",a,b);
}
void swap(int x,int y){
int temp;
temp=x;
x=y;
y=temp;
printf("\In swap() function, x=%d\t y=%d",x,y);
}
OUTPUT:
Enter a and b
values: 10 20
Before swap(),
a=10 b=20
In swap() function
x=20 y=10
After swap(),
a=10 b=20
19
Call by Reference (or) Pass by reference(or) Passing Arguments by reference:
In this method, the addresses of the actual arguments are passed to the formal parameters
of the function. If the arguments are passed by reference , the changes made in the values pointed
to by the formal parameters in the called function are reflected back to the calling function
Example Program:
#include<stdio.h> void
swap(int*,int*); void
main()
{
int a,b;
printf("Enter a and b values:");
scanf("%d %d",&a,&b);
printf("Before swap(), a=%d\tb=%d\n",a,b);
swap(&a,&b);
printf("\nAfter swap(), a=%d\tb=%d\n",a,b);
}
void swap(int *x,int *y)
{
int temp;
temp=*x;
*x=*y;
*y=temp;
printf("\In swap() function, x=%d\t y=%d",*x,*y);
}
OUTPUT:
Enter a and b values: 10 20
Before swap(), a=10 b=20 In
swap(), x=20 y=10
After swap(), a=20 b=10
5 New location is created , this Existing memory location is used through its
method is slow address, this method is fast
20
//Additional Programs
//To find Sum of N natural numbers Using Function
#include<stdio.h>
#include<conio.h>
void sum();
void main()
{
clrscr();
sum();
getch();
}
void sum()
{
int i,sum1=0,num;
printf("Enter a number:");
scanf("%d",&num);
for(i=1;i<=num;i++)
{
sum1=sum1 + i;
}
printf("Sum of Natural Number is %d",sum1);
}
21
// C program using pointer to read in an array of integers and print its element in reverse order
#include<stdio.h>
#include<conio.h>
void main()
{
int size, i, arr[10];
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();
}
22
void slen(char *s) //String Length
{
int l;
for(l=0;s[l]!='\0';l++);
printf("\nLength of string (%s) is %d\n",s,l);
}
void srev(char *s) //String Reverse
{
int i,j;
char temp;
for(i=0;s[i]!='\0';i++);
i--;
for(j=0;i>j;)
{
temp=s[i];
s[i]=s[j];
s[j]=temp;
j++;
i--;
}
printf("\nThe reversed string is %s \n",s);
}
void scpy(char *s, char *ss) //String Copy
{
int i;
for(i=0;ss[i]!='\0';i++)s[i]=ss[i];
s[i]='\0';
printf("\nString copy from s2 to s3 is %s\n",s);
}
void scmp(char *s, char *ss) //String Compare
{
int flag,i;
for(i=0;s[i]!='\0'||ss[i]!='\0';i++)
{
if(s[i]==ss[i])
flag=1;
else
{
flag=0;
break;}
}
if(flag==1)
printf("\n Two strings are equal\n");
else
printf("\n Two strings are not equal");
}
void scat(char *s, char *ss) //String Concatenation
{
int i,j;
for(i=0;s[i]!='\0';i++);
for(j=0;ss[j]!='\0';j++)
{
s[i]=ss[j];
i++;
23
}
s[i]='\0';
printf("\n The concatenate(s2,s4) is %s\n",s);
}
IMPORTANT QUESTIONS – UNIT 3
Questions
1. Define pointer. How will you declare it?
2. What is a pointer to a pointer?
3. Express the operations that can be performed on pointers.
4. What is pointer arithmetic? What are valid pointer arithmetic operations?
5. What are a void pointer and a null pointer?
6. Differentiate between address operator and indirection operator?
7. Why is pointer arithmetic not applicable on void pointers?
8. Which is better to use? Macro or function. Justify your answer.
9. What is the relation between the operators '&' and '*' in C pointers?
10 Identify the use of Pointer.
11 Point out the meaning of user-defined function.
12 What is meant by library function?
13 Write the syntax for function declaration.
14 Compose the two parts of function definition.
What is the output of the following code fragment? int x=
456, *p1, *p2;
15 p1=&x; p2=&p1;
printf ("Value of x is : %d\n", x);
printf("Value of *p1 is : %d\n", *p1);
printf ("Value of *p2 is: %d\n", *p2);
16 When null pointer is used?
17 What is meant by pass by value and pass by reference?
18 What is a function call? Give an example of a function call.
19 Invent the meaning of default arguments and command line arguments.
20 What is a recursive function?
21 Specify the need for function.
22 Assess the meaning of function pointer.
23 What is array of pointer?
24 Mention the advantage of pass by reference.
25 Compare actual parameter & formal argument
26 What is a function? What are its uses?
27 List out any 4 math functions
24
28 What is a function prototype?
29 Differentiate library and user defined functions
30 Differentiate call by value and call by reference
PART – B
1. Describe about pointers and their operations that can be performed on it.
2. What is modular Programming? How does the Language C support modular
programming? Explain in detail.
3. What is an array of pointers and what is pointer to an array? Explain in detail with
example.
4. Explain about pointers and write the use of pointers in arrays with suitable example.
5. Demonstrate about function declaration and function definition.
6. Classify the function prototypes with suitable examples.
7. What is the necessity of parameter passing in C Programs? What are the two types ofdoing that?
Explain any one in detail.
8. Discuss about the classification of functions depending upon their inputs and output
(parameters)
9. Explain in detail about Pass by Value and Pass by reference.
10 Discuss about passing arrays to function.
11 Explain in detail about recursive function with sample code.
12 Explain in detail about function pointers.
13 Write notes on fixed argument functions and variable argument functions.
14 What are the applications of recursive function? Computation of Sine series using C
program.
15 Write a C program for Scientific calculator using built-in functions.
16 Write a C program for Swapping of two numbers and changing the value of a variable using
pass by reference.
17 Write a C program to sort the given N names.
18 Explain any eight build in functions of math.
19 What is recursion? Explain the procedure to compute sin(x) using recursive functions. Write the
C code for the same.
20 Write a C program to reverse a string using recursion.
21 What is a function in C? Explain the steps in writing a function in C program withExample
22 What is recursion? Write a C program to find the sum of the digits, to find the factorial of a
number and binary search using recursion.
23 Explain the various pointer arithmetic operations with example
24 Explain array of pointers with example
25 Discuss about Pointer operators in brief
25