0% found this document useful (0 votes)
24 views8 pages

Unit 4

Uploaded by

yashpareek746
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
24 views8 pages

Unit 4

Uploaded by

yashpareek746
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 8

What is Function : A function is a group of statements that together perform a task.

Benefits of using functions in a program :

a) To improve the readability of code.


b) Improves the reusability of the code, same function can be used in any program rather than writing the same code
from scratch.
c) Debugging of the code would be easier if you use functions, as errors are easy to be traced.
d) Reduces the size of the code, duplicate set of statements are replaced by function calls.

Types of Functions :

1) Predefined standard library functions


Standard library functions are also known as built-in functions. Functions such s puts(), gets(), printf(), scanf() etc
are standard library functions. These functions are already defined in header files so we just call them whenever
there is a need to use them.

2) User Defined functions


The functions that we create in a program are known as user defined functions or in other words a function created
by user is known as user defined function.

To use a function in C program we have to perform the following tasks


(i) Function declaration (Prototype)
(ii) Function definition
(iii) Function Call

Important points to use functions


(i) Function declaration/Function definition must appear before function call.
(ii) No need to write function declaration if function definition appear before function call.
(iii) Function declaration(Prototype) does not contain function body.
(iv) A function returns a single value.
(v) If a function does not return a value then return type should be void.

Defining a Function
The general form of a function definition in C programming language is as follows −

return_type function_name( parameter list )


{
body of the function
}

A function definition in C programming consists of a function header and a function body. Here are all the parts of a
function −

• Return Type − A function may return a value. The return_type is the data type of the value the function returns.
Some functions perform the desired operations without returning a value. In this case, the return_type is the
keyword void.

• Function Name − This is the actual name of the function.

• Parameters − A parameter is like a placeholder. When a function is invoked, we pass a value to the parameter.
This value is referred to as actual parameter or argument. The parameter list refers to the type, order, and
number of the parameters of a function. Parameters are optional; that is, a function may contain no parameters.
• Function Body − The function body contains a collection of statements that define what the function does.

Function Declarations : A function declaration tells the compiler about a function name, parameter list and return
type. It does not contain function body.

A function declaration has the following parts −


return_type function_name( parameter list );

Calling a Function
To call a function, we simply need to pass the required parameters along with the function name, and if the function returns
a value, then we can store the returned value.

Example 1 : Write a program to input two numbers and print sum using function.

#include <stdio.h>
int sum(int a,int b); // Function prototype
void main()
{
int x,y,ans;
printf("Input two numbers ");
scanf("%d%d",&x,&y);
ans=sum(x,y); // Function Call
printf("Addition is %d \n",ans);

}
int sum(int a,int b) // Function Definition
{
return a+b;
}

Example 2 : Write a program to input a number and print factorial using recursive function.
What is recursion : When a function calls itself is called recursion.
#include <stdio.h>
int fact(int n)
{
if (n==0)
return 1;
else
return n*fact(n-1);
}
void main()
{
int n,ans;
printf("Input a numbers ");
scanf("%d",&n);
ans=fact(n);
printf("Factorial is %d \n",ans);

}
Example 3 : Write a program to input a string and print length using function.
#include <stdio.h>
int len(char str[])
{
int i=0;
while (str[i] != '\0')
i++;

return i;
}
void main()
{
char str[30];
int ans;
printf("Input a string ");
scanf("%s",str);
ans=len(str);
printf(" Length of String %d \n",ans);

C Storage class
Every variable in C programming has two properties: type and storage class. Type refers to the data type of a variable and
storage class determines the scope, visibility and lifetime of a variable.
There are 4 types of storage class:

(i) automatic (local)


(ii) external (global)

(iii) static
(iv) register

(i) Local Variables : Variables that are declared inside a function or block are called local variables. They can be used
only by statements that are inside that function or block of code. Formal parameters are treated as local variables with-in a
function
(ii) Global Variables : Global variables are defined outside a function, usually on top of the program. Global variables hold
their values throughout the lifetime of your program and they can be accessed inside any of the functions defined for the
program. A program can have same name for local and global variables but the value of local variable inside a function will
take preference.

#include <stdio.h>
void display();

int n = 5; // global variable

int main()
{
++n;
display();
return 0;
}

void display()
{
++n;
printf("n = %d", n);
}
Output will be 7

(iii) static : The value of a static variable persists until the end of the program .

#include <stdio.h>
void display();

int main()
{
display();
display();
}
void display()
{
static int c = 1;
c += 5;
printf("%d ",c);
}

Output will be 6 11
(iv) register : These variables are declared inside cpu registers to make processing fast.

register int a;
Storage Storage Default initial Lifetime Scope Keyword
Class Area value

Automatic Memory Garbage value Within Block/Function Local Auto

Register CPU Garbage value Within Block/Function Local Register


register

Static Memory Zero Throughout program Local Static


execution

External Memory Garbage value Throughout program Global Extern


execution

C Pointers
pointer is a variable which stores the address of another variable. This variable can be of type int, char, array, function, or
any other pointer. The size of the pointer depends on the architecture. However, in 32-bit architecture the size of a pointer
is 2 byte.

Declaring a pointer : The pointer in c language can be declared using * (asterisk symbol). It is also known as indirection

pointer used to dereference a pointer.

int *a; //pointer to int


char *c; //pointer to char

Address Of (&) Operator


The address of operator '&' returns the address of a variable. But, we need to use %u to display the address of a variable.

Advantage of pointer
1) Pointer reduces the code and improves the performance, it is used to retrieving strings, trees, etc. and used with
arrays, structures, and functions.

2) We can return multiple values from a function using the pointer.

3) It makes you able to access any memory location in the computer's memory.

Usage of pointer
There are many applications of pointers in c language.

1) Dynamic memory allocation

In c language, we can dynamically allocate memory using malloc() and calloc() functions where the pointer is used.
2) Arrays, Functions, and Structures

Pointers in c language are widely used in arrays, functions, and structures. It reduces the code and improves the
performance.

Example 1 :
#include<stdio.h>
Void main()
{
int num=50;
printf(“ Address of num : %u \n”,&num);
printf(“Value of num : %d \n”,num);
}

Example 2 :
#include<stdio.h>
Void main()
{
int num=50;
int *p;
p=&num; //stores the address of number variable
printf("Address of p variable is %u \n",p); // p contains the address of the number therefore printing
p gives the address of number.
printf("Value of p variable is %d \n",*p); // As we know that * is used to dereference a pointer therefor
e if we print *p, we will get the value stored at the address contai
ned by p.
}

Example 3 :
#include <stdio.h>
int main()
{
int* pc, c;

c = 22;
printf("Address of c: %p\n", &c);
printf("Value of c: %d\n\n", c); // 22

pc = &c;
printf("Address of pointer pc: %p\n", pc);
printf("Content of pointer pc: %d\n\n", *pc); // 22

c = 11;
printf("Address of pointer pc: %p\n", pc);
printf("Content of pointer pc: %d\n\n", *pc); // 11

*pc = 2;
printf("Address of c: %p\n", &c);
printf("Value of c: %d\n\n", c); // 2
return 0;
}

Common mistakes when working with pointers


int c, *pc;

// pc is address but c is not


pc = c; // Error

// &c is address but *pc is not


*pc = &c; // Error

// both &c and pc are addresses


pc = &c;

// both c and *pc values


*pc = c;

Pointer Arithmetic :
Pointers variables are also known as address data types because they are used to store the address of another
variable. The address is the memory location that is assigned to the variable. It doesn’t store any value.
Hence, there are only a few operations that are allowed to perform on Pointers. The operations are slightly
different from the ones that we generally use for mathematical calculations. The operations are:

1. Increment/Decrement of a Pointer
2. Addition of integer to a pointer
3. Subtraction of integer to a pointer
4. Subtracting two pointers of the same type
5. Comparison of two Pointers

Increment: 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.

Decrement: 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.

Addition : When a pointer is added with a value, the value is first multiplied by the size of data type and then
added to the pointer.

Subtraction : When a pointer is subtracted with a value, the value is first multiplied by the size of the data type
and then subtracted from the pointer.

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
calculating how many bits of data it is according to the pointer data type. The subtraction of two pointers gives the
increments between the two pointers.
Example :

#include<stdio.h>
void main ()
{
int arr[5] = {1, 2, 3, 4, 5};
int *p = arr;
int i;
printf("printing array elements...\n");
for(i = 0; i< 5; i++)
{
printf("%d ",a[i]);
printf("%d ",*(a+i));
printf(“ %u “,a); // Address of array
printf(“%u “,p);
}
}

You might also like