PPS - Unit 3
PPS - Unit 3
UNIT – III
1
Functions
• A function is a block of code that performs a particular task.
• A function can be called multiple times to provide reusability and
modularity to the C program.
• Dividing a larger program into various subprograms are called as
functions or modules.
Types of Functions
There are two types of functions in C programming:
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/she can use it many times. It reduces the
complexity of a big program and optimizes the code.
Functions
Built-in User-defined
Functions Functions
Functions
Advantages of user-defined function:
• A large program can be divided into smaller modules. Hence, a
large project can be divided among many programmers.
• It makes your code reusable. You just have to call the function by
its name to use it, wherever required.
• In case of large programs with thousands of code lines, debugging
and editing becomes easier if you use functions.
• It makes the program more readable and easy to understand.
How User Defined function works
3 Elements of User defined functions
SNo C Function Syntax
Element
1 Function declaration return_type function_name (argument
list);
Actual Parameters
Formal Parameters
The actual parameters are the parameters that are specified in calling
function.
The formal parameters are the parameters that are declared at called
function.
When a function gets executed, the copy of actual parameter values are
copied into formal parameters.
There are two methods to pass parameters from calling function to called
function and they are as follows...
Call by Value
Call by Reference
Call by Value
• In call by value parameter passing method, the copy of actual
parameter values are copied to formal parameters and these formal
parameters are used in called function.
• The changes made on the formal parameters does not effect the
values of actual parameters.
• After the execution control comes back to the calling function, the
actual parameter values remains same.
Call by Value Example
#include<stdio.h>
void swap(int,int) ; // function declaration
void main(){
int num1, num2 ;
num1 = 10 ; num2 = 20 ;
printf("\nBefore swap: num1 = %d, num2 = %d", num1, num2) ;
swap(num1, num2) ; // calling function
printf("\nAfter swap: num1 = %d\nnum2 = %d", num1, num2);
}
void swap(int a, int b) // called function
{
int temp ;
temp = a ;
a=b;
b = temp ;
}
Call by Reference
• In Call by Reference parameter passing method, the memory
location address of the actual parameters is copied to formal
parameters.
• This address is used to access the memory locations of the actual
parameters in called function.
• Whenever we use these formal parameters in called function, they
directly access the memory locations of actual parameters.
• So the changes made on the formal parameters effects the values of
actual parameters.
Call by Reference Example
#include<stdio.h>
void swap(int *,int *) ; // function declaration
void main(){
int num1, num2 ;
num1 = 10 ; num2 = 20 ;
printf("\nBefore swap: num1 = %d, num2 = %d", num1, num2) ;
swap(&num1, &num2) ; // calling function
printf("\nAfter swap: num1 = %d, num2 = %d", num1, num2);
}
void swap(int *a, int *b) // called function
{
int temp ;
temp = *a ;
*a = *b ;
*b = temp ;
}
Passing Arrays to Functions
#include<stdio.h>
int findSum(int marks[]);
void main()
{
int sum;
int marks[] = {99, 90, 96, 93, 95};
sum = findSum(marks);
printf(“Sum of marks = %d", sum);
}
int findSum(int marks[])
{
int i,sum=0;
for (i = 0; i <= 4; i++) {
sum += marks[i];
}
return sum;
}
Standard Functions and Libraries
Header Example
Purpose
File Functions
stdio.h Standard I/O operations printf(), scanf()
• A variable of structure type can store multiple data items of different data
types under one name.
struct <struct_name>
<data_type> <variable_name>;
<data_type> <variable_name>;
……..
<data_type> <variable_name>;
};
Example of Structure
The structure of Employee is declared as
struct employee
{
int emp_id;
char name[20];
float salary;
char address[50];
int dept_no;
int age;
};
Memory Space Allocation
8000 emp_id
8002 name[20]
8022 salary
8026 address[50]
8076 dept_no
8078 age
Example for sizeof() structure
• #include<stdio.h>
• struct stud
• {
• int roll;
• char name[10];
• int marks;
• };
• void main()
• {
• int size;
• struct stud s; //Declaring a structure variable
• size = sizeof(s);
• printf(“\nSize of Structure : %d", size);
• }
• Size of Structure 'S' = sizeof(roll) + sizeof(name) + sizeof(mark)
Accessing Structure Members
2) s.rollno=111;
strcpy(s.name,“Sanjana”);
s.marks=558;
Example program for structure Initialization
#include<stdio.h>
struct stud
{
int roll;
char name[10];
int marks;
};
void main()
{
int size;
struct stud s={111,"Sanjana",558};
printf("Roll no : %d\n", s.roll);
printf("Name : %s\n", s.name);
printf("Marks : %d\n", s.marks);
}
Example program to read data from keyboard
• #include <stdio.h> •
• struct student
• { • scanf("%d", &s.roll);
• char name[50]; • printf("Enter marks: ");
• int roll; • scanf("%f", &s.marks);
• float marks; • printf("Displaying Information:\
• } s; n");
• void main() • printf("Name: ");
• { • puts(s.name);
• printf("Enter information:\n"); • printf("Roll number: %d\
n",s.roll);
• printf("Enter name: ");
• printf("Marks: %f\n", s.marks);
• scanf("%s", s.name);
• }
• printf("Enter roll number: ");
Structure Assignment
The value of one structure variable is assigned to another
variable of same type using assignment statement. If the e1 and
e2 are structure variables of type employee then the statement
e1 = e2;
For Example:-
struct employee e1[100];
Program to implement the Array of Structure
#include<stdio.h>
struct Employee scanf("%d",&Emp[i].Id);
{ printf("\n\tEnter Employee Name : ");
int Id; scanf("%s",&Emp[i].Name);
char Name[25]; printf("\n\tEnter Employee Age : ");
int Age; scanf("%d",&Emp[i].Age);
long Salary; printf("\n\tEnter Employee Salary : ");
}; scanf("%ld",&Emp[i].Salary);
void main() }
{ printf("\nDetails of Employees");
int i; for(i=0;i<3;i++)
struct Employee Emp[ 3 ]; printf("\n%d\t%s\t%d\t
for(i=0;i<3;i++) %ld",Emp[i].Id,Emp[i].Name,Emp[i].Age,
{ Emp[i].Salary);
printf("\nEnter details of %d }
Employee",i+1);
printf("\n\tEnter Employee
Id : ");
Structures within Structures
{
<data_type> <variable_name>;
struct <struct_name>
{
<data_type> <variable_name>;
……..
}<struct_variable>;
} <variable_name>;
Structures within Structures Example
struct employee
For Example:-
e1.doj.day;
e1.doj.month;
e1.doj.year;
Accessing Structures within Structures
#include <stdio.h> {
#include <string.h> e1.id=101;
struct Employee strcpy(e1.name, "Sonoo
{ Jaiswal");//copying string into char array
int id; e1.doj.dd=10;
char name[20]; e1.doj.mm=11;
struct Date e1.doj.yyyy=2014;
{ printf( "employee id : %d\n", e1.id);
int dd; printf( "employee name : %s\n",
int mm; e1.name);
int yyyy; printf( "employee date of joining
}doj; (dd/mm/yyyy) : %d/%d/%d\n",
}e1; e1.doj.dd,e1.doj.mm,e1.doj.yyyy);
}
void main( )
Union Data Type
union <union_name>
<data_type> <variable_name>;
<data_type> <variable_name>;
……..
<data_type> <variable_name>;
};
Example of Union
The union of Employee is declared as
union employee
{
int emp_id;
char name[20];
float salary;
char address[50];
int dept_no;
int age;
};
Difference between Structures & Union
61
Pointer Basics
Pointer Definition and syntax
•* symbol is used to get the value of the variable that the pointer is
pointing to.
67
Pointer compatability
Example:
int x=9,*ptr1;
float y=5.55,*ptr2;
char ch='a',*ptr3;
ptr1=&x; // Correct, because ptr1 and x belong to same type of data(int).
ptr2=&x; // Incorrect, because ptr2 and x belong to different types of data.
ptr3=&x; // Incorrect, because ptr3 and x belong to different types of data.
ptr1=&y; // Incorrect, because ptr1 and y belong to different types of data.
ptr2=&y; // Correct, because ptr2 and y belong to same type of data(float).
ptr3=&y; // Incorrect, because ptr3 and y belong to different types of data.
ptr1=&ch; // Incorrect, because ptr1 and ch belong to different types of data.
ptr2=&ch; // Incorrect, because ptr2 and ch belong to different types of data.
ptr3=&ch; // Correct, because ptr3 and ch belong to same type of data(ch).
Pointer Arithmetic
69
Pointer to Pointer
If a pointer holds the address of another pointer then such type of
pointer is known as pointer-to-pointer or double pointer
Syntax:
int **ptr;
70
Pointer to Pointer Example
#include<stdio.h>
void main()
{
int a, *p1, **p2;
a=65;
p1=&a;
p2=&p1;
printf("a = %d\n", a);//65
printf("address of a = %d\n", &a);//5000
printf("p1 = %d\n", p1);//5000
printf("address p1 = %d\n", &p1);//6000
printf("*p1 = %d\n", *p1);//65
printf("p2 = %d\n", p2);//6000
printf("*p2 = %d\n", *p2);//5000
71
printf("**p2 = %d\n", **p2);//65
}
Void pointer
A void pointer points to unknown datatypes.
A void pointer doesnot know to which data it is pointing to.
Void pointer is a specific pointer type – void * – a pointer that points to
some data location in storage, which doesn’t have any specific type.
Program:
#include<stdio.h>
int x;
float y;
char ch;
void *ptr=&x; // void pointer
void main()
{
clrscr();
*(int*)ptr=15; // int* is called as pointer type casting
printf("x:%d\n",x);
ptr=&y;
*(float*)ptr=5.55;
printf("y:%f\n",y);
ptr=&ch;
*(char*)ptr='s';
printf("a:%c",ch);
getch();
}
// (float)--->normal type casting
// (*float)--->pointer type casting
Output:
Pointer to Arrays
• When an array is declared, compiler allocates sufficient amount of
memory to contain all the elements of the array.
• Base address i.e address of the first element of the array is also
allocated by the compiler.
Example:
int x[4];
The program computes the sum of six elements entered by the user.
Example 2: Pointers and Arrays
#include <stdio.h>
int main()
{
int x[5] = {1, 2, 3, 4, 5};
int* ptr;
ptr = &x[2]; // ptr is assigned the address of the third element
printf("*ptr = %d \n", *ptr); // 3
printf("*(ptr+1) = %d \n", *(ptr+1)); // 4
printf("*(ptr-1) = %d", *(ptr-1)); // 2
return 0;
}
Pointers as Function Argument in C
• Pointer as a function parameter is used to hold addresses of
arguments passed during function call. This is also known as call
by reference.
• When a function is called by reference any change made to the
reference variable will effect the original variable.
• The address of num1 and num2 are passed to the swap() function
using swap(&num1, &num2);.
1.malloc()
2.calloc()
3.realloc()
4.free()
malloc()
C malloc()
The name "malloc" stands for memory allocation.
The malloc() function reserves a block of memory of the specified number
of bytes. And, it returns a pointer of void which can be casted into pointers
of any form.
Syntax of malloc()
Example
ptr = (float*) malloc(100 * sizeof(float));
The above statement allocates 400 bytes of memory. It's because the size of
float is 4 bytes. And, the pointer ptr holds the address of the first byte in the
allocated memory.
Syntax of calloc()
ptr = (castType*)calloc(n, size);
Example:
ptr = (float*) calloc(25, sizeof(float));
Syntax of realloc()
C free()
Syntax of free()
free(ptr);
int main()
{
int x = 10, y = 5, area;
area = AREA(x, y);
printf("Area of rectangle is: %d", area);
return 0;
}
Output:
Area of rectangle is: 50
#Ifdef, #Else And #Endif Preprocessors
• “#ifdef” directive checks whether particular macro is defined or not.
If it is defined, “If” clause statements are included in source file.
• Otherwise, “else” clause statements are included in source file for
compilation and execution.
Example:
#include <stdio.h>
#define RAJU 100
int main()
{
#ifdef RAJU
printf("RAJU is defined. So, this line will be added in this C file\n");
#else
printf("RAJU is not defined\n");
#endif
return 0; Output:
RAJU is defined. So, this line will be added in this C file
}
#Ifndef and #Endif Preprocessors
• #ifndef exactly acts as reverse as #ifdef directive. If particular macro
is not defined, “If” clause statements are included in source file.
• Otherwise, else clause statements are included in source file for
compilation and execution.
#include <stdio.h>
#define RAJU 100
int main()
{
#ifndef SELVA
{
printf("SELVA is not defined. So, now we are going to define here\n");
#define SELVA 300
}
#else
printf("SELVA is already defined in the program”);
#endif
return 0;
Output: SELVA is not defined. So, now we are going to
define here
}
#If, #Else and #Endif Preprocessors
•“If” clause statement is included in source file if given condition is true.
•Otherwise, else clause statement is included in source file for compilation
and execution.
Example:
#include <stdio.h>
#define a 100
int main()
{
#if (a==100)
printf("This line will be added in this C file since a = 100\n");
#else
printf("This line will be added in this C file since a is not equal to 100\n");
#endif
return 0;
}
Output: This line will be added in this C file
since a = 100
#Undef Preprocessor
This directive undefines existing macro in the program.
Example:
#include <stdio.h>
#define height 100
void main()
{
printf("First defined value for height : %d\n",height);
#undef height // undefining variable
#define height 600 // redefining the same for new value
printf("value of height after undef & redefine:%d",height);
}
Output:
First defined value for height : 100
value of height after undef & redefine : 600
“Command Line Arguments”
Command Line Arguments
• The arguments passed from command line are called command line
arguments. These arguments are handled by main() function.
• The argument values are passed on to your program during
program execution.
Syntax:
int main(int argc, char *argv[])
Where,
1.argc: It refers to “argument count”. It counts the number of
arguments on the command line.
2. Write a program.
First use cd.. for coming back to Turbo C++ main directory
cd..
cd SOURCE
Command Line Arguments Execution
6. Execute Program with Command Line Arguments
FILES
UNIT – III
Functions: Declaring a function, Parameters and return type
of a function, passing parameters to functions, Recursive
Functions, Storage Classes.
Structures: Defining structures, initializing structures,
unions.
Pointers: Idea of pointers, Defining pointers, Pointer to
Pointer, Dynamic Memory Management functions (DMA)
File Handling in C: Creating and Reading and writing text
and binary files, Appending data to existing files, Writing
and reading structures using binary files, Random access
using fseek, ftell and rewind functions.
111
Files Introduction
A file is a container in computer storage devices used for storing data.
FILE *fptr;
fptr = fopen ("file_name", "Mode");
The fclose() function is used to close a file. The file must be closed after
performing all the operations on it.
Example:
#include <stdio.h>
main()
{
FILE *fp;
fp = fopen("file1.txt", "w");//opening file
fputc('a',fp);//writing single character into file
fclose(fp);//closing file
}
Writing data to a file:fputs() function
The fputs() function writes a line of characters into file. It outputs
string to a stream.
Syntax:
int fputs(const char *s, FILE *stream);
Example:
#include<stdio.h>
#include<conio.h>
void main(){
FILE *fp;
fp=fopen("myfile2.txt","w");
fputs("hello c programming",fp);
fclose(fp);
getch();
}
Writing data to a file:fprintf() function
The fprintf() function is used to write set of characters into file. It
sends formatted output to a stream.
Syntax:
int fprintf(FILE *stream, const char *format [, argument, ...])
Example:
#include <stdio.h>
void main()
{
FILE *fp;
fp = fopen("file.txt", "w");//opening file
fprintf(fp, "Hello file by fprintf...\n");//writing data into file
fclose(fp);//closing file
}
Reading data from a File
There are three different functions dedicated to reading data from a
file:
•fgetc(file_pointer): fgetc() is used to obtain input from a file single
character at a time. This function returns the number of characters
read by the function.
Example:
#include<stdio.h>
void main()
{
FILE *fp;
char text[300];
fp=fopen("myfile2.txt","r");
printf("%s",fgets(text,200,fp));
fclose(fp);
}
Reading data from a File:fscanf()
The fscanf() function is used to read set of characters from file. It reads
a word from the file and returns EOF at the end of file.
Syntax:
int fscanf(FILE *stream, const char *format [, argument, ...])
Example:
#include <stdio.h>
main(){
FILE *fp;
char buff[255];//creating char array to store data of file
fp = fopen("file.txt", "r");
while(fscanf(fp, "%s", buff)!=EOF){
printf("%s ", buff );
}
fclose(fp);
}
Writing and Reading to a binary file
Writing to a binary file:
To write into a binary file, you need to use the fwrite() function. The
functions take four arguments:
• address of data to be written in the disk
• size of data to be written in the disk
• number of such type of data
• pointer to the file where you want to write.
Syntax:
fwrite(addressData, sizeData, numbersData, pointerToFile);
Parameters
stream - This is the pointer to a FILE object that identifies the stream.
offset - This is the number of bytes to offset from whence.
whence - This is the position from where offset is added.
It is specified by one of the following constants.
O/p:
This is C Programming Language
Random Access Functions: ftell()
ftell() function returns the value of the current pointer position in the
file. The value is count from the beginning of the file.
Syntax: ftell(fptr);
Example:
#include<stdio.h>
int main()
{
FILE *fp = fopen("test.txt","r");
char string[20];
fscanf(fp,"%s",string);
/* Printing position of file pointer */
printf("%ld", ftell(fp));
return 0;
}
Random Access Functions: rewind()
rewind() function is used to move the file pointer to the beginning of the
given file.
Syntax: rewind( fptr);
#include<stdio.h>
void main(){
FILE *fp;
char c;
fp=fopen("file.txt","r");
while((c=fgetc(fp))!=EOF){
printf("%c",c);
}
rewind(fp);//moves the file pointer at beginning of the file
while((c=fgetc(fp))!=EOF){
printf("%c",c);
}
fclose(fp);
}
Appending data to existing files
#include<stdio.h> printf("1 file created...\n");
int main() getchar();
{ printf("\nThe contents of file
FILE *p; are..");
char fname[20],ch; rewind(p);
printf("Enter the file name:"); while(1)
scanf("%s",fname); {
p=fopen(fname,"a+"); ch=fgetc(p);
while(1) if(ch==-1)
{ break;
ch=getchar(); printf("%c",ch);
if(ch==-1) }
break; fclose(p);
fputc(ch,p); }
}
“Thank You”
135