CHAPTER –7
Function
A self-contained program segment or a sub-routine that carries out a specific well-defined task and
has a single exit is known as function. In simple words function is a pre-defined routine to perform
a particular operation. A function is a collection of code, which is executed when the function is
called.
Advantages
1. It is easy to understand.
2. It avoids the repetition of the same set of codes again and again.
3. It makes the program easier to debug.
4. Program containing functions are also easier to maintain.
Types of function
In “C” function can be divided into two types
1. System defined function. Or library function.
2. User defined function (UDF)
System defined function
These are the commonly required functions, which is already defined or written inside the “c”.
Example : printf( )
scanf( )
gets( )
User defined function
The functions, which are created by the user to perform frequently used operation, are known as
user-defined function. A user-defined function is generally associated with the following two things-
1. Invocation of a function
2. Definition of a function
Function Invocation
Function invocation means to call the function to carry out its task. It is called by specifying its
name. Function invocation generally present in main( ) but it may be present in another UDF.
(The function, which calls another function is known as calling function and the function which is
called is known as called function.) There may be more than one function invocation in a calling
function. One function returns only one value to its calling function.
Example : main ( ) calling function
{
hello ( ); function invocation
}
hello ( ) called function
{
printf (“\n Hello friends”);
}
Function definition
Function definition
Function definition means the actual representation of a function that carries out a specific
operation.
Syntax : < function name> (< list of parameters >)
{
< Statement >;
}
A user-defined function may be
1) A function not returning values
2) A function accepting values
3) A function returning values
Function not returning values
171. fname1.c
WAP to define a function print your name, age and roll number.
172. fsum1.c
WAP to define a function, which accepts two number from user and displays its sum and
product.
173. frarea1.c
WAP to define two different functions which display the area and perimeter of a
rectangle whose length and breadth is entered by the user.
174. fsumno1.c
WAP to define a function to find out the sum of the all numbers form m to n where the
value of m and n is entered by the user.
175. WAP to define a function, which displays the numbers from 1 to n where n is entered by
the user.
Function accepting the values
When the function is called by passing parameter (values or variables) then it should be collected
in the function definition to enable the function to operate on these. To pass the parameter to the
called functions the list of parameters should be specified inside the parentheses of function
invocation. These parameters are called the actual parameter or actual argument.
The parameters passed from the calling function should be collected in the parentheses of the
called function by using n number of dummy variables called formal parameter or formal
arguments.The number, type and sequence of the formal parameter should be exact to the actual
parameter.
Example :main ( )
{
int x,y;
printf (“\n enter a no.”);
scanf (“ %d”, & x);
printf (“\n enter 2nd no”);
add (x, y);
Actual parameter or Actual argument
}
add (int a,int b )
{
Formal parameter or Formal Arguments
Int z;
z=a+b;
printf ( “\n sum =%d”,z);
}
176. farea1.c
WAP to enter radius of the circle. Define a function to display the area and
circumference.
177. ffact1.c
WAP to enter a number. Define a function to display the factorial of each digit.
178. fstring1.c
WAP to enter a string and a number n. Define a function to display the string n
number of times.
179. fprime1.c
WAP to enter two numbers . Define a function to display the prime number in
between the numbers.
180. farms1.c
WAP to enter a number. Define a function to check whether it is a Armstrong number
or not.
181. fspecial.c
WAP to enter a number. Define a function to check whether it is special number or
not.
Function returning values
When the program control finds the closing curly brackets at the end of the function then it
returns to the calling function. In this case the function doesn’t return any value to its calling
function, but a function can be made to return a value to its calling function. The value returned
by the called function should be collected in the calling function by using equal sign or passing
it to the printf ( ). A function can return only one value at a time.
return( )
It is used to transfer the program execution control from the called function to the calling function. It
can also return a value to the calling function. Generally return is the last statement of a function
definition because any statement after the return function is never executed. return( ) can be
used to return the following.
1) Control Ex- return
2) Constant Ex- return (32);
3) Variable Ex- return(a);
4) Expression Ex- return (x*y +2);
182. frarea2.c
WAP to enter the length and breadth of a rectangle. Define a function to calculate it’s
area print the area in the main().
183. fsumno2.c
WAP to enter a number. Define two functions to calculate its factorials and cube.
Display the sum and average of the factorial and cube of the number.
184. fstring2.c
WAP to enter a string. Define a function to calculate it’s length. In the main() print the
string by number of times equal to the length of the string.
Variables
Variable is the memory location where data is stored. Its value may change during the execution of
program.Generally variables are of following three types.
1) Local variable
2) Formal parameter
3) Global variable
Local variable
Local variables are those variables, which can be used by the statements that is written inside the
code block which declares it. These are created with each entry and destroyed with each exit from
the block in which they are declared. Their contents are lost once the block is left.
Example : add ( )
{
int x, y, z =0;
x=2;
y=3;
z=x+y;
printf (“\n sum = %d”, z);
}
Formal parameter
The variables, which are declared in a function to accept the values or arguments passed by the
calling function, is known as formal parameter. These variables behave like a local variable but are
declared inside the parentheses of a function. After the declaration these variables can be used
inside the function like normal local variables and are destroyed in each exit from the function.
Example : rarea (int l, int b)
{
int a;
a=l*b;
printf (“ \n Area=%d”, a);
}
Global variable
Global variable are those variables, which is available to all the statements in a program. Global
variables are generally declared outside any function of a program and hold their value through out
the program execution. Global variables can be declared anywhere in the program but before its
use, but it is better to declare it at the top of the program.
Example : int ctr ; /* ctr is the global variable */
main( )
{
int z;
ctr=3;
if(ctr>90)
{
z=45;
}
}
ctr( )
{
int x=45;
if (x>25)
{
ctr=100;
}
}
Storage class
Storage class is that which decides the followings of a variable.
i. Scope of the variable. It means where the variable is available with in the program.
ii. Location of the variable
(RAM or CPU register)
iii. Initial value or default value
iv. Life of the variable
In “C” there are four types of storage class.
a. Automatic
b. Extern
c. Static
d. Register
Automatic
It is the default storage class
1. Creation : memory (RAM)
2. Scope : local to the block in which the variable is declared.
3. Default value :garbage
4. Life : As long as the control is within the block.
5. Keyword : auto
Example : auto int x;
int x;
Output1.c
What is the output of the following program
# include <stdio.h>
main( )
{
int x=0;
divert( );
printf(“%d\n”, x);
divert( );
x=x+3;
printf(“%d\n”, x);
}
divert ( )
{
int x =0;
x+=2;
printf(“% \n”, x);
}
Output
2
0
2
3
Extern
These storage classes doesn’t create any variable but informs the compiler for its existence.
1. Location – Memory (RAM)
2. Scope – Global
3. Default value – 0
4. Life – As long as programs execution doesn’t come to an end.
5. Keyword – extern
Example : extern int x;
Output2.C
What will be the output of the following program.
# include <stdio.h>
int n=10;
main ( )
{
int n;
clrscr ( );
print(“ %d \n”, n);
num1( );
}
num( )
{
extern int n;
printf (“%d”, n);
}
Note :if the name of the local variable and global variable are same then preference is given to
the local variable.
Static
A variable having storage class static is permanent and keeps its value across the function calls.
1. Location – Memory (RAM)
2. Scope – Local
3. Default value – 0
4. Life – between different function calls.
5. Keyword – static
Example : static int x;
Output3.C
What will be the output of the following program.
# include < stdio.h>
main ( )
{
clrscr ( );
incre ( );
incre ( );
incre ( );
}
incre ( )
{
char ch = 65;
ch= ch+1;
printf (“ \n %c”, ch);
}
Output
B
B
B
Output4.C
Write the output of the following program.
# include < stdio.h>
main ( )
{
clrscr( );
incre( );
incre( );
incre( );
}
incre( )
{
static char ch=65;
ch=ch+1;
print (“\n %c”, ch);
}
Note :static variable is initialized once.
register
These variables are created in one of the CPU register.
1. Location – CPU register
2. Scope – Local
3. Default value – Garbage
4. Life – As long as the control is within the block.
5. Keyword – register
Example : register int x;
185. Arms1. C
WAP to print all the Armstrong numbers from 1 to 999.
# include < stdio.h>
main ( )
{
int n, r, a, s = 0;
n=1;
while (n <=999)
{
s=0;
a=n;
while (a>0)
{
r=a%10;
s=s+(r*r*r);
a=a/10;
}
if(s==n)
{
printf (“\n %d”, n);
}
n=n+1;
}
}
Pointer
Pointer is a special type of variable, which contains the address of a memory location. Pointer
provides the indirect way of accessing the value of a data item.
int n = 223;
n—variable
223 data
1045--- address
pn pointer( variable)
1045 address of n
1140—address of pointer
Note : The ‘&’ symbol is used to print the address of a memory location or the address of a
Variable.
Example : int n =223;
printf (“% u”,&n);
186. WAP to enter a number and print the address of the memory location where that number is
stored.
# include <stdio.h>
main( )
{
int n;
printf(“\n enter a no”);
scanf(“%d”, n);
printf(“%u”, &n);
}
%u – unsigned integer.
Use of pointer
1. It returns more than one value from a function.
2. It provides the indirect way of accessing a variable.
3. It leads to more efficient code.
4. It manipulates the arrays more easily.
5. It can create data structures like linked list.
Declaring a pointer
Syntax : <data type> *<pointer>;
Example : int *px;
Assigning the address to a pointer
Syntax : <pointer variable> = &<variable>;
Example : int x=4, *px; px= &x;
Assigning a value to a variable through a pointer
Example : *px=104;
Note : ‘ * ’ is read as ‘value at ‘
187. What will be the output of the following program.
#include <stdio.h>
main()
{
int x, y, *px, *py;
x=44;
y=55;
x=y+5;
y=x-10;
px=&x;
py=&y;
printf(“%d”, *px);
printf(“%d”, *py);
}
Pointer Arithmetic
Arithmetic operations can also be done on pointers. But only following arithmetic operations can
only be performed on pointers.
1) Subtraction of a number from a pointer.
Example : int x, *px;
px =& x;
px = px-2;
2) Addition of a number to pointer.
Example : int x, *px;
px= &x;
px=px+3;
Pointer to function
Call by value
When we call a function by passing the value as argument then this concept is known as call by
value. But this concept has a disadvantage i.e. it has no effect to the calling function because as
the default storage class is automatic, the variables modified in the function definition are
destroyed when the control comes out from the function definition.
188. What will be the output of the following program.
#include <stdio.h>
main()
{
int x,y;
x=4;
y=5;
pars(x, y);
printf(“\n%d\n%d”, x, y);
}
pars(int a, int b)
{
a=a+10;
b=b+10;
}
Call by Reference
When a function is called by passing the address of the variable i.e. pointer, then the concept is
known as call by reference. In this case the modification in the function definition or in the called
function has effects to its calling function.
189. What will be the output of the following
#include<stdio.h>
main()
{
int x,y;
x=4;
y=5;
pars(&x, &y);
printf(“\n%d\n%d”,x,y);
}
pars( int *a, int *b)
{
*a=*a+10;
*b=*b+10;
}
190. WAP to enter the radius of a circle. Define a function to calculate its area and
circumference. Print the area and circumference in the main()
191. WAP to enter the length and breadth of a rectangle. Define a function to calculate its area
and perimeter. Print the area and perimeter in the main().
192. WAP to enter two numbers. Define a function to exchange the value. Print the numbers in
main().
Pointers and array
Just like the variable the address of an array can also be the assigned to the pointer. Generally the
address of the first element of the array is assigned to the pointer.
193. WAP to enter five numbers into an array and print it by using a function.
194. WAP to enter 5 numbers into an array. Define a function to print it reversal.
195. WAP to enter a string and define a function to print it in reverse order.
196. WAP to enter a string and define a function to copy it to another string variable. Print the
string variable in the main()
Structure
Structure is a collection of variable having same or different data types grouped together under a
single name.
A Variable
A S H O K ARRAY
A S H O K 15 S C I E N C E 69
Name Age Subject Mark
The variable that makes up the structure are known as structure elements or structure members. A
structure declaration doesn’t reserve any space in the memory. It defines the form of the structure.
Actually structure is a user defined data type. Declaring a structure means creating a structure a
new data type. Once a new data type has been defined then one or more variables of that type
can be declared.
Structure Declaration
Syntax : struct <tag name>
{
<element1>;
< element 2>;
}
< stucture variable>;
Example : struct student
{
char name [ 30 ];
int age;
char subject [ 15 ];
int mark;
}
Example : struct student stu;
struct student stu, s, stu1;
Accessing the structure element
Syntax : < Structure name>. < Structure element>
Example : scanf (“ %s”, stu.name);
scanf (“%s”, stu.subject);
printf (“%s”, stu.name);
scanf (“ %d”, stu.age);
gets (stu.name);
Initializing a structure
struct student stu = {“Ashok “, 15, “science”, 69};
Note : One structure variable can be assignment to another structure variable but they
should be the same type.
Example : stu1=stu;
197. WAP to input name, code and Basic salary of an employee and print them by using
structure.
198. WAP to enter the data into a structure having following elements.
Name char 25
Quantity int
Price int
Display item name , quantity, price and total amount.
199. WAP to define a structure having the following details of an employee.
Name char 30
Basic int
Calculate his grade according to the following condition and print his name, grade and
basic salary.
Basic Grade
basic>=8000 A
6000=<basic<8000 B
basic<6000 C
Array of structures
Like array of characters, array of integers we can also have array of structures. An array of
structures is a collection of similar data types which themselves are a collection of dissimilar data
types.
Declaration
Syntax : struct <structure name><structure variable>[<no. of elements>]
Example : struct student s[5]
Accessing
scanf(”%s”, e[0].name);
scanf(“%d”, e[1].bs);
Example: printf(“%d”, e[z].bs);
get(e[3].name);
200. WAP to declare a structure having following details
name char[25]
marks int
Enter the data of 5 students and display them.
201. WAP to declare a structure having following details
itemname char 20
rate int
qty int
Enter data for four items and print them in the following format.
Item Name Quantity Rate Amount
- - - -
- - - -
typedef
It is used to re-define an existing data type to a new data type name.
Syntax : typedef <data type> <variable or new data type>
Example : typedef int Mark;
Mark m, s, e;
Mark n[5];
Generally upper case letters are used for the new data type name to make it clear that we are
dealing with a re-named data type. typedef is very useful when the name of a particular data type
is long.
Example : typedef long int AMT;
AMT x, int;
typedef statement is more useful while declaring the structure variable because it eliminates the
repeated use of < struct tag name>.
Example : typedef struct STU
{
char na [30];
int r;
int m;
};
main ( )
{
STU S.
STU S1[5];
}
202. WAP to enter today’s date and display tomorrows date.
Files in C
Files
File is a media to store the data and information permanently in the disk based storage for any
future use.
Management of files include the followings-
1) Opening the file
2) Read or write into the file
3) Closing the file
Opening the file
Before reading from a file or writing into a file it should be opened for a particular purpose.
Technically opening a file means creating a relationship between the operating system and the
program. In c opening a file is possible by creating a file structure pointer and assigning the file to
it.
File pointer
In order to read or write into a file, a file pointer is needed. File pointer is a pointer to structure,
which is defined in the header file stdio.h. It contains all the information about the file. The name of
this structure is known as FILE. So before opening a file it is needed to declare a file pointer
having the structure type FILE.
Syntax : FILE < file pointer >;
Exmple : FILE *fp;
fopen
A file is opened in different modes to carry out different operations.
“r”
In this mode one can read the information from the file. If the specified file does not exit NULL is
returned to the file pointer.
“w”
In this mode a new file is opened for writing purpose. If the specified file exists it will be destroyed
and a new file is created in its place. NULL is returned if the disk is write protected or there is no
space in the disk.
“a”
This mode is used to add data or information at the end of the specified file. If the specified file
does not exit a new file is created.
r ’ - > for reading and writing.
w’ - > for reading and writing.
a’- > for reading and appending.
Closing a file with fclose ( )
It is used to close a file.
Syntax : fclose (<file pointer>);
Example : fclose (fp);
Reading and writing a file
Reading from a file and writing into a file can be done by using the following functions or
commands.
fgetc ( )
It is used for reading characters from a file open in the read mode. It returns EOF if the end of file
occurs otherwise it returns a character from the input buffer.
Syntax : < character variable>= fgetc (<file pointer>);
Eample : ch= fgetc (fp);
Note : Buffer is a temporary memory location.
212. WAP to read an existing text file and display its contents on the str screen.
fputc( )
It is used to write a single character into a file, which is opened in “ w ” mode.
Syntax : fputc(< variable >, <file pointer >);
Example : fputc(ch, fp);
213. WAP to enter some characters into a file until enter key is pressed.
214. WAP to enter the source file name and target file name. Copy the contents of the source file
to target file.
fgets ( )
It is used to read a string of character from a file. It returns NULL if EOF reached.
Syntax : fgets (< string variable >, <string length>, < file pointer>);
Example : fgets (str, 79, fp);
215. WAP to enter a file name and display its contents on the screen.
fputs ( )
It is used to write a string of characters into a file.
Syntax : fputs (< string variable >, < file pointer >);
Example : fputs (str, fp);
216. WAP to enter n number of names into a file.
Binary mode and text mode
In text mode text and characters are stored one character per byte. In this mode numbers are
stored as strings of characters, not as they are stored in memory, two bytes for an integer, four
bytes for float. Thus no 5261, even though it occupies two bytes in memory, when transferred to
the disk it will occupy four bytes i.e. one byte per character. Thus the numbers with more digits will
require more disk space.But in binary mode more numbers are stored in binary format it means
each number will occupy same number of bytes on disk as it occupy in memory.
Opening a file in binary mode
fp = fopen (“st.txt”,”rb”);
Character “b” is used to specify the binary mode.
Opening a file in text mode
Character “t” is used to specify the text mode. But as it is the default more there is no need to
specify the text mode.
Example : fp= fopen (“st.txt”, ”r”);
fp= fopen (“st.txt”, ”rt”);
Command line argument
Generally the UDFs are called from the main( ) and arguments are passed from the main( ) to that
function. Except the main( ) the UDFs can also be called from other UDFs. As main( ) is a function
so it should be called by any one. Operating system is there to call main( ). As arguments can be
passed from the calling function to the called function, so while calling main( ) from the operating
system, arguments can also be passed. From the operating system command line these
arguments are passed while calling the main( ). In this case these arguments are known as
command line arguments.
When operating system calls main( ) by pressing arguments then main( ) uses two special
arguments (variables) to receive it. These arguments are specified inside the parenthesis of the
main(). These two arguments are
i. argc (ii) argv
argc
It is a special type of variable, which holds the number of arguments passed from the command
line. It is of integer type. This value of argc is always at least 1 because the name of the program is
the first argument.
argv
It holds the arguments from the command lines as strings. It is of character type. Actually it is an
array of strings.
Example : char *argv[ ];
217. Name5.c
Write a command line argument to pass a name and print it 5 times.
218. Sum.c
Write a command line argument to add two different numbers.
219. Write command line argument programs to develop the following command.
a. SQRT <number>
b. DIV (<number1> <number2>)
c. Pulpow <number> <power>
d. Prime <number1> <number2>
e. Facters <numbers>
224. Write a command line argument program to accept a string and print it reversely.
225. Write a command line argument program to imitate the type command of dos.
# include <stdio.h>
main (int argc, char * argv [ ])
{
int x;
for (x=1; x<=5; x++)
{
printf(“\n % s”, argv [1]);
}
}