0% found this document useful (0 votes)
15 views37 pages

Test 1

This document provides an overview of functions in C programming, categorizing them into library functions and user-defined functions. It discusses the structure of user-defined functions, including their definition, declaration, calling methods, return values, and types of functions based on arguments and return values. Additionally, it covers concepts such as recursion, nested functions, and passing arrays and strings to functions.

Uploaded by

govindanm223
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
15 views37 pages

Test 1

This document provides an overview of functions in C programming, categorizing them into library functions and user-defined functions. It discusses the structure of user-defined functions, including their definition, declaration, calling methods, return values, and types of functions based on arguments and return values. Additionally, it covers concepts such as recursion, nested functions, and passing arrays and strings to functions.

Uploaded by

govindanm223
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 37

Unit IV

4.1. Functions:

In C programming functions can be classified into two categories,


namely,

 Library functions – These are not required to be written by user.


Ex: printf, scanf, sqrt, cos, strcat, etc.
 User-defined functions – This has to be developed by the user at
the time of writing a program. Ex: Main

4.1.1. Need for user defined functions

 Every program must have a main function to indicate where the


program has to begin its execution.
 The program may become too large and complex and as a result the
task of debugging, testing and maintaining becomes difficult.
 If a program is divided into functional parts, then each part may be
independently coded and later combined into a single unit.
 These independently coded programs are called subprograms that are
much easier to understand, debug and test.
 There are times when some types of operation or calculation is
repeated at many points throughout a program
 In such situations, we may repeat the program statements whenever
they are needed
 Another approach is to design a function that can be called and used
whenever require.
 This saves both time and space
Advantages

 It facilitates top-down modular programming.


 The length of a source program can be reduced by using functions at
appropriate places.
 This factor is particularly critical with microcomputers where memory
space is limited
 It is easy to locate and isolate a faulty function for further
investigations
 A function may be used by many other programs, this means that a C
program can build on what others have already done, instead of
starting over, from scratch.

4.1.2. The form of C functions

The elements of user-defined functions are

 Function definition
 Function call
 Function declaration
Definition of functions

A function definition is also known as function implementation. It includes


the following elements

 Function name
 Function type
 List of parameters
 Local variable declarations
 Function statements and
 A return statement.
All the six elements are grouped into two parts, namely,
 Function header(first three elements)
 Function body(second three elements)
Syntax

function_typefunction_name(parameter list)
{
local variable declarations;
executable statement1;
executable statement2;
-----------------
return(expression);
}
where,

 function_type – data type of return value of the function.


 function_name – name of the function
Rules for naming s function
o It must begin with a letter
o It may be in uppercase or in lowercase
o It should not be a keyword, library function name
 argument-list-declaration – variable declarations separated by
commas
 expression – valid arithmetic expression.
Function Header

The function header consists of three parts

 The function type


 The function name
 The formal parameter list.
 A semicolon is not used at the end of the function header.
Name and Type
 The function type specifies the type of value that the function is
expected to return to the program calling the function.
 If the return type is not explicitly specified, C will assume that it is an
integer type.
 If the function is not returning anything, then we need to specify the
return type as void.
 The function name is any valid C identifier and therefore must follow
the same rules of formation as other variable names in C.
Formal Parameter List

 The parameter list declares the variables that will receive the data sent
by the calling program.
 They serve as input data to the function to carry out the specified task.
 Since they represent actual input values, they are often referred to as
formal parameters.
 The parameters are also known a arguments.
Function Body

 The function body contains the declarations and statements necessary


for performing the required task.
 The body enclosed in braces, contains three parts, the order is given
below
o Local declarations - that specify the variable needed by the
function.
o Function statements - that perform of the task of the function.
o A return statement - that returns the value evaluated by the
function.
 If a function does not return any value we can omit the return
statement.
Example

floatmul(float x, float y)
{
float result;
result=x*y;
return(result);
}

FunctionCalls

A function can be called by simply using the function name followed by


a list of actual parameters (or arguments), if any enclosed in parentheses.

Example

main()
{
int y;
y = mul (10,5); /*function call */
printf(“%d/n”,y);
}

 When the compiler encounters a function call, the control is transferred


to the function mul().
 This function is then executed line by line as described and a value is
returned when a return statement is encountered.
 This value is assigned to y.
 There are many different ways to call a function. They are
o mul(10,5)
o mul(m,5)
o mul(10,n)
o mul(m,n)
o mul(m+5,10)
o mul(10,mul(m,n))
o mul(expression1,expression2)
Function Declaration

A function declaration consists of four parts. They are

 Function type(return type)


 Function name
 Parameter list
 Terminating semicolon
Syntax

Function-type function-name (parameter list);

A prototype declaration may be placed in two places in a program.

 Above all the functions (including main) - global prototype.


 Inside a function definition - local prototype.
The place of declaration of a function defines a region in a program in
which the function may be used by other functions. This region is known as
the scope of the function.

4.1.3. Return Values and Their Types

A function may or may not sent back any value to the calling function.
If I does, it is done through the return statement.

The return statement can take one of the following forms

 return; - The “plain” return does not return any value; it acts much as
the closing
brace of the function.
Example

If (error)
return;

 return (expression); - The return with an expression returns the value


of the
expression.

Example
intmul (int x, int y)
{
int p;
P=x*y;
return(p);
}

 It return the value of p which is the product of the values of x


and y.
 The last two statements can be combined into one statement as
follows
return (x*y);

4.1.4. Calling a function

 A function can be called by simply using the function name in a


statement.
 When the function encounters a function call, the control is transferred
to the function
 Example

mul(x,y)

main()

int p;
 The function is executed and the value is returned and assigned to p
 A function which returns a value can be used in expressions like any
other variables
 Example
printf("%dn", mul(p,q));
y = mul(p,q) / (p+q);
if (mul(m,n)>total)
printf("large");

 A function cannot be used on the right side of an assignment


statement
mul(a,b) = 15;
 A function that does not return any value may not be used in
expression; but can be called to perform certain tasks specified in the
function
main()
{
printline();

}
4.1.5. Category of functions

A function, depending on whether arguments are present or not and


whether a value is returned or not, it may belong to one of the following
categories

 Functions with no arguments and no return values.


 Functions with arguments and no return values.
 Functions with arguments and one return value.
 Functions with no arguments but return a value.
 Functions that return multiple values.
No arguments and no return values

 When a function has no arguments, it does not receive any data from
the calling function.
 Similarly, when it does not return a value, the calling function does not
receive any data from the called function.
 There is no data transfer between the calling function and the called
function.
 Example

#include <stdio.h>

#include <conio.h>

main()

void test1(); /*function declaration*/

clrscr();

test1(); /*function call*/

getch();

void test1() /*function definition*/

Output

WELCOME TO SOWDESWARI COLLEGE

Arguments but no return values

 The function with arguments will receive data from the calling function.
 The actual arguments and formal arguments should match in number,
data type and order.
 The values of actual arguments are assigned to the formal arguments
on a one-to-one basis, starting with the first argument.
 When the function call is made, only the copy of the actual arguments
is passed into the called function.
 So their values cannot be altered by the function.
 When a function does not return a value, the calling function does not
receive any data from the called function.
 Therefore it is a one-way data communication.

 Example

#include <stdio.h>

#include <conio.h>

main()

{void print(int);

clrscr();

print(5);

getch();

}
Output

The value is 5

Arguments with return values

 The function with arguments will receive data from the calling function.
 The values of actual arguments are assigned to the formal arguments
on a one-to-one basis, starting with the first argument.
 When the function call is made, only the copy of the actual arguments
is passed into the called function.
 So their values cannot be altered by the function.
 When a function returns a value, the calling function will receive a data
from the called function.
 The nature of data communication between the calling function and
the called function is two-way communication.
Example

#include<stdio.h>
#include <math.h>
main(){
int square(int);
inta,b;
clrscr();
printf(“\nEnter the numbers\n”);
scanf(“%d”,&a);
b=square(a);
printf(“Square is %d”,b);
getch();
}
int square(int x) {
int c;
Output
Enter the numbers
100
Square is 10

No Arguments and return values

 When a function has no arguments, it does not receive any data from
the calling function.
 When a function returns a value, the calling function will receive a data
from the called function.
 The nature of communication between the calling function and the
called function is one-way communication.
 Example

#include <stdio.h>

#include <conio.h>

main()

int s;

int add();

clrscr();

s=add();

printf(“Sum=%d\n”,s);

getch();

int add()

inta,b;
Output

Enter two integers

Sum=5

4.1.6. Nested functions

 Some programmer thinks that defining a function inside an another


function is known as “nested function”.
 But the reality is that it is not a nested function, it is treated as lexical
scoping.
 Lexical scoping is not valid in C because the compiler can’t reach/find
the correct memory location of the inner function.
 Nested function is not supported by C because we cannot define a
function within another function in C.
 We can declare a function inside a function, but it’s not a nested
function.
 Because nested functions definitions can notaccess local variables of
the surrounding blocks, they can access only global variables of the
containing module.
 Therefore, nested functions have only a limited use. If we try to
approach nested function in C, then we will get compile time error.

#include <stdio.h>

int main(void)

printf("Main");
int fun()

Output:

Compile time error: undefined reference to `view'

4.1.7. Recursion

Recursion is the process of repeating items in a self-similar way. In


programming languages, if a program allows you to call a function inside the
same function, then it is called a recursive call of the function.

Example

#include <stdio.h>

#include <conio.h>

main()

{
int n;
Output

Enter the n value

The factorial value of 4=24

4.1.8. Functions with arrays

One-Dimensional Arrays

 It is possible to pass the values of an array to a function.


 To pass a one-dimensional array to a called function, it is sufficient to
list the name of the array without any subscriptand the size of the
array as arguments.
 The name of the array represents the address of its first element.
 By passing the array name, we are passing the address of the array to
the called function.
 The array in the called function now refers to the same array stored in
the memory.
 Therefore, any changes in the array in the called function will be
reflected in the original array.
 Passing addresses of parameters to the functions is referred to as pass
by address.
 There are three rules to pass an array to a function

o The function must be called by passing only the name of the array.
o In the function definition, the formal parameter must be an array
type; the size of the array does not need to be specified.
o The function prototype must show that the argument is an array.
Example

#include <stdio.h>
#include <conio.h>
main()
{
float largest(float a[], int n);
float value[4]={2.5,-4.75,1.2,3.67};
clrscr();
printf(“The largest value is = %f\n”,largest(value,4));
getch();
}
float largest(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);
}
Output
The largest value is = 4.000000

Two-Dimensional Arrays

 Like simple arrays, we can also pass multi-dimensional arrays to


functions.
 The rules for passing two dimensional arrays to functions are
o The function must be called by passing only the array name.
o In the function definition, we must indicate that the array has two-
dimensions by including two sets of brackets.
o The size of the second dimension must be specified.
o The prototype declaration should be similar to the function header.
Example

#include <stdio.h>
#include <conio.h>
#define m 3
#define n 4
main()
{
void display(int a[][n]);
int a[m][n]={{1,2,3,4},{5,6,7,8},{9,10,11,12}};
clrscr();
display(a);
}
void display(int a[][n])
{
inti,j;
printf(“Contents of the array\n”);
for(i=0;i<=m-1;i++)
{
for(j=0;j<=n-1;j++)
printf(“\t%d”,a[i][j]);
printf(“\n”);
}
getch();
}

Output

Contents of the array

1 2 3 4

5 6 7 8

9 10 11 12

Passing strings to functions


 The strings are treated a character arrays in C and therefore the rules
for passing strings to functions are very similar to those for passing
arrays to functions. The rules for passing strings to functions are
 The string to be passed must be declared as a formal argument of the
function when it is defined.
 The function prototype must show that the argument is a string.
 A call to the function must have a string array name without subscripts
as its actual argument.
Example

#include <stdio.h>
#include <conio.h>
main()
{
char t[20];
intn,j;
void left(char t[],int n);
clrscr();
printf(“\n Enter the string “);
gets(t);
printf(“\nEnter the no. of characters “);
scanf(“%d”,&n);
left(t,n);
getch();
}
void left(char t[],int n)
{
int i;
printf(“%s”,t);
for(i=0;i<n,i++)
printf(“\n%c”,t[i]);
}

Output
Enter the string SOWDESWARI COLLEGE

Enter the no. of characters 10

SOWDESWARI COLLEGE

4.1.9. Call by value

 In call by value method, the value of the actual parameters is copied


into the formal parameters. In other words, we can say that the value
of the variable is used in the function call in the call by value method.
 In call by value method, we can not modify the value of the actual
parameter by the formal parameter.
 In call by value, different memory is allocated for actual and formal
parameters since the value of the actual parameter is copied into the
formal parameter.
 The actual parameter is the argument which is used in the function call
whereas formal parameter is the argument which is used in the
function definition.
Example

#include <stdio.h>

void swap(int , int); //prototype of the function

int main()

{ int a = 10;

int b = 20;

printf("Before swapping the values in main a = %d, b = %d\


n",a,b);

swap(a,b);

printf("After swapping values in main a = %d, b = %d\


n",a,b);

void swap (int a, int b)

int temp;
Output

Before swapping the values in main a = 10, b = 20

After swapping values in function a = 20, b = 10

After swapping values in main a = 10, b = 20

4.1.10. Call by reference

 In call by reference, the address of the variable is passed into the


function call as the actual parameter.
 The value of the actual parameters can be modified by changing the
formal parameters since the address of the actual parameters is
passed.
 In call by reference, the memory allocation is similar for both formal
parameters and actual parameters. All the operations in the function
are performed on the value stored at the address of the actual
parameters, and the modified value gets stored at the same address.
Example

#include <stdio.h>
void swap(int *, int *);
int main()
{
int a = 10;
int b = 20;
printf("Before swapping the values in main a = %d, b = %d\n",a,b);
swap(&a,&b);
printf("After swapping values in main a = %d, b = %d\n",a,b);
}
void swap (int *a, int *b)
{
int temp;
temp = *a;
*a=*b;
*b=temp;
printf("After swapping values in function a = %d, b = %d\n",*a,*b);
} }

Output

Before swapping the values in main a = 10, b = 20

After swapping values in function a = 20, b = 10

After swapping values in main a = 20, b = 10

3.2.11. Storage classes

 It is very important to understand the concept of storage classes and


their utility in order to develop efficient multifunction programs
 In C there are four storage classes
o Automatic variables
o External variables
o Static variables
o Register variables
 Scope of variable – Determines over what parts of the program a
variable is actually available for use (active)
 Lifetime of variable – Refers to the period during which a variable
retains a given value during execution of program (alive)
 Variables are categorized depending on the place of their declaration
o Internal (local) - which are declared within a particular function
o External (global) - which are declared outside of any function
 Automatic variables
o Automatic variables are declared inside a function in which they
are to be utilized
o They are created when the function is called and destroyed
automatically when the function is exited, hence the name
automatic
o Automatic variables are therefore private to the function in which
they are declared
o Automatic variables are also referred to as local or internal
variables
o A variable declared inside a function without storage class
specification is, by default, an automatic variable
o We may also use the keyword “auto” to declare automatic
variables explicitly
main()
{
autoint number;
.......

 External variables
o Variables that are both alive and active throughout the entire
program are known as external variables
o They are also known as global variables
o Global variables can be accessed by any function in the program
o External variables are declared outside a function
o In case a local variables and a global variable have the same name,
the local variable will have precedence over the global one in the
function where it is declared
o Once a variable has been declared as global, any function can use it
and change its value
o Then subsequent functions can reference only that new value
o Global variable is that it is visible only from the point of declaration
to the end of the program
o Global variables are initialized to zero by default
o The main cannot access the variable that has been declared after
the main function
o This problem can be solved by declaring the variable with the
storage class “extern”
 Static variables
o The value of static variables persists until the end of the program
o A variable can be declared static using the keyword “static”
o A static variable may be an internal or external type, depending on
the place of declaration
o Internal static variables
 Declared inside a function
 The scope extend up to end of the function in which they are
defined
 Similar to auto variables, except that they remain
inexistence (alive) throughout the remainder of the program
 Static variable is initialized only once, when the program is
compiled.
 It is never initialized again
o External static variables
 Declared outside of all functions and is available to all the
functions in that program
 The difference between a static external variable and a
simple external variable is that – the static external variable
is available only within the file where it is defined while the
simple external variable can be accessed by other files
 Register variables
o Register access is much faster than a memory access
o We can make a variable to be placed in one of the machine register
instead of memory using “register”
o Most compiler allow int or char variables to be placed in the register
o ANSI standard does not restrict to any particular data type
o C will automatically convert register variables into non-register
variables once the limit is reached

4.2. Character arrays and string functions


4.2.1. Character arrays

A string is a sequence of characters that is treated as a single data


item. Any group of characters (except double quote sign) defined between
double quotation marks is a string constant.

Example

“Man is obviously made to think”

Character arrays or strings are used by programming languages to


manipulate text such as words and sentences. The common operations
performed on character strings include

 Reading and writing strings.


 Combining strings together.
 Copying one string to another.
 Comparing strings for equality.
 Extracting a portion of a string.
A string constant is a one dimensional array of characters terminated
by a null(“\0”). For example: char name[]={“H”,”E”,”L”,”L”,”O”,”\0”};

Each character in the array occupies one byte of memory and the last
character is always “\0”. The null character will be automatically added by
the compiler.

Declaring character array (string) variables

In C there is no strings data type. However, it allows us to


represent strings as character arrays. In C, therefore, a string variable is any
valid C variable name and is always declared as an array of characters.

Syntax

charstring_name[size];

The size determines the number of characters in the string_name.

Examples

char city[10];

When the compiler assigns a character string to a character array, it


automatically supplies a null character (“\0”) at the end of the string.
Therefore the sizeshould be equal to the maximum number of characters in
the string plus one.

Initializing string variables

We can initialize a character array without specifying the number of


elements. For example
char string[ ] = {“G”,”O”,”O”,”D”,”\0”};

The above statement defines the array as a five element array. We can
also declare the size munch larger than the string size in the initialization.
For example, the below statement is also permitted.

char string[10] = “GOOD”;

Reading strings from terminal

Using scanf function

 The input function “scanf()” can be used with %s format specification


to read in a string of characters.
 Example
char address[10];

scanf(“%s”,address);

 The “scanf()” function automatically terminates the string that is read


with a null character and therefore the character array should be large
enough to hold the input string plus the null character.
 We can also specify the field width using the form %ws in the scanf
statement for reading a specified number of characters from the input
string.
 Example
scanf(“%ws”,name);

 The width w is equal to or greater than the number of characters typed


in. The entire string will be stored in the string variable. The width w is
less than the number of characters in the string. The excess characters
will be truncated and left unread.
Example program

#include<stdio.h>

#include<conio.h>

main()
Output

Enter Your Name POOJA

Hello POOJA!

Reading a Line of Text

 The “scanf()” statement with “%s” or “%ws” can read only strings
without whitespaces. That is, they cannot be used for reading a text
containing more than one word.
 However, C supports a format specification known as the edit set
conversion code “%[..]” that can be used to read a line containing a
variety of characters, including whitespaces.
Example program

#include<stdio.h>

#include<conio.h>

main()

{ char name[25]

clrscr();

printf(“Enter the string\n”);

scanf(“%[^\n]s”,name);

Output

Enter the string

SALEM SOWDESWARI COLLEGE

SALEM SOWDESWARI COLLEGE

Using getchar and gets functions

Using getchar function

 The “getchar()” function is used to read a single character from the


terminal.
 We can use this function repeatedly to read successive single
characters from the input and place them into a character array.
 Thus, an entire line of text can be read and stored in an array.
 The reading is terminated when the new line character (“\n”) is
entered and the null character is then inserted at the end of the string.
Syntax

charch;

ch=getchar();

Using gets function

 Another and more convenient method of reading a string of text


containing white spaces is use the library function “gets()” available in
the <stdio.h> header file.
Syntax

charstring_name[20];

gets(string_name);

Example program

#include<stdio.h>

#include<conio.h>

main()

{ charmy_name[30];

clrscr();

printf(“Enter Your Name\n”);

gets(my_name);

puts(“My name is”);


Output

Enter Your Name

SARUKESH

My name is SARUKESH

Writing strings to screen

Using printf Function

 The “printf” function with %s format is used to print strings to the


screen.
 The format %s can be used to display an array of characters that is
terminated by the null character.
 Example
printf(“%s”,name);

 It can be used to display the entire contents of the array name.


 We can also specify the precision with which the array is displayed.
 For instance, the specification %10.4 indicates that the first four
characters are to be printed in a field width of 10 columns.
The features of the %s specifications are

 When the field width is less than the length of the string, the entire
string is printed.
 The integer value on the right side of the decimal point specifies the
number of characters to be printed.
 When the number of characters to be printed in specified as zero,
nothing is printed.
 The minus sign in the specification causes the string to be printed left-
justified.
 The specification % .ns prints the first n characters of the string.
Example program
#include<stdio.h>

#include<conio.h>

main()

char name[25];

clrscr();

printf(“Enter the name”);

scanf(“%s”,name);

Output

Enter the name

REENA

Name is REENA

Using putchar and puts Functions

Using putchar function

putchar() function is used to output the values of character variables.

Syntax

char ch=”A”
putchar(ch);

Using puts function

Another and more convenient way of printing string values is to use


the function “puts()” declared in the header file<stdio.h>.

Syntax

puts(str);

You might also like