C Unit-2 PPT
C Unit-2 PPT
C Unit-2 PPT
Language
Unit -2
Functions
• A function is a group of statements enclosed by {} that together
perform a task.
• A function can be called multiple times to provide reusability and
modularity to the C program.
• You can pass data, known as parameters/arguments, into a function.
Types of Functions:
There are two types of functions:
1.Library Functions: are the functions which are declared in the C header
files such as scanf(), printf(), gets(), puts(), ceil(), floor() etc.
2.User-defined functions: are the functions which are created by the C
programmer, so that he can use it many times. It reduces the complexity of
a big program and optimizes the code.
Function declaration:
• A function declaration must be declared globally in a c program to tells the
compiler about a function's name, return type, and parameters.
• The syntax of function declaration is as follows −
return_type function_name( parameter list )
Function definition:
• A function definition provides the actual body of the function.
• The general form of a function definition is as follows −
return_type function_name( parameter list )
{
body of the function
}
Function call:
• Function can be called from anywhere in the program.
• The parameter list must not differ in function calling and function
declaration.
• The syntax of function declaration is as follows −
function_name( parameter list )
Return Value:
• A function may or may not return a value from the function. If you don't
have to return any value from the function, use void for the return type.
• If you want to return any value from the function, you need to use any
data type such as int, float, char, etc.
• The return type depends on the value to be returned from the function.
• A function may or may not accept any argument. It may or may not
return any value.
• Based on these facts, There are four different aspects of function calls.
function without arguments and without return value
function without arguments and with return value
function with arguments and without return value
function with arguments and with return value
Example for Function without argument and return value:
#include<stdio.h>
void sum();
void main()
{
printf("\nGoing to calculate the sum of two numbers:"); su
m();
}
void sum()
{
int a,b;
printf("\nEnter two numbers");
scanf("%d %d",&a,&b);
printf("The sum is %d",a+b);
}
Example for Function without argument and with return value:
#include<stdio.h>
int sum();
void main()
{
int result;
printf("\nGoing to calculate the sum of two numbers:");
result = sum();
printf("%d",result);
}
int sum()
{
int a,b;
printf("\nEnter two numbers");
scanf("%d %d",&a,&b);
return a+b;
}
Example for Function with argument and without return value:
#include<stdio.h>
void sum(int, int);
void main()
{
int a,b,result;
printf("\nGoing to calculate the sum of two numbers:");
printf("\nEnter two numbers:");
scanf("%d %d",&a,&b);
sum(a,b);
}
void sum(int a, int b)
{
printf("\nThe sum is %d",a+b);
}
Example for Function with argument and with return value:
#include<stdio.h>
int sum(int, int);
void main()
{
int a,b,result;
printf("\nGoing to calculate the sum of two numbers:");
printf("\nEnter two numbers:");
scanf("%d %d",&a,&b);
result = sum(a,b);
printf("\nThe sum is : %d",result);
}
int sum(int a, int b)
{
return a+b;
}
Recursion:
The process in which a function calls itself is called recursion and the
corresponding function which calls itself is called a recursive function.
There are two methods to pass the data into the function, call by
value and call by reference.
Call by value:
• The value of the actual parameters is copied into the formal parameters.
• The value of actual parameters do not change by changing the formal para
meters.
Call by reference:
•The address of the variable is passed into the function call as the actual
parameter.
•The value of the actual parameters can be modified by changing the formal
parameters since the address of the actual parameters is passed.
Example: Swapping the values of the two variables using call by value method.
#include <stdio.h>
void swap(int , int); //prototype of the function
int main()
{
int a = 10;
int b = 20;
printf("Before swapping the values in main a = %d, b = %d\n",a,b);
swap(a,b);
printf("After swapping values in main a = %d, b = %d\n",a,b);
}
void swap (int a, int b)
{
int temp;
temp = a;
a=b;
b=temp;
printf("After swapping values in function a = %d, b = %d\n",a,b);
} Output:
Before swapping the values in main a = 10, b = 20
After swapping values in function a = 20, b = 10
After swapping values in main a = 10, b = 20
Example: Swapping the values of the two variables using call by reference method.
#include <stdio.h>
void swap(int *, int *); //prototype of the function
int main()
{
int a = 10;
int b = 20;
printf("Before swapping the values in main a = %d, b = %d\n",a,b);
swap(&a,&b);
printf("After swapping values in main a = %d, b = %d\n",a,b);
}
void swap (int *a, int *b)
{
int temp;
temp = *a;
*a=*b;
*b=temp;
printf("After swapping values in function a = %d, b = %d\n",*a,*b);
}
Output:
Before swapping the values in main a = 10, b = 20
After swapping values in function a = 20, b = 10
After swapping values in main a = 20, b = 10
Preprocessor Directives
• The pre-processor is a program which process the source code
before it passes through compiler.
• Preprocessor directives begin with a ‘#’ (hash) symbol.
• The ‘#’ symbol indicates that whatever statement starts with a ‘#’ will
go to the preprocessor program to get executed.
• Pre-processor are placed in source program before the main line and
do not require a semicolon at the end.
You can see the intermediate steps in the above diagram.
• The source code written by programmers is first stored in a file, let the
name be “program.c“.
• This file is then processed by preprocessors and an expanded source code
file is generated named “program.i”.
• This expanded file is compiled by the compiler and an object code file is
generated named “program.obj”.
• Finally, the linker links this object code file to the object code of the
library functions to generate the executable file “program.exe”.
1. Macros
2. File Inclusion
3. Conditional Compilation
4. Other directives
1. Macros:
• Macros are pieces of code in a program that is given some name.
• Whenever this name is encountered by the compiler, the compiler
replaces the name with the actual piece of code.
• The ‘#define’ directive is used to define a macro.
• Macro definitions do not need a semi-colon to end.
Example:
#include <stdio.h> Output:
#define LIMIT 5
0
void main()
{
1
for (int i = 0; i < LIMIT; i++) 2
{ 3
printf("%d \n",i); 4
}
}
Note: The word ‘LIMIT’ in the macro definition is called a macro template and ‘5’ is
macro expansion.
Macros With Arguments:
We can also pass arguments to macros. Macros defined with arguments
work similarly to functions.
Example:
#include <stdio.h>
#define AREA(l, b) (l * b)
Void main()
{
int l1 = 10, l2 = 5, area;
area = AREA(l1, l2);
printf("Area of rectangle is: %d", area);
}
Output:
Syntax:
#ifdef macro_name
statement1;
statement2;
statement3;
.
.
statementN;
#endif
If the macro with the name ‘macro_name‘ is defined, then the block of
statements will execute normally, but if it is not defined, the compiler will
simply skip this block of statements.
Example:
#include <stdio.h>
#include <conio.h>
#define NOINPUT
void main()
{
int a=0;
#ifdef NOINPUT
a=2;
#endif
printf("Value of a: %d\n", a);
getch();
}
Output:
Value of a: 2
4. Preprocessor Operators
#define message_for(a, b) \
printf(#a " and " #b ": We love you!\n")
void main()
{
message_for(Carole, Debra);
}
Output:
Carole and Debra: We love you!
The Token Pasting (##) Operator:
The token-pasting operator (##) within a macro definition combines two
arguments. It permits two separate tokens in the macro definition to be
joined into a single token.
Example:
#include <stdio.h>
void main()
{
int token34 = 40;
tokenpaster(34);
}
Output:
token34 = 40
Storage Classes
Storage classes are used to determine the lifetime, visibility, memory
location, and initial value of a variable.
There are four types of storage classes in C.
• Automatic
• External
• Static
• Register
Automatic:
•Automatic variables are allocated memory automatically at runtime.
•The scope of the automatic variables is limited to the block in which they
are defined.
•The automatic variables are initialized to garbage by default.
•The keyword used for defining automatic variables is auto.
•Every local variable is automatic in C by default.
Example:
#include <stdio.h>
int main()
{
auto int a = 10,i;
printf("%d ",++a);
{
auto int a = 20;
for (i=0;i<3;i++)
{
printf("%d ",a); // 20 will be printed 3 times since it is the local value of a
}
}
printf("%d ",a); // 11 will be printed since the scope of a = 20 is ended.
}
Output:
11 20 20 20 11
External:
•Extern storage class is used when we have global functions or variables which
are shared between two or more files.
•If a variable is declared as external then the compiler searches for that
variable to be initialized somewhere in the program. If it is not, then the
compiler will show an error.
•The keyword extern is used to declare a external storage class.
•The default initial value of external integral type is 0 otherwise null.
•We can only initialize the extern variable globally.
Example:
#include <stdio.h>
int a = 20;
int main()
{
extern int a;
printf("%d",a);
}
Output:
20
Static:
•The variables defined as static specifier can hold their value between the
multiple function calls.
•Static local variables are visible only to the function or the block in which they
are defined.
•The visibility of the static global variable is limited to the file in which it has
declared.
•Default initial value of the static integral variable is 0 otherwise null.
•The keyword used to define static variable is static.
Example:
#include<stdio.h>
void main() void sum()
{ { Output:
int i; static int a = 10;
for(i = 0; i< 3; i++) static int b = 24; 10 24
{ printf("%d%d \n",a,b); 11 25
sum(); a++; 12 26
} b++;
} }
Register:
•It is similar to the auto storage class. The variable is limited to the
particular block.
•The variables defined as the register is allocated the memory into the CPU
registers depending upon the size of the memory remaining in the CPU.
•We can not use &operator for the register variable.
•The default value of the register local variables is 0.
•The keyword register is used to declare a register storage class.
Example:
#include <stdio.h>
int main()
{
register int a = 0;
printf("%u",&a); // This will give a compile time error since we can not acce
ss the address of a register variable.
}
Array
An array is defined as the collection of similar type of data items stored at
contiguous memory locations.
Advantages:
1) Code Optimization: Less code to the access the data.
2) Ease of traversing: By using the for loop, we can retrieve the elements of
an array easily.
3) Ease of sorting: To sort the elements of the array, we need a few lines of
code only.
4) Random Access: We can access any element randomly using the array.
Disadvantages:
1) Size Limit: We can store only the fixed size of elements in the array. It
doesn’t grow its size at runtime.
Declaration of one dimensional (1D) Array:
data_type array_name[array_size];
int marks[5];
Initialization of 1D Array:
marks[0]=80;
marks[1]=60;
marks[2]=70;
marks[3]=85;
marks[4]=75;
int marks[5]={20,30,40,50,60};
int marks[]={20,30,40,50,60};
Array Input/Output:
Example : Program to take 5 values from the user and store them in an
array
#include <stdio.h>
Void main() Output:
{ Enter 5 integers: 1
int values[5]; -3
printf("Enter 5 integers: "); 34
for(int i = 0; i < 5; ++i) 0
{ 3
scanf("%d", &values[i]); Displaying integers: 1
} -3
printf("Displaying integers: "); 34
for(int i = 0; i < 5; ++i) 0
{ 3
printf("%d\n", values[i]);
}
}
Two Dimensional (2D) Array:
• The two-dimensional array can be defined as an array of arrays.
• The 2D array is organized as matrices which can be represented as the
collection of rows and columns.
data_type array_name[rows][columns];
int twodimen[4][3];
Initialization of 2D Array:
int arr[4][3]={{1,2,3},{2,3,4},{3,4,5},{4,5,6}};
Example: Storing elements in a matrix and printing it.
#include <stdio.h>
void main ()
{
int arr[3][3],i,j; Output:
for (i=0;i<3;i++)
{ Enter a[0][0]: 56
for (j=0;j<3;j++) Enter a[0][1]: 10
{ Enter a[0][2]: 30
printf("Enter a[%d][%d]: ",i,j); Enter a[1][0]: 34
scanf("%d",&arr[i][j]); Enter a[1][1]: 21
} Enter a[1][2]: 34
}
printf("\n Printing the elements ....\n"); Enter a[2][0]: 45
for(i=0;i<3;i++) Enter a[2][1]: 56
{ Enter a[2][2]: 78
printf("\n");
Printing the elements ....
for (j=0;j<3;j++)
{
56 10 30
printf("%d\t",arr[i][j]); 34 21 34
} 45 56 78
}
}
Pointers
The pointer is a variable which stores the address of another variable.
Usage of pointer:
1) Dynamic memory allocation: We can dynamically allocate memory using
malloc() and calloc() functions where the pointer is used.
Declaring a pointer:
The pointer can be declared using * (asterisk symbol). It is also known as
indirection pointer used to dereference a pointer.
Syntax:
datatype *var-name;
int *a;
int n = 10;
int* p = &n;
Example:
#include<stdio.h>
void main()
{
int number=50;
int *p;
p=&number;
printf("Address of number variable is %u \n",number);
printf("Address of p variable is %u \n",p);
printf("Value of p variable is %d \n",*p);
}
Output:
Address of number variable is fff4
Address of p variable is fff4
Value of p variable is 50
Pointer Arithmetic:
• Incrementing Pointer:
If we increment a pointer by 1, the pointer will start pointing to the
immediate next location. The address of the pointer will get
increased by the size of the data type to which the pointer is
pointing.
• Decrementing Pointer:
If we decrement a pointer, it will start pointing to the previous
location. The address of the pointer will get decreased by the size of
the data type to which the pointer is pointing.
Example: Traversing an array by using pointer
#include <stdio.h>
void main ()
{
int var[] = {10, 100, 200};
int i;
int *ptr = var;
for ( i = 0; i < 3; i++)
{
printf("Address of var[%d] = %u\n", i, ptr );
printf("Value of var[%d] = %d\n", i, *ptr );
ptr++;
}
}
Output:
Address of var[0] = bf882b30
Value of var[0] = 10
Address of var[1] = bf882b34
Value of var[1] = 100
Address of var[2] = bf882b38
Value of var[2] = 200
• Pointer Addition:
We can add a value to the pointer variable. The formula of adding value to pointer is:
new_address= current_address + (number * size_of(data type))
• Pointer Subtraction:
We can subtract a value to the pointer variable. The formula of subtracting value to
pointer is given below:
new_address= current_address - (number * size_of(data type))
Example:
#include<stdio.h>
void main()
{
int number=50;
int *p;
p=&number;
printf("Address of p variable is %u \n",p);
p=p+3;
printf("After adding 3: Address of p variable is %u \n",p);
}
Output:
Address of p variable is 3214864300
After adding 3: Address of p variable is 3214864306
Pointer to array:
int arr[10];
int *p[10]=&arr;
Example:
#include <stdio.h>
int main ()
{
int var[3] = {10, 100, 200};
int i, *ptr[3];
Function Description
strlen(string_name) returns the length of string name.
#include <stdio.h>
#include <string.h>
void main ()
{
char str1[12] = "Hello";
char str2[12] = "World";
char str3[12];
int len ;
len = strlen(str1);
printf(“Length of str1: %d\n", len );
strcpy(str3, str1);
printf(“Value of str3: %s\n", str3 );
strcat( str1, str2);
printf(“Value of str1: %s\n", str1 );
}
Output:
Length of str1: 5
Value of str3:Hello
Value of str1:HelloWorld
Example 2:
#include<stdio.h>
#include <string.h>
void main()
{
char str1[20],str2[20];
printf("Enter 1st string: ");
gets(str1);
printf(“1st String is: %s",str1);
printf("\nReverse of 1st String is: %s",strrev(str1));
printf("\nLower of 1st String is: %s",strlwr(str1));
printf("\nUpper of 1st String is: %s",strupr(str1));
printf("Enter 2nd string: ");
Output:
gets(str2);
Enter 1st string: Hello
if(strcmp(str1,str2)==0)
1st string is: Hello
printf("Strings are equal");
Reverse of 1st String is:olleH
else
Lower of 1st String is:hello
printf("Strings are not equal");
Upper of 1st String is:HELLO
}
Enter 2nd string: Hello
Strings are equal
Dynamic memory allocation
• It is used to allocate memory at runtime.
• Dynamic memory allocation is possible by 4 functions of stdlib.h header file.
• malloc()
• calloc()
• realloc()
• free()
malloc() function:
• The malloc() function allocates single block of requested memory.
• It doesn't initialize memory at execution time, so it has garbage value
initially.
• It returns NULL if memory is not sufficient.
Syntax:
ptr=(cast-type*)malloc(byte-size)
calloc() function:
• The calloc() function allocates multiple block of requested memory.
• It initially initialize all bytes to zero.
• It returns NULL if memory is not sufficient.
Syntax:
ptr=(cast-type*)calloc(number, byte-size)
realloc() function:
If memory is not sufficient for malloc() or calloc(), you can reallocate the
memory by realloc() function.
Syntax:
ptr=realloc(ptr, new-size)
free() function:
The memory occupied by malloc() or calloc() functions must be released by
calling free() function. Otherwise, it will consume memory until program exit.
Syntax:
free(ptr)
Example:
#include<stdio.h>
#include<stdlib.h>
void main()
{
int n,i,*ptr,sum=0;
printf("Enter number of elements: ");
scanf("%d",&n);
ptr=(int*)malloc(n*sizeof(int));
if(ptr==NULL)
{
printf("Sorry! unable to allocate memory");
exit(0);
}
printf("Enter elements of array: ");
for(i=0;i<n;++i) Output:
{
Enter elements of array: 3
scanf("%d",ptr+i);
Enter elements of array: 10
sum+=*(ptr+i);
10
}
10
printf("Sum=%d",sum); Sum=30
free(ptr);
return 0; }
Example:
#include <stdio.h>
#include <stdlib.h>
void main()
{
int n, I, *ptr;
n = 5;
printf("Enter number of elements: %d\n", n);
ptr = (int*)calloc(n, sizeof(int));
if (ptr == NULL)
{
printf("Memory not allocated.\n");
exit(0);
}
printf("The elements of the array are: ");
for (i = 0; i < n; ++i)
{
ptr[i] = i + 1;
printf("%d, ", ptr[i]);
}
n = 10;
printf("\n\nEnter the new size of the array: %d\n", n);
ptr = realloc(ptr, n * sizeof(int));
printf("Memory successfully re-allocated using realloc.\n");
printf("The elements of the array are: ");
for (i = 0; i < n; ++i)
{
ptr[i] = i + 1;
printf("%d, ", ptr[i]);
}
free(ptr);
}
}
Output:
Enter number of elements: 5
The elements of the array are: 1, 2, 3, 4, 5,
Enter the new size of the array: 10
Memory successfully re-allocated using realloc.
The elements of the array are: 1, 2, 3, 4, 5, 6, 7, 8, 9, 10,