Structure and Union
• Functions is a sub-program that contains one or more
statements and it performs some task when called.
TYPES:
2
FUNCTIONS:
Functions
User-Defined
Functions
Pre-Defined
Functions
3
PRE-DEFINED FUNCTIONS
• The pre-defined functions or library functions are built-
in functions.
• The user can use the functions, but cannot modify the
function.
4
4
sqrt(x):
It is used to find the square root of x
Example: sqrt(36) is 6
abs(x):
It is used to find the absolute value of x
Example: abs(-36) is 36
pow(x,y):
It is used to find the value of xy
Example: pow(5,2) is 25
ceil(x):
It is used to find the smallest integer greater than or
equal to x
Example: ceil(7.7) is 8
USER-DEFINED FUNCTIONS
• Introduction
User-defined function has to be developed by the user
at the time of writing a program.
5
NEED FOR USER-DEFINED FUNCTIONS
• main is a specially recognized function in C.
• Program utilizing only main leads to a number of
problems.
– The program - become too large and complex - result the task
of debugging, testing and maintaining becomes difficult.
• Some operations or calculations are repeated at many
points throughout a program.
6
ADVANTAGES:
• It facilitates top-down modular programming.
• The length of a source program can be reduced by using
functions at appropriate places.
• It is easy to locate and isolate a faulty function for
further investigation.
• A function may be used by many other programs.
7
MULTI-FUNCTION PROGRAM
• A function is a self-contained block of code that
performs a particular task.
• Once a function has been designed and packed, it can
be treated as a ‘block box’ that takes some data from the
main program and returns a value.
8
A function called printline which could print a line of 39-charavter length.
main()
{
printline();
printf(“This illustrates the use of C functions n”);
printline();
}
printline()
{
int i;
for (i=1;i<40;i++)
printf(“-”);
printf(“n”);
}
Output:
-----------------------------------------
This illustrates the use of C functions
-----------------------------------------
9
10
How Function Works
 Once a function is called the control passes to the called
function.
 The working of calling function is temporarily stopped.
 When the execution of called function is completed then
the control returns back to the calling function and
execute the next statement.
Fig 1: Flow control in a multi-function program
main()
{
___________
function1();
___________
function2();
___________
}
function1()
{
___________
}
function2()
{
___________
function3();
}
function3()
{
___________
} 11
Calling Function
Called Function
Called/Calling
Function
Called Function
THE FORM OF C FUNTIONS
function-name(argument list)
argument declaration;
{
local variable declarations;
executable statement1;
executable statement2;
……………….
……………….
return(expression);
}
12
13
Parameters
 Actual Parameter
These are the parameters transferred from the
calling function to the called function.
 Formal Parameter
These are the parameters which is used in the called
function.
14
RETURN VALUES AND THEIR TYPES
• A function sends back any information to the calling
function is called return values.
• It is possible to pass the called function any number of
values, the called function can only return one value per
call.
return;
or
return(expression);
15
RETURN VALUES AND THEIR TYPES
• A return is encountered; the control is immediately
passed back to the calling function.
• return with an expression
mul(x,y)
int x,y;
{
int p;
p = x*y;
return p; or return(x*y)
} 16
A function may have more than one return statement.
if(x<=0)
return(0);
else
return(1);
Function return is called type specifier in the function
header
double product(x,y)
float sqr_root(p)
17
CALLING A FUNCTION
 A function can be called by simply using the function
name in a statement.
Example
main()
{
int p;
p = mul(10,5);
printf(“%dn”, p);
} 18
19
Function Prototypes
A function, depending on whether arguments are
present or not and whether a value is returned or not, may
belong to one of the following categories:
•Function with no arguments and no return values
•Function with arguments and no return values
•Function with arguments and return values
•Function with no arguments and with return values
20
Function with no arguments and no return
values
 Here no data transfer take place between the calling
function and the called function.
 These functions act independently, i.e. they get input
and display output in the same block.
main()
{
___________
function2();
___________
}
function2()
{
___________
___________
___________
}
No
input
No
output
21
#include <stdio.h>
#include<conio.h>
void main()
{
void add(void); //calling function
add();
}
void add() //called function
{
int a,b,c;
printf("nEnter two number:");
scanf("%d%d",&a,&b);
c=a+b;
printf("nSum is:%d",c);
}
Output:
Enter two number:
3
4
Sum is:7
22
Function with arguments and no return
values
 Here data transfer take place between the calling
function and the called function.
 It is a one way data communication, i.e. the called
program receives data from calling program but it does
not return any value to the calling program.
main()
{
___________
function2(a);
___________
}
function2(f)
{
___________
___________
___________
}
Values of
arguments
No return
value
23
#include <stdio.h>
#include<conio.h>
void main()
{
int a,b;
void add(int,int);
printf("nEnter two number:");
scanf("%d%d",&a,&b);
add(a,b);
}
void add(int x,int y) //function with arguments
{
int z;
z=x+y;
printf("nSum is:%d",z);
}
Output:
Enter two number:
2
4
Sum is:6
24
Function with arguments and return
values
 Here data transfer take place between the calling
function and the called function and returns value to
calling function.
 It is a two way data communication, i.e. the called
program receives data from calling program and it
return some value to the calling program.
main()
{
___________
p=function2(a);
___________
}
data_type function2(f)
{
___________
___________
return exp;
}
Values of
arguments
return value
25
#include <stdio.h>
#include<conio.h>
void main()
{
int a,b,c;
int add(int,int);
printf("nEnter two number:");
scanf("%d%d",&a,&b);
c=add(a,b);
printf("nSum is:%d",c);
}
int add(int x,int y)
{
int z;
z=x+y;
return(z);
}
Output:
Enter two number:
6
7
Sum is:13
26
Function with no arguments and with
return values
 Here data transfer take place between the called
function and the calling function.
 It is a one way data communication, i.e. the called
program does not receives data from calling program
but it return some value to the calling program.
main()
{
___________
p=function2();
___________
}
data_type function2()
{
___________
___________
return exp;
}
No
arguments
return value
27
#include <stdio.h>
#include<conio.h>
void main()
{
int add(),d;
d=add();
printf("nSum is:%d",d);
}
int add() //function with no argument
{ int a,b,c;
printf("nEnter two number:");
scanf("%d%d",&a,&b);
c=a+b;
return(c);
}
Output:
Enter two number:
8
5
Sum is:13
28
Parameter Passing Methods
 Call by value
 Call by reference
CALL BY VALUE
 Actual argument passed to the formal argument.
 Any changes to the formal argument does not affect the
actual argument.
CALL BY VALUE
30
#include <stdio.h>
#include<conio.h>
void change(int,int);
void main()
{
int x,y,
printf("nEnter value of x:");
scanf("%d",&x);
printf("nEnter value of y:");
scanf("%d",&y);
change(x,y);
printf("nnValues in the Main()-->x=%d,y=%d",x,y);
}
void change(int a,int b)
{
int c;
c=a; a=b; b=c;
printf("nValues in the Fuction -->x=%d,y=%d",a,b);
}
Output:
Enter value of x:5
Enter value of y:6
Values in the Fuction -->x=6,y=5
Values in the Main()-->x=5,y=6
31
Call by reference
 Instead of passing value, the address of the argument
will be passed.
 Any changes to the formal argument will affect the
actual argument.
CALL BY REFERENCE
33
#include <stdio.h>
#include<conio.h>
void change(int*,int*);
void main()
{
int x,y, printf("nEnter value of x:");
scanf("%d",&x);
printf("nEnter value of y:");
scanf("%d",&y);
change(&x,&y);
printf("nnValues in the Main()-->x=%d,y=%d",x,y);
}
void change(int *a,int *b)
{
int c;
c=*a; *a=*b; *b=c;
printf("nValues in the Function -->x=%d,y=%d",*a,*b);
}
Output:
Enter value of x:5
Enter value of y:6
Values in the Fuction -->x=6,y=5
Values in the Main()-->x=6,y=5
NESTING OF FUNCTIONS
main()
{
int a,b,c;
float ratio();
scanf(“%d%d%d”, &a, &b, &c);
printf(“%fn”, ratio(a,b,c));
}
float ratio(x,y,z)
int x,y,z;
{
if(difference(y,z))
return(x/(y-z));
else
return(0.0);
}
34
difference(p,q)
int p,q;
{
if(p!=q)
return(1);
else
return(0);
}
Nesting of function call is also possible.
Eg: P = mul(mul(5,2),6);
Output:
8 5 3
4
35
Recursion
 It is a process of calling the same function itself again
and again until some condition is satisfied.
 Syntax:
func1()
{
………..
func1();
}
36
#include<stdio.h>
#include<conio.h>
void main()
{
int a;
int rec(int);
printf("nEnter the number:");
scanf("%d",&a);
printf("The factorial of %d! is %d",a,rec(a));
}
int rec(int x)
{
int f;
if(x==1)
return(1);
else
f=x*rec(x-1);
return(f);
}
Output:
Enter the number: 5
The factorial of 5! is 120
37
Example: Working of 3!
1
2
6
In the following 'C' code, in which order the functions would be called
?
1. a = ( f1(23,14 ) * f2 (12/14)) + f3 () ;
A.f1,f2,f3
B.f3,f2,f1
C.The order may vary from compiler to compiler
D.None of these
2 What error would the following function give on
compilation ?
f(int a,int b)
{
int a;
a = 20;
return a;
}
A.Missing parentheses in return statement
B.Function should be define as int f(int a,int b)
C.Redeclaration of a
D.No error
int calculate(int num);
may
int calculate(int num);
may
3. A function that is prototype as
int calculate(int num); may
A.Recieve an integer variable named num from the main
() program
B.Receive any integer variable from the main() program
C.Either (a) or (b)
D.None of these
4. The declaration
void function1(int)
indicates the function1 is a function which
A.Has no arguments
B.Returns nothing
C.Both (a) and (b)
D.None of these
5. The default parameter passing mechanism is
A.call by value
B.call by reference
C.call by value result
D.none of above
6. Use of functions
A.helps to avoid repeating a set of statements many
times
B.enhances the logical clarity of the program
C.helps to avoid repeated prograniming across programs
D.all of the above
7. Pick the correct statements
A.The body of a function should have only one return
statement
B.The body of a function may have many return
statements
C.A function can return only one value to the calling
environment
D.Both (b) & (c)
int calculate(int num);
may
int calculate(int num);
may
8. void can be used
A. as a data-type of a function that returns nothing to its
calling environment
B.inside the brackets of a function that does not need any
argument
C.in an expression
D.both (a) & (b)
9. Any C program
A.must contain at least one function
B.need not contain any function
C.needs input data
D.none of the above
23: The following program
main ()
{ int a = 4;
change { a };
printf ("%d", a);
}
change (a)
int a;
{
printf("%d", ++a);
}
outputs
A.55
B.45
C.54
D.44
11.The following program
main()
{ A.prints 012
inc(); inc(); inc(); B.prints 123
} D.prints 111
inc()
{
static int x;
printf("%d", ++x);
}
12. The following program
main()
{
int abc();
abc ();
( *abc) ();
}
int abc( )
{
printf ("come");
}
A.results in a compilation error
B.prints come come
C.results in a run time
D.prints come come
13. #include‹stdio.h›
int main()
{
struct site
{
char name[] = "GeeksQuiz";
int no_of_pages = 200;
};
struct site *ptr;
printf("%d ", ptr->no_of_pages);
printf("%s", ptr->name);
getchar();
return 0;
}
A 200 GeeksQuiz
B 200
C Runtime Error
D Compiler Error
14. Assume that size of an integer is 32 bit. What is the output
of following program?
#include<stdio.h>
struct st
{
int x;
static int y;
};
int main()
{
printf("%d", sizeof(struct st));
return 0;
}
A 4 B 8 C Compiler Error D Runtime Error
FUNCTION WITH ARRAYS
• To pass an array to a called function, it is sufficient to
list the name of the array, without any subscripts, and
the size of the array as argument.
float largest(array, size);
41
main()
{
float largest();
static float value[4] = {2.5, -4.75, 1.2, 3.67};
printf(“%fn”, largest(value, 4));
}
float largest(a, n)
float a[ ];
int n;
{
int i; float max;
max = a[0];
for(i=1;i<n;i++)
if(max<a[i])
max = a[i];
return(max);
} 42
Output:
3.67
•43
43
STRUCTURE
 A Structure is a collection of different data items, that
are stored under a common name.
Syntax:
struct structure_name
{
structure element1;
structure element2;
…………………….
};
•44
44
 Defines a new type
I.e., a new kind of data type that compiler regards
as a unit
 E.g.,
struct motor {
float volts; //voltage of the motor
float amps; //amperage of the motor
int phases; //# of phases of the motor
float rpm; //rotational speed of motor
}; //struct motor
STRUCTURE
•45
45
 Defines a new type
 E.g.,
struct motor {
float volts;
float amps;
int phases;
float rpm;
}; //struct motor
Note:– name of type is optional if
you are just declaring a single
struct
STRUCTURE
•46
46
STRUCTURE
 Defines a new type
 E.g.,
struct motor {
float volts;
float amps;
int phases;
float rpm;
}; //struct motor
Members of the
struct
•47
47
DECLARING STRUCT VARIABLES
struct motor p, q, r;
Declares and sets aside storage for three variables –
p, q, and r – each of type struct motor
struct motor M[25];
Declares a 25-element array of struct motor;
allocates 25 units of storage, each one big enough
to hold the data of one motor
struct motor *m;
Declares a pointer to an object of type struct
motor
•48
48
INITIALIZING STRUCTURES
struct Rect
{
double x;
double y;
char color;
double width;
double height;
};
struct Rect r1 = {0,0,’r’,5,10};
0
0
r
5.0
10.0
x
y
color
width
height
r1
•49
49
ACCESSING DATA MEMBERS
 To access a data member use
Varname.membername
 struct Rect r1 = {0,0,’r’,5,10};
r1.x
r1.y
r1.color
r1.width
r1.height
0
0
r
5
10
x
y
color
width
height
r1
•50
50
 Let
struct motor p;
struct motor q[10];
 Then
p.volts — is the voltage
p.amps — is the amperage
p.phases — is the number of phases
p.rpm — is the rotational speed
q[i].volts — is the voltage of the ith motor
q[i].rpm — is the speed of the ith motor
ACCESSING DATA MEMBERS
 Let
struct motor *p;
 Then
(*p).volts — is the voltage of the motor pointed
to by p
(*p).phases — is the number of phases of the
motor pointed to by p
•51
51
ACCESSING DATA MEMBERS
•52
52
 The (*p).member notation is a nuisance
Clumsy to type; need to match ( )
Too many keystrokes
 This construct is so widely used that a special notation
was invented, i.e.,
p->member, where p is a pointer to the structure
ACCESSING DATA MEMBERS
•53
53
 Let
struct motor *p;
 Then
p -> volts — is the voltage of the motor pointed
to by p
p -> phases — is the number of phases of the
motor pointed to by p
ACCESSING DATA MEMBERS
•54
54
OPERATIONS ON STRUCT
 Copy/assign
struct motor p, q;
p = q;
 Get address
struct motor p;
struct motor *s
s = &p;
 Access members
p.volts;
s -> amps;
•55
55
 Remember:–
 Passing an argument by value is an instance of
copying or assignment
 Passing a return value from a function to the caller is
an instance of copying or assignment
 E.g,:–
struct motor f(struct motor g) {
struct motor h = g;
...;
return h;
}
OPERATIONS ON STRUCT
•56
56
SCOPE OF A STRUCTURE
 Member variables are local to the structure.
 Member names are not known outside the structure.
•57
57
#include <stdio.h>
struct student{
char name[50];
int roll;
float marks;
};
int main(){
struct student s;
printf("Enter information of students:nn");
printf("Enter name: ");
scanf("%s",s.name);
printf("Enter roll number: ");
scanf("%d",&s.roll);
printf("Enter marks: ");
scanf("%f",&s.marks);
printf("nDisplaying Informationn");
printf("Name: %sn",s.name);
printf("Roll: %dn",s.roll);
printf("Marks: %.2fn",s.marks);
return 0;
}
Enter information of students: Displaying
Information
Enter name: Abcde name:
Abcde
•58
58
 The array of structure is used to store the large number
of similar records.
 For example :- to store the record of 100 employees then
array of structure is used.
 The method to define and access the array element of
array of structure is similar to other array.
Struct<struct_name> <var_name>/<array_name> [<value>];
For Example:-
Struct employee e1[100];
ARRAY OF STRUCTURE
•59
59
#include <stdio.h>
#include <conio.h>
struct employee
{
int emp_id;
char name[20];
float salary;
char address[50];
int dept_no;
int age;
};
•60
60
void main ( )
{
struct employee e1[100];
int i;
for (i=1; i<=100; i++)
{
printf (“Enter the employee id of employee”);
scanf (“%d”,&e[i].emp_id);
printf (“Enter the name of employee”);
scanf (“%s”,e[i].name);
printf (“Enter the salary of employee”);
scanf (“%f”,&e[i].salary);
printf (“Enter the address of employee”);
scanf (“%s”, e[i].address);
printf (“Enter the department of employee”);
scanf (“%d”,&e[i].dept_no);
printf (“Enter the age of employee”);
scanf (“%d”,&e[i].age);
}
•61
61
for (i=1; i<=100; i++)
{
printf (“The employee id of employee is : %d”, e[i].emp_id);
printf (“The name of employee is: %s”,e[i].name);
printf (“The salary of employee is: %f”, e[i].salary);
printf (“The address of employee is : %s”, e[i].address);
printf (“The department of employee is : %d”, e[i].dept_no);
printf (“The age of employee is : %d”, e[i].age);
}
getch();
}
•62
62
to define the structure within structure is
struct <struct_name>{
<data_type> <variable_name>;
struct <struct_name>
{ <data_type>
<variable_name>;
……..}<struct_variable>;
<data_type> <variable_name>;
};
STRUCTURES WITHIN STRUCTURES
•63
63
The structure of Employee is declared as
struct employee
{ int emp_id;
char name[20];
float salary;
int dept_no;
struct date
{ int day;
int month;
int year;
}doj;
};
•64
64
 The data member of structure within structure is
accessed by using two period (.) symbol.
 The syntax to access the structure within structure is
struct _var. nested_struct_var. struct_member;
For Example:-
e1.doj.day;
e1.doj.month;
e1.doj.year;
ACCESSING STRUCTURES WITHIN
STRUCTURES
•65
65
The structure variable can be passed to a function as a
parameter.
The program to pass a structure variable to a function.
#include <stdio.h>
#include <conio.h>
struct employee
{
int emp_id;
char name[20];
float salary;
};
PASSING STRUCTURE TO FUNCTION
•66
66
void main ( )
{
struct employee e1;
printf (“Enter the employee id of employee”);
scanf(“%d”,&e1.emp_id);
printf (“Enter the name of employee”);
scanf(“%s”,e1.name);
printf (“Enter the salary of employee”);
scanf(“%f”,&e1.salary);
printdata (struct employee e1);
getch();
}
void printdata( struct employee emp)
{
printf (“nThe employee id of employee is : %d”, emp.emp_id);
printf (“nThe name of employee is : %s”, emp.name);
printf (“nThe salary of employee is : %f”,emp.salary);
}
•67
67
 A union is a user defined data type like structure.
 The union groups logically related variables into a
single unit.
 The union data type allocate the space equal to space
need to hold the largest data member of union.
 The union allows different types of variable to share
same space in memory.
 There is no other difference between structure and union
than internal difference.
 The method to declare, use and access the union is same
as structure.
UNION DATA TYPE
•68
68
A union has to defined, before it can used. The syntax of
defining a structure is
union <union_name>
{
<data_type> <variable_name>;
<data_type> <variable_name>;
……..
<data_type> <variable_name>;
};
DEFINING OF UNION
•69
69
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;
};
EXAMPLE OF UNION
•70
70
Memory Space Allocation
8000
emp_id, dept_no, age
8002
salary
8004
name
8022
address
8050
employee
•74
74
1) The memory occupied by structure variable is the
sum of sizes of all the members but memory occupied
by union variable is equal to space hold by the largest
data member of a union.
2) In the structure all the members are accessed at any
point of time but in union only one of union member
can be accessed at any given time.
DIFFERENCE BETWEEN STRUCTURES
& UNION
Five major operations can be performed on
file are:
Creation of a new file.
Opening an existing file.
Reading data from a file.
Writing data in a file.
Closing a file.
fopen Opens a file.
fclose Closes a file.
getc Reads a character from a file
putc Writes a character to a file
getw Read integer
putw Write an integer
fprintf Prints formatted output to a file
fscanf Reads formatted input from a file
fgets Read string of characters from a
file
fputs Write string of characters to file
feof Detects end-of-file marker in a file
#include <stdio.h>
main()
{
FILE *fp;
fp = fopen("/tmp/test.txt", "w+");
fprintf(fp, "This is testing for fprintf...n");
fputs("This is testing for fputs...n", fp);
fclose(fp); }
Creating & Writing a File
Reading a File
#include <stdio.h>
main()
{
FILE *fp;
char buff[255];
fp = fopen("/tmp/test.txt", "r");
fscanf(fp, "%s", buff);
printf("1 : %sn", buff );
fgets(buff, 255, (FILE*)fp);
printf("2: %sn", buff );
fgets(buff, 255, (FILE*)fp);
printf("3: %sn", buff );
fclose(fp);
}
#include <stdio.h>
#include <stdlib.h>
int main ()
{
FILE * fp;
fp = fopen ("file.txt", "w+“);
fprintf(fp, "%s %s %s %d", "We", "are", "in", 2012);
fclose(fp);
return(0);
}
Output
We are in 2012
#include <stdio.h>
int main()
{
FILE *fp1, *fp2;
char filename[40];
char c; int del_line, temp = 1;
printf("Enter file name: ");
scanf("%s", filename);
fp1 = fopen(filename, "r");
c = getc(fp1);
while (c != EOF)
{
printf("%c", c);
c = getc(fp1);
}
rewind(fp1);
printf(" n Enter line number of the line to be deleted:");
scanf("%d", &del_line);
//open new file in write mode
fp2 = fopen("copy.c", "w");
c = getc(fp1);
while (c != EOF)
{
c = getc(fp1); if (c == 'n') temp++;
//except the line to be deleted
if (temp != del_line)
{
putc(c, fp2);
}
}
fclose(fp1);
fclose(fp2);
//remove original file
remove(filename);
//rename the file copy.c to original name
rename("copy.c", filename);
printf("n The contents of file after being modified are as follows:n");
fp1 = fopen(filename, "r");
c = getc(fp1);
while (c != EOF)
{
printf("%c", c);
c = getc(fp1);
}
fclose(fp1);
return 0; }
Enter file name:abc.txt
There are 4 lines in abc.txt
1.Which of the following true about FILE *fp
(A) FILE is a keyword in C for representing files and fp is a variable of
FILE type.
(B) FILE is a structure and fp is a pointer to the structure of FILE type
(C) FILE is a stream
(D) FILE is a buffered stream
2. When fopen() is not able to open a file, it returns
(A) EOF
(B) NULL
(C) Runtime Error
(D) Compiler Dependent
3. getc() returns EOF when
A. End of files is reached
B B. When getc() fails to read a character
C. Both of the above
D D. None of the above

eee2-day4-structures engineering college

  • 1.
  • 2.
    • Functions isa sub-program that contains one or more statements and it performs some task when called. TYPES: 2 FUNCTIONS: Functions User-Defined Functions Pre-Defined Functions
  • 3.
    3 PRE-DEFINED FUNCTIONS • Thepre-defined functions or library functions are built- in functions. • The user can use the functions, but cannot modify the function.
  • 4.
    4 4 sqrt(x): It is usedto find the square root of x Example: sqrt(36) is 6 abs(x): It is used to find the absolute value of x Example: abs(-36) is 36 pow(x,y): It is used to find the value of xy Example: pow(5,2) is 25 ceil(x): It is used to find the smallest integer greater than or equal to x Example: ceil(7.7) is 8
  • 5.
    USER-DEFINED FUNCTIONS • Introduction User-definedfunction has to be developed by the user at the time of writing a program. 5
  • 6.
    NEED FOR USER-DEFINEDFUNCTIONS • main is a specially recognized function in C. • Program utilizing only main leads to a number of problems. – The program - become too large and complex - result the task of debugging, testing and maintaining becomes difficult. • Some operations or calculations are repeated at many points throughout a program. 6
  • 7.
    ADVANTAGES: • It facilitatestop-down modular programming. • The length of a source program can be reduced by using functions at appropriate places. • It is easy to locate and isolate a faulty function for further investigation. • A function may be used by many other programs. 7
  • 8.
    MULTI-FUNCTION PROGRAM • Afunction is a self-contained block of code that performs a particular task. • Once a function has been designed and packed, it can be treated as a ‘block box’ that takes some data from the main program and returns a value. 8
  • 9.
    A function calledprintline which could print a line of 39-charavter length. main() { printline(); printf(“This illustrates the use of C functions n”); printline(); } printline() { int i; for (i=1;i<40;i++) printf(“-”); printf(“n”); } Output: ----------------------------------------- This illustrates the use of C functions ----------------------------------------- 9
  • 10.
    10 How Function Works Once a function is called the control passes to the called function.  The working of calling function is temporarily stopped.  When the execution of called function is completed then the control returns back to the calling function and execute the next statement.
  • 11.
    Fig 1: Flowcontrol in a multi-function program main() { ___________ function1(); ___________ function2(); ___________ } function1() { ___________ } function2() { ___________ function3(); } function3() { ___________ } 11 Calling Function Called Function Called/Calling Function Called Function
  • 12.
    THE FORM OFC FUNTIONS function-name(argument list) argument declaration; { local variable declarations; executable statement1; executable statement2; ………………. ………………. return(expression); } 12
  • 13.
    13 Parameters  Actual Parameter Theseare the parameters transferred from the calling function to the called function.  Formal Parameter These are the parameters which is used in the called function.
  • 14.
  • 15.
    RETURN VALUES ANDTHEIR TYPES • A function sends back any information to the calling function is called return values. • It is possible to pass the called function any number of values, the called function can only return one value per call. return; or return(expression); 15
  • 16.
    RETURN VALUES ANDTHEIR TYPES • A return is encountered; the control is immediately passed back to the calling function. • return with an expression mul(x,y) int x,y; { int p; p = x*y; return p; or return(x*y) } 16
  • 17.
    A function mayhave more than one return statement. if(x<=0) return(0); else return(1); Function return is called type specifier in the function header double product(x,y) float sqr_root(p) 17
  • 18.
    CALLING A FUNCTION A function can be called by simply using the function name in a statement. Example main() { int p; p = mul(10,5); printf(“%dn”, p); } 18
  • 19.
    19 Function Prototypes A function,depending on whether arguments are present or not and whether a value is returned or not, may belong to one of the following categories: •Function with no arguments and no return values •Function with arguments and no return values •Function with arguments and return values •Function with no arguments and with return values
  • 20.
    20 Function with noarguments and no return values  Here no data transfer take place between the calling function and the called function.  These functions act independently, i.e. they get input and display output in the same block. main() { ___________ function2(); ___________ } function2() { ___________ ___________ ___________ } No input No output
  • 21.
    21 #include <stdio.h> #include<conio.h> void main() { voidadd(void); //calling function add(); } void add() //called function { int a,b,c; printf("nEnter two number:"); scanf("%d%d",&a,&b); c=a+b; printf("nSum is:%d",c); } Output: Enter two number: 3 4 Sum is:7
  • 22.
    22 Function with argumentsand no return values  Here data transfer take place between the calling function and the called function.  It is a one way data communication, i.e. the called program receives data from calling program but it does not return any value to the calling program. main() { ___________ function2(a); ___________ } function2(f) { ___________ ___________ ___________ } Values of arguments No return value
  • 23.
    23 #include <stdio.h> #include<conio.h> void main() { inta,b; void add(int,int); printf("nEnter two number:"); scanf("%d%d",&a,&b); add(a,b); } void add(int x,int y) //function with arguments { int z; z=x+y; printf("nSum is:%d",z); } Output: Enter two number: 2 4 Sum is:6
  • 24.
    24 Function with argumentsand return values  Here data transfer take place between the calling function and the called function and returns value to calling function.  It is a two way data communication, i.e. the called program receives data from calling program and it return some value to the calling program. main() { ___________ p=function2(a); ___________ } data_type function2(f) { ___________ ___________ return exp; } Values of arguments return value
  • 25.
    25 #include <stdio.h> #include<conio.h> void main() { inta,b,c; int add(int,int); printf("nEnter two number:"); scanf("%d%d",&a,&b); c=add(a,b); printf("nSum is:%d",c); } int add(int x,int y) { int z; z=x+y; return(z); } Output: Enter two number: 6 7 Sum is:13
  • 26.
    26 Function with noarguments and with return values  Here data transfer take place between the called function and the calling function.  It is a one way data communication, i.e. the called program does not receives data from calling program but it return some value to the calling program. main() { ___________ p=function2(); ___________ } data_type function2() { ___________ ___________ return exp; } No arguments return value
  • 27.
    27 #include <stdio.h> #include<conio.h> void main() { intadd(),d; d=add(); printf("nSum is:%d",d); } int add() //function with no argument { int a,b,c; printf("nEnter two number:"); scanf("%d%d",&a,&b); c=a+b; return(c); } Output: Enter two number: 8 5 Sum is:13
  • 28.
    28 Parameter Passing Methods Call by value  Call by reference CALL BY VALUE  Actual argument passed to the formal argument.  Any changes to the formal argument does not affect the actual argument.
  • 29.
  • 30.
    30 #include <stdio.h> #include<conio.h> void change(int,int); voidmain() { int x,y, printf("nEnter value of x:"); scanf("%d",&x); printf("nEnter value of y:"); scanf("%d",&y); change(x,y); printf("nnValues in the Main()-->x=%d,y=%d",x,y); } void change(int a,int b) { int c; c=a; a=b; b=c; printf("nValues in the Fuction -->x=%d,y=%d",a,b); } Output: Enter value of x:5 Enter value of y:6 Values in the Fuction -->x=6,y=5 Values in the Main()-->x=5,y=6
  • 31.
    31 Call by reference Instead of passing value, the address of the argument will be passed.  Any changes to the formal argument will affect the actual argument.
  • 32.
  • 33.
    33 #include <stdio.h> #include<conio.h> void change(int*,int*); voidmain() { int x,y, printf("nEnter value of x:"); scanf("%d",&x); printf("nEnter value of y:"); scanf("%d",&y); change(&x,&y); printf("nnValues in the Main()-->x=%d,y=%d",x,y); } void change(int *a,int *b) { int c; c=*a; *a=*b; *b=c; printf("nValues in the Function -->x=%d,y=%d",*a,*b); } Output: Enter value of x:5 Enter value of y:6 Values in the Fuction -->x=6,y=5 Values in the Main()-->x=6,y=5
  • 34.
    NESTING OF FUNCTIONS main() { inta,b,c; float ratio(); scanf(“%d%d%d”, &a, &b, &c); printf(“%fn”, ratio(a,b,c)); } float ratio(x,y,z) int x,y,z; { if(difference(y,z)) return(x/(y-z)); else return(0.0); } 34 difference(p,q) int p,q; { if(p!=q) return(1); else return(0); } Nesting of function call is also possible. Eg: P = mul(mul(5,2),6); Output: 8 5 3 4
  • 35.
    35 Recursion  It isa process of calling the same function itself again and again until some condition is satisfied.  Syntax: func1() { ……….. func1(); }
  • 36.
    36 #include<stdio.h> #include<conio.h> void main() { int a; intrec(int); printf("nEnter the number:"); scanf("%d",&a); printf("The factorial of %d! is %d",a,rec(a)); } int rec(int x) { int f; if(x==1) return(1); else f=x*rec(x-1); return(f); } Output: Enter the number: 5 The factorial of 5! is 120
  • 37.
  • 38.
    In the following'C' code, in which order the functions would be called ? 1. a = ( f1(23,14 ) * f2 (12/14)) + f3 () ; A.f1,f2,f3 B.f3,f2,f1 C.The order may vary from compiler to compiler D.None of these 2 What error would the following function give on compilation ? f(int a,int b) { int a; a = 20; return a; } A.Missing parentheses in return statement B.Function should be define as int f(int a,int b) C.Redeclaration of a D.No error int calculate(int num); may int calculate(int num); may 3. A function that is prototype as int calculate(int num); may A.Recieve an integer variable named num from the main () program B.Receive any integer variable from the main() program C.Either (a) or (b) D.None of these 4. The declaration void function1(int) indicates the function1 is a function which A.Has no arguments B.Returns nothing C.Both (a) and (b) D.None of these
  • 39.
    5. The defaultparameter passing mechanism is A.call by value B.call by reference C.call by value result D.none of above 6. Use of functions A.helps to avoid repeating a set of statements many times B.enhances the logical clarity of the program C.helps to avoid repeated prograniming across programs D.all of the above 7. Pick the correct statements A.The body of a function should have only one return statement B.The body of a function may have many return statements C.A function can return only one value to the calling environment D.Both (b) & (c) int calculate(int num); may int calculate(int num); may 8. void can be used A. as a data-type of a function that returns nothing to its calling environment B.inside the brackets of a function that does not need any argument C.in an expression D.both (a) & (b) 9. Any C program A.must contain at least one function B.need not contain any function C.needs input data D.none of the above 23: The following program main () { int a = 4; change { a }; printf ("%d", a); } change (a) int a; { printf("%d", ++a); } outputs A.55 B.45 C.54 D.44
  • 40.
    11.The following program main() {A.prints 012 inc(); inc(); inc(); B.prints 123 } D.prints 111 inc() { static int x; printf("%d", ++x); } 12. The following program main() { int abc(); abc (); ( *abc) (); } int abc( ) { printf ("come"); } A.results in a compilation error B.prints come come C.results in a run time D.prints come come 13. #include‹stdio.h› int main() { struct site { char name[] = "GeeksQuiz"; int no_of_pages = 200; }; struct site *ptr; printf("%d ", ptr->no_of_pages); printf("%s", ptr->name); getchar(); return 0; } A 200 GeeksQuiz B 200 C Runtime Error D Compiler Error 14. Assume that size of an integer is 32 bit. What is the output of following program? #include<stdio.h> struct st { int x; static int y; }; int main() { printf("%d", sizeof(struct st)); return 0; } A 4 B 8 C Compiler Error D Runtime Error
  • 41.
    FUNCTION WITH ARRAYS •To pass an array to a called function, it is sufficient to list the name of the array, without any subscripts, and the size of the array as argument. float largest(array, size); 41
  • 42.
    main() { float largest(); static floatvalue[4] = {2.5, -4.75, 1.2, 3.67}; printf(“%fn”, largest(value, 4)); } float largest(a, n) float a[ ]; int n; { int i; float max; max = a[0]; for(i=1;i<n;i++) if(max<a[i]) max = a[i]; return(max); } 42 Output: 3.67
  • 43.
    •43 43 STRUCTURE  A Structureis a collection of different data items, that are stored under a common name. Syntax: struct structure_name { structure element1; structure element2; ……………………. };
  • 44.
    •44 44  Defines anew type I.e., a new kind of data type that compiler regards as a unit  E.g., struct motor { float volts; //voltage of the motor float amps; //amperage of the motor int phases; //# of phases of the motor float rpm; //rotational speed of motor }; //struct motor STRUCTURE
  • 45.
    •45 45  Defines anew type  E.g., struct motor { float volts; float amps; int phases; float rpm; }; //struct motor Note:– name of type is optional if you are just declaring a single struct STRUCTURE
  • 46.
    •46 46 STRUCTURE  Defines anew type  E.g., struct motor { float volts; float amps; int phases; float rpm; }; //struct motor Members of the struct
  • 47.
    •47 47 DECLARING STRUCT VARIABLES structmotor p, q, r; Declares and sets aside storage for three variables – p, q, and r – each of type struct motor struct motor M[25]; Declares a 25-element array of struct motor; allocates 25 units of storage, each one big enough to hold the data of one motor struct motor *m; Declares a pointer to an object of type struct motor
  • 48.
    •48 48 INITIALIZING STRUCTURES struct Rect { doublex; double y; char color; double width; double height; }; struct Rect r1 = {0,0,’r’,5,10}; 0 0 r 5.0 10.0 x y color width height r1
  • 49.
    •49 49 ACCESSING DATA MEMBERS To access a data member use Varname.membername  struct Rect r1 = {0,0,’r’,5,10}; r1.x r1.y r1.color r1.width r1.height 0 0 r 5 10 x y color width height r1
  • 50.
    •50 50  Let struct motorp; struct motor q[10];  Then p.volts — is the voltage p.amps — is the amperage p.phases — is the number of phases p.rpm — is the rotational speed q[i].volts — is the voltage of the ith motor q[i].rpm — is the speed of the ith motor ACCESSING DATA MEMBERS
  • 51.
     Let struct motor*p;  Then (*p).volts — is the voltage of the motor pointed to by p (*p).phases — is the number of phases of the motor pointed to by p •51 51 ACCESSING DATA MEMBERS
  • 52.
    •52 52  The (*p).membernotation is a nuisance Clumsy to type; need to match ( ) Too many keystrokes  This construct is so widely used that a special notation was invented, i.e., p->member, where p is a pointer to the structure ACCESSING DATA MEMBERS
  • 53.
    •53 53  Let struct motor*p;  Then p -> volts — is the voltage of the motor pointed to by p p -> phases — is the number of phases of the motor pointed to by p ACCESSING DATA MEMBERS
  • 54.
    •54 54 OPERATIONS ON STRUCT Copy/assign struct motor p, q; p = q;  Get address struct motor p; struct motor *s s = &p;  Access members p.volts; s -> amps;
  • 55.
    •55 55  Remember:–  Passingan argument by value is an instance of copying or assignment  Passing a return value from a function to the caller is an instance of copying or assignment  E.g,:– struct motor f(struct motor g) { struct motor h = g; ...; return h; } OPERATIONS ON STRUCT
  • 56.
    •56 56 SCOPE OF ASTRUCTURE  Member variables are local to the structure.  Member names are not known outside the structure.
  • 57.
    •57 57 #include <stdio.h> struct student{ charname[50]; int roll; float marks; }; int main(){ struct student s; printf("Enter information of students:nn"); printf("Enter name: "); scanf("%s",s.name); printf("Enter roll number: "); scanf("%d",&s.roll); printf("Enter marks: "); scanf("%f",&s.marks); printf("nDisplaying Informationn"); printf("Name: %sn",s.name); printf("Roll: %dn",s.roll); printf("Marks: %.2fn",s.marks); return 0; } Enter information of students: Displaying Information Enter name: Abcde name: Abcde
  • 58.
    •58 58  The arrayof structure is used to store the large number of similar records.  For example :- to store the record of 100 employees then array of structure is used.  The method to define and access the array element of array of structure is similar to other array. Struct<struct_name> <var_name>/<array_name> [<value>]; For Example:- Struct employee e1[100]; ARRAY OF STRUCTURE
  • 59.
    •59 59 #include <stdio.h> #include <conio.h> structemployee { int emp_id; char name[20]; float salary; char address[50]; int dept_no; int age; };
  • 60.
    •60 60 void main () { struct employee e1[100]; int i; for (i=1; i<=100; i++) { printf (“Enter the employee id of employee”); scanf (“%d”,&e[i].emp_id); printf (“Enter the name of employee”); scanf (“%s”,e[i].name); printf (“Enter the salary of employee”); scanf (“%f”,&e[i].salary); printf (“Enter the address of employee”); scanf (“%s”, e[i].address); printf (“Enter the department of employee”); scanf (“%d”,&e[i].dept_no); printf (“Enter the age of employee”); scanf (“%d”,&e[i].age); }
  • 61.
    •61 61 for (i=1; i<=100;i++) { printf (“The employee id of employee is : %d”, e[i].emp_id); printf (“The name of employee is: %s”,e[i].name); printf (“The salary of employee is: %f”, e[i].salary); printf (“The address of employee is : %s”, e[i].address); printf (“The department of employee is : %d”, e[i].dept_no); printf (“The age of employee is : %d”, e[i].age); } getch(); }
  • 62.
    •62 62 to define thestructure within structure is struct <struct_name>{ <data_type> <variable_name>; struct <struct_name> { <data_type> <variable_name>; ……..}<struct_variable>; <data_type> <variable_name>; }; STRUCTURES WITHIN STRUCTURES
  • 63.
    •63 63 The structure ofEmployee is declared as struct employee { int emp_id; char name[20]; float salary; int dept_no; struct date { int day; int month; int year; }doj; };
  • 64.
    •64 64  The datamember of structure within structure is accessed by using two period (.) symbol.  The syntax to access the structure within structure is struct _var. nested_struct_var. struct_member; For Example:- e1.doj.day; e1.doj.month; e1.doj.year; ACCESSING STRUCTURES WITHIN STRUCTURES
  • 65.
    •65 65 The structure variablecan be passed to a function as a parameter. The program to pass a structure variable to a function. #include <stdio.h> #include <conio.h> struct employee { int emp_id; char name[20]; float salary; }; PASSING STRUCTURE TO FUNCTION
  • 66.
    •66 66 void main () { struct employee e1; printf (“Enter the employee id of employee”); scanf(“%d”,&e1.emp_id); printf (“Enter the name of employee”); scanf(“%s”,e1.name); printf (“Enter the salary of employee”); scanf(“%f”,&e1.salary); printdata (struct employee e1); getch(); } void printdata( struct employee emp) { printf (“nThe employee id of employee is : %d”, emp.emp_id); printf (“nThe name of employee is : %s”, emp.name); printf (“nThe salary of employee is : %f”,emp.salary); }
  • 67.
    •67 67  A unionis a user defined data type like structure.  The union groups logically related variables into a single unit.  The union data type allocate the space equal to space need to hold the largest data member of union.  The union allows different types of variable to share same space in memory.  There is no other difference between structure and union than internal difference.  The method to declare, use and access the union is same as structure. UNION DATA TYPE
  • 68.
    •68 68 A union hasto defined, before it can used. The syntax of defining a structure is union <union_name> { <data_type> <variable_name>; <data_type> <variable_name>; …….. <data_type> <variable_name>; }; DEFINING OF UNION
  • 69.
    •69 69 The union ofEmployee is declared as union employee { int emp_id; char name[20]; float salary; char address[50]; int dept_no; int age; }; EXAMPLE OF UNION
  • 70.
    •70 70 Memory Space Allocation 8000 emp_id,dept_no, age 8002 salary 8004 name 8022 address 8050 employee
  • 74.
    •74 74 1) The memoryoccupied by structure variable is the sum of sizes of all the members but memory occupied by union variable is equal to space hold by the largest data member of a union. 2) In the structure all the members are accessed at any point of time but in union only one of union member can be accessed at any given time. DIFFERENCE BETWEEN STRUCTURES & UNION
  • 75.
    Five major operationscan be performed on file are: Creation of a new file. Opening an existing file. Reading data from a file. Writing data in a file. Closing a file.
  • 76.
    fopen Opens afile. fclose Closes a file. getc Reads a character from a file putc Writes a character to a file getw Read integer putw Write an integer fprintf Prints formatted output to a file fscanf Reads formatted input from a file fgets Read string of characters from a file fputs Write string of characters to file feof Detects end-of-file marker in a file
  • 77.
    #include <stdio.h> main() { FILE *fp; fp= fopen("/tmp/test.txt", "w+"); fprintf(fp, "This is testing for fprintf...n"); fputs("This is testing for fputs...n", fp); fclose(fp); } Creating & Writing a File
  • 78.
    Reading a File #include<stdio.h> main() { FILE *fp; char buff[255]; fp = fopen("/tmp/test.txt", "r"); fscanf(fp, "%s", buff); printf("1 : %sn", buff ); fgets(buff, 255, (FILE*)fp); printf("2: %sn", buff ); fgets(buff, 255, (FILE*)fp); printf("3: %sn", buff ); fclose(fp); }
  • 79.
    #include <stdio.h> #include <stdlib.h> intmain () { FILE * fp; fp = fopen ("file.txt", "w+“); fprintf(fp, "%s %s %s %d", "We", "are", "in", 2012); fclose(fp); return(0); } Output We are in 2012
  • 80.
    #include <stdio.h> int main() { FILE*fp1, *fp2; char filename[40]; char c; int del_line, temp = 1; printf("Enter file name: "); scanf("%s", filename); fp1 = fopen(filename, "r"); c = getc(fp1); while (c != EOF) { printf("%c", c); c = getc(fp1); } rewind(fp1); printf(" n Enter line number of the line to be deleted:"); scanf("%d", &del_line); //open new file in write mode fp2 = fopen("copy.c", "w"); c = getc(fp1); while (c != EOF) { c = getc(fp1); if (c == 'n') temp++; //except the line to be deleted if (temp != del_line) { putc(c, fp2); } } fclose(fp1); fclose(fp2); //remove original file remove(filename); //rename the file copy.c to original name rename("copy.c", filename); printf("n The contents of file after being modified are as follows:n"); fp1 = fopen(filename, "r"); c = getc(fp1); while (c != EOF) { printf("%c", c); c = getc(fp1); } fclose(fp1); return 0; }
  • 82.
    Enter file name:abc.txt Thereare 4 lines in abc.txt
  • 83.
    1.Which of thefollowing true about FILE *fp (A) FILE is a keyword in C for representing files and fp is a variable of FILE type. (B) FILE is a structure and fp is a pointer to the structure of FILE type (C) FILE is a stream (D) FILE is a buffered stream 2. When fopen() is not able to open a file, it returns (A) EOF (B) NULL (C) Runtime Error (D) Compiler Dependent 3. getc() returns EOF when A. End of files is reached B B. When getc() fails to read a character C. Both of the above D D. None of the above