C Unit-2 PPT

Download as pdf or txt
Download as pdf or txt
You are on page 1of 50

Programming Using ‘C’

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.

Different aspects of function calling:

• 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.

Example: To calculate the factorial of a number.

#include <stdio.h> long int fact(int n)


long int fact (int); {
if (n==0)
int main() {
{ return 1;
int n,f; }
printf("Enter the number:"); else
scanf("%d",&n); {
f = fact(n); return n*fact(n-1); ;
printf("factorial = %d",f); }
return 0; }
}
Call by value and Call by reference:

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”.

There are 4 Main Types of Preprocessor Directives:

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:

Area of rectangle is: 50


2. File Inclusion:
This type of preprocessor directive tells the compiler to include a file in the
source code program.
There are two types of files that can be included by the user in the program:

Header files or Standard files: These files contain definitions of pre-defined


functions like printf(), scanf(), etc. These files must be included to work with
these functions. Different functions are declared in different header files. For
example, standard I/O functions are in the ‘iostream’ file whereas functions
that perform string operations are in the ‘string’ file.
Syntax:
#include< file_name >
where file_name is the name of the file to be included. The ‘<‘ and ‘>’ brackets
tell the compiler to look for the file in the standard directory.

User-defined files: When a program becomes very large, it is a good practice


to divide it into smaller files and include them whenever needed. These types
of files are user-defined files. These files can be included as:
Syntax:
#include"filename"
3. Conditional Compilation
Conditional Compilation directives are a type of directive that helps to
compile a specific portion of the program or to skip the compilation of some
specific part of the program based on some conditions. This can be done with
the help of the two preprocessing commands ‘ifdef‘ and ‘endif‘.

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

The Macro Continuation (\) Operator:


A macro is normally confined to a single line. The macro continuation operator (\) is
used to continue a macro that is too long for a single line.

The Stringize (#) Operator:


The stringize or number-sign operator ( '#' ), when used within a macro definition,
converts a macro parameter into a string constant. This operator may be used only in a
macro having a specified argument or parameter list.
Example:
#include <stdio.h>

#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>

#define tokenpaster(n) printf ("token" #n " = %d", token##n)

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.

Declaration of two dimensional Array:

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.

2) Arrays, Functions, and Structures: Pointers are widely used in arrays,


functions, and structures. It reduces the code and improves the
performance.

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:

There are four arithmetic operators that can be used on pointers:


• Increment
• Decrement
• Addition
• Subtraction

• 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];

for ( i = 0; i < 3; i++)


{
ptr[i] = &var[i];
printf("Value of var[%d] = %d\n", i, *ptr[i] );
}
Output:
Value of var[0] = 10
Value of var[1] = 100
Value of var[2] = 200
Array to Pointer:
int *p[10];
Example:
#include <stdio.h>
int main ()
{
int *ptr[3] = {10, 100, 200};
int i;

for ( i = 0; i < 3; i++)


{
printf("Value of var[%d] = %d\n", i, *ptr[i] );
}
Output:
Value of var[0] = 10
Value of var[1] = 100
Value of var[2] = 200
Pointer to a function:
void show ();
void(*p)() = &show;
Example:
#include<stdio.h>
int addition ();
void main ()
{
int result;
int (*ptr)();
ptr = &addition;
result = (*ptr)();
printf("The sum is %d",result);
}
int addition()
{
int a, b;
printf("Enter two numbers?"); Output:
scanf("%d %d",&a,&b); Enter two numbers?10 15
return a+b; The sum is 25
}
Pointer to Array of functions:
The pointer to an array of functions is a pointer pointing to an array which contains the
pointers to the functions.
Example:
#include <stdio.h> int sum(int x, int y)
int sum(int num1, int num2); {
int sub(int num1, int num2); return(x + y);
}
void main()
int sub(int x, int y)
{ int x, y, choice, result;
int (*ope[2])(int, int); {
ope[0] = sum; return(x - y);
ope[1] = sub; }
printf("Enter two integer numbers:
"); Output:
scanf("%d%d", &x, &y); Enter two integer numbers: 13 48
printf("Enter 0 to sum, 1 to subtract: Enter 0 to sum, 1 to subtract: 1
");
Result=61
scanf("%d", &choice);
result = ope[choice](x, y);
printf(“Result=%d", result);
}
Strings
The string can be defined as the one-dimensional array of characters terminated by a null
('\0'). The '%s' is used as a format specifier for the string.
There are two ways to declare a string in c language.
• By char array
char greeting[6] = {'H', 'e', 'l', 'l', 'o', '\0'};
• By string literal
char greeting[] = "Hello";
gets() and puts() functions:
These functions are declared in the header file stdio.h. Both the functions are involved in
the input/output operations of the strings.
Example:
#include<stdio.h>
#include <string.h>
void main()
{
Output:
char name[50];
Enter your name: Sonia
printf("Enter your name: "); Your name is: Sonia
gets(name);
printf("Your name is: ");
puts(name);
}
String Functions: These functions are declared in the header file string.h.

Function Description
strlen(string_name) returns the length of string name.

strcpy(destination, source) copies the contents of source string to


destination string.
strcat(first_string, second_string) concats or joins first string with second
string. The result of the string is stored
in first string.
strcmp(first_string, second_string) compares the first string with second
string. If both strings are same, it
returns 0.
strrev(string) returns reverse string.
strlwr(string) returns string characters in lowercase.

strupr(string) returns string characters in uppercase.


Example 1:

#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,

You might also like