The document discusses functions in C programming. It defines functions as sub-programs that perform tasks when called. It describes pre-defined functions like sqrt(), abs(), pow() etc. and user-defined functions. User-defined functions are needed to break programs into modular pieces. Functions provide advantages like facilitating top-down programming and reusability. The document also discusses parameter passing methods like call by value and call by reference, and returning values from functions. Nesting and recursion of functions is explained with examples. Finally, it briefly discusses passing arrays and structures to functions.
It tells about functions in C++,Types,Use,prototype,declaration,Arguments etc
function with
A function with no parameter and no return value
A function with parameter and no return value
A function with parameter and return value
A function without parameter and return value
Call by value and address
Programming Fundamentals Functions in C and typesimtiazalijoono
Programming Fundamentals
Functions in C
Lecture Outline
• Functions
• Function declaration
• Function call
• Function definition
– Passing arguments to function
1) Passing constants
2) Passing variables
– Pass by value
– Returning values from functions
• Preprocessor directives
• Local and external variables
It tells about functions in C++,Types,Use,prototype,declaration,Arguments etc
function with
A function with no parameter and no return value
A function with parameter and no return value
A function with parameter and return value
A function without parameter and return value
Call by value and address
Programming Fundamentals Functions in C and typesimtiazalijoono
Programming Fundamentals
Functions in C
Lecture Outline
• Functions
• Function declaration
• Function call
• Function definition
– Passing arguments to function
1) Passing constants
2) Passing variables
– Pass by value
– Returning values from functions
• Preprocessor directives
• Local and external variables
Water scarcity is the lack of fresh water resources to meet the standard water demand. There are two type of water scarcity. One is physical. The other is economic water scarcity.
Quality defects in TMT Bars, Possible causes and Potential Solutions.PrashantGoswami42
Maintaining high-quality standards in the production of TMT bars is crucial for ensuring structural integrity in construction. Addressing common defects through careful monitoring, standardized processes, and advanced technology can significantly improve the quality of TMT bars. Continuous training and adherence to quality control measures will also play a pivotal role in minimizing these defects.
NO1 Uk best vashikaran specialist in delhi vashikaran baba near me online vas...Amil Baba Dawood bangali
Contact with Dawood Bhai Just call on +92322-6382012 and we'll help you. We'll solve all your problems within 12 to 24 hours and with 101% guarantee and with astrology systematic. If you want to take any personal or professional advice then also you can call us on +92322-6382012 , ONLINE LOVE PROBLEM & Other all types of Daily Life Problem's.Then CALL or WHATSAPP us on +92322-6382012 and Get all these problems solutions here by Amil Baba DAWOOD BANGALI
#vashikaranspecialist #astrologer #palmistry #amliyaat #taweez #manpasandshadi #horoscope #spiritual #lovelife #lovespell #marriagespell#aamilbabainpakistan #amilbabainkarachi #powerfullblackmagicspell #kalajadumantarspecialist #realamilbaba #AmilbabainPakistan #astrologerincanada #astrologerindubai #lovespellsmaster #kalajaduspecialist #lovespellsthatwork #aamilbabainlahore#blackmagicformarriage #aamilbaba #kalajadu #kalailam #taweez #wazifaexpert #jadumantar #vashikaranspecialist #astrologer #palmistry #amliyaat #taweez #manpasandshadi #horoscope #spiritual #lovelife #lovespell #marriagespell#aamilbabainpakistan #amilbabainkarachi #powerfullblackmagicspell #kalajadumantarspecialist #realamilbaba #AmilbabainPakistan #astrologerincanada #astrologerindubai #lovespellsmaster #kalajaduspecialist #lovespellsthatwork #aamilbabainlahore #blackmagicforlove #blackmagicformarriage #aamilbaba #kalajadu #kalailam #taweez #wazifaexpert #jadumantar #vashikaranspecialist #astrologer #palmistry #amliyaat #taweez #manpasandshadi #horoscope #spiritual #lovelife #lovespell #marriagespell#aamilbabainpakistan #amilbabainkarachi #powerfullblackmagicspell #kalajadumantarspecialist #realamilbaba #AmilbabainPakistan #astrologerincanada #astrologerindubai #lovespellsmaster #kalajaduspecialist #lovespellsthatwork #aamilbabainlahore #Amilbabainuk #amilbabainspain #amilbabaindubai #Amilbabainnorway #amilbabainkrachi #amilbabainlahore #amilbabaingujranwalan #amilbabainislamabad
Automobile Management System Project Report.pdfKamal Acharya
The proposed project is developed to manage the automobile in the automobile dealer company. The main module in this project is login, automobile management, customer management, sales, complaints and reports. The first module is the login. The automobile showroom owner should login to the project for usage. The username and password are verified and if it is correct, next form opens. If the username and password are not correct, it shows the error message.
When a customer search for a automobile, if the automobile is available, they will be taken to a page that shows the details of the automobile including automobile name, automobile ID, quantity, price etc. “Automobile Management System” is useful for maintaining automobiles, customers effectively and hence helps for establishing good relation between customer and automobile organization. It contains various customized modules for effectively maintaining automobiles and stock information accurately and safely.
When the automobile is sold to the customer, stock will be reduced automatically. When a new purchase is made, stock will be increased automatically. While selecting automobiles for sale, the proposed software will automatically check for total number of available stock of that particular item, if the total stock of that particular item is less than 5, software will notify the user to purchase the particular item.
Also when the user tries to sale items which are not in stock, the system will prompt the user that the stock is not enough. Customers of this system can search for a automobile; can purchase a automobile easily by selecting fast. On the other hand the stock of automobiles can be maintained perfectly by the automobile shop manager overcoming the drawbacks of existing system.
COLLEGE BUS MANAGEMENT SYSTEM PROJECT REPORT.pdfKamal Acharya
The College Bus Management system is completely developed by Visual Basic .NET Version. The application is connect with most secured database language MS SQL Server. The application is develop by using best combination of front-end and back-end languages. The application is totally design like flat user interface. This flat user interface is more attractive user interface in 2017. The application is gives more important to the system functionality. The application is to manage the student’s details, driver’s details, bus details, bus route details, bus fees details and more. The application has only one unit for admin. The admin can manage the entire application. The admin can login into the application by using username and password of the admin. The application is develop for big and small colleges. It is more user friendly for non-computer person. Even they can easily learn how to manage the application within hours. The application is more secure by the admin. The system will give an effective output for the VB.Net and SQL Server given as input to the system. The compiled java program given as input to the system, after scanning the program will generate different reports. The application generates the report for users. The admin can view and download the report of the data. The application deliver the excel format reports. Because, excel formatted reports is very easy to understand the income and expense of the college bus. This application is mainly develop for windows operating system users. In 2017, 73% of people enterprises are using windows operating system. So the application will easily install for all the windows operating system users. The application-developed size is very low. The application consumes very low space in disk. Therefore, the user can allocate very minimum local disk space for this application.
Vaccine management system project report documentation..pdfKamal Acharya
The Division of Vaccine and Immunization is facing increasing difficulty monitoring vaccines and other commodities distribution once they have been distributed from the national stores. With the introduction of new vaccines, more challenges have been anticipated with this additions posing serious threat to the already over strained vaccine supply chain system in Kenya.
Industrial Training at Shahjalal Fertilizer Company Limited (SFCL)MdTanvirMahtab2
This presentation is about the working procedure of Shahjalal Fertilizer Company Limited (SFCL). A Govt. owned Company of Bangladesh Chemical Industries Corporation under Ministry of Industries.
Democratizing Fuzzing at Scale by Abhishek Aryaabh.arya
Presented at NUS: Fuzzing and Software Security Summer School 2024
This keynote talks about the democratization of fuzzing at scale, highlighting the collaboration between open source communities, academia, and industry to advance the field of fuzzing. It delves into the history of fuzzing, the development of scalable fuzzing platforms, and the empowerment of community-driven research. The talk will further discuss recent advancements leveraging AI/ML and offer insights into the future evolution of the fuzzing landscape.
Forklift Classes Overview by Intella PartsIntella Parts
Discover the different forklift classes and their specific applications. Learn how to choose the right forklift for your needs to ensure safety, efficiency, and compliance in your operations.
For more technical information, visit our website https://intellaparts.com
Student information management system project report ii.pdfKamal Acharya
Our project explains about the student management. This project mainly explains the various actions related to student details. This project shows some ease in adding, editing and deleting the student details. It also provides a less time consuming process for viewing, adding, editing and deleting the marks of the students.
Immunizing Image Classifiers Against Localized Adversary Attacksgerogepatton
This paper addresses the vulnerability of deep learning models, particularly convolutional neural networks
(CNN)s, to adversarial attacks and presents a proactive training technique designed to counter them. We
introduce a novel volumization algorithm, which transforms 2D images into 3D volumetric representations.
When combined with 3D convolution and deep curriculum learning optimization (CLO), itsignificantly improves
the immunity of models against localized universal attacks by up to 40%. We evaluate our proposed approach
using contemporary CNN architectures and the modified Canadian Institute for Advanced Research (CIFAR-10
and CIFAR-100) and ImageNet Large Scale Visual Recognition Challenge (ILSVRC12) datasets, showcasing
accuracy improvements over previous techniques. The results indicate that the combination of the volumetric
input and curriculum learning holds significant promise for mitigating adversarial attacks without necessitating
adversary training.
2. • 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. 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
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
6. 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
7. 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
8. 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
9. 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. 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: Flow control 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 OF C FUNTIONS
function-name(argument list)
argument declaration;
{
local variable declarations;
executable statement1;
executable statement2;
……………….
……………….
return(expression);
}
12
13. 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.
15. 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
16. 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
17. 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
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 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. 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. 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. 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. 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. 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. 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. 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. 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.
30. 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. 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.
33. 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
34. 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. 35
Recursion
It is a 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;
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
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 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
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
43. •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
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
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
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
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
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 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
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).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
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:–
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
56
SCOPE OF A STRUCTURE
Member variables are local to the structure.
Member names are not known outside the structure.
57. •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
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
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 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
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
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
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
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 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
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
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
74. •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
75. 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.
76. 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
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
79. #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
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; }
83. 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