Sei sulla pagina 1di 22

32

CSC-102: Programming in C (B.Sc.CSIT)

6. Arrays

6.1 ­ Introduction

An array is an identifier that refers to a collection of data items that all have the same name. All data items in an array must be of same type. The individual data items are represented by their corresponding array-elements. Each array element is referred to by specifying the array name followed by one or more subscripts, with each subscript enclosed in square brackets. Each subscript must be expressed as a nonnegative integer. The number of subscripts determines the dimensionality of the array. For example X[i] refers to an element in one dimensional array X. Y[i][j] refers an element in two-dimensional array Y. Higher-dimensional array can be also be formed, by adding additional subscripts in the same manner. Individual data item in the array may be referred to separately by stating their position in the array. Let use assume the value of array elements x[i] as given below. X[1] = 5; X[2] = 10; X[3] = 15;

The position number given in parentheses are called index. The smallest element of an array’s index is called its’ lower bound, and the highest element is called its’ upper bound.

If Min is the lower bound, and Max is the upper bond of an array then, the number of elements that one dimensional array

can hold is called it’s range and is given by (Max – Min + 1).

Arrays can have one or more dimensions, in which case they might be declared as int results[20]; int matrix[5][5];

6.2 ­ Types of Arrays

Arrays can be categorized based on numeric and non-numeric data.

1. Numeric array: Array of numbers (like int, float, double data types) are called numeric array. Numeric arrays always deals with numeric values.

2. Character array (string): Array of characters are called numeric array. One dimensional character array is also called string. We generally use <string.h> header file to perform several operations on string data. Character arrays do not deal with numeric values.

Arrays can be categorized based on the number of dimension.

1. One dimensional array: Array with single dimension is called one-dimensional array.

2. Multidimensional array: Array with more than one dimension is called multi-dimensional array.

6.3 ­ Declaring and using one ­ dimensional numeric array

A list of items can be given one variable name using only one subscript and such a variable is called a single-subscript

variable or a one-dimensional array. In mathematics, we often deal with variables that are single-subscripted. For instance,

we use the equation A

The subscripted variable x i refers to the it th element of x. In C program, single-subscripted variable x i can be expressed as

to calculate the average of n values of x.

x[0], x[1], x[2]

x[n]

The subscript can begin with number 0.

In general terms, a one-dimensional array declaration can be expressed as

data-type array[expression];

Where data-type is the data type, array is the array name, and expression is a positive-valued integer expression which indicates the number of array elements.

33

CSC-102: Programming in C (B.Sc.CSIT)

Example-1

A C program that ask user to input elements of float array and print it’s elements.

#include<stdio.h>

#include<conio.h>

void main()

{

int i;

float x[5];

clrscr();

for(i=0; i<=5;i++)

{

printf("\nx[%d]= ",i); scanf("%f",&x[i]);

}

printf("\n\nThis is what you have entered\n"); for(i=0; i<=5;i++)

printf("%.2f\t",x[i]);

getch();

}

Note:- The array size need not be specified explicitly when initial values are included as a part of an array definitions. With a numerical array, the size will automatically be set equal to the number of initial values included within the definition.

6.4 ­ Initialization of array

Let us consider the following array definitions, which are variations of the definitions in the above example. int x[] = {10,15,20,25,30};

The individual elements will be initialized by the following values. x[0] = 10; x[1] = 15; x[2] = 20; x[3] = 25; x[4] = 30;

6.5 ­ Processing an array

There is no single operation for a whole entire array in C. If two array a and b are similar (i.e., same data type, same dimensionality and same size), assignment operations, comparison operations, etc. must be carried out on an element-by- element basis. This is usually accomplished within a loop, where each pass through the loop is used to process one array element. The number of pass through the loop will therefore equal the number of array elements to be processed.

Example-2

A C program that will calculate the average of n numbers, then compute the deviation of each number

34

CSC-102: Programming in C (B.Sc.CSIT)

#include <stdio.h> #include <conio.h>

void main()

{

int i; float SUM, AVG;

float x[5], d[5]; SUM = 0; for(i= 0; i<=5;++i)

{

printf("x[%d]=",i+1);

scanf("%f", &x[i]); SUM +=x[i];

}

AVG = SUM/6; printf("\nThe average is %f\n\n", AVG);

for(i= 0; i<=5;++i)

{

d[i]=x[i]-AVG; printf("x[ %d] = %f\t d[ %d]= %f\n", i+1,x[i], i+1, d[i]);

}

}

getch();

Example-3

A C program that calculates the maximum, minimum and average elements from a given array. #include <stdio.h> #include <conio.h>

void main()

{

float x[]={12,32,87,90,5,4,7,2,9,101},max, min, avg;

int i;

clrscr();

max=x[0];

for(i=1; i<=0; i++) if(max<x[i]) max=x[i];

min=x[0];

for(i=1; i<=9; i++) if(min>x[i]) min=x[i];

avg= x[0]; for(i=1; i<=9; i++) avg=avg+x[i];

avg=avg/10;

printf("\nArray's elements are:\n");

for(i=0;i<=9;i++)

printf("%.2f\t",x[i]);

35

CSC-102: Programming in C (B.Sc.CSIT)

printf("Minimum element of this array is %.2f\n",min); printf("Maximum element of this array is %.2f\n",max); printf("Avrage element of this array is %.2f\n",avg); getch();

}

6.6 ­ Sorting one dimensional numeric array

Sorting means arranging elements either in ascending order or descending order.

Example-4

Ac program that sorts elements of array in ascending order

#include<stdio.h> #include<conio.h> void main()

 { float x[]={12,32,87,90,5,4,7,2,101,9}; int i,j,tmp; clrscr(); printf("\nArray's elements before sorting are:\n"); for(i=0;i<10;i++) printf("%.2f\t", x[i]); for(i=0; i<10; i++) for(j=i+1; j<10; j++) if(x[i]>x[j]) { tmp = x[i]; x[i] = x[j]; x[j] = tmp; } printf("\nArray's elements after sorting in ascending are:\n"); for(i=0;i<10;i++) printf("%.2f\t", x[i]); getch(); }

6.7 ­ Declaring and processing multidimensional numeric arrays

In multidimensional arrays, a separate pair of square brackets is required for each subscript. Thus, a two-dimensional array will require two pairs of square brackets; a three-dimensional array will require three pairs of square brackets, and so on.

In general terms, a multidimensional array definition can be written as

data-type array[expression1] [expression2]

Where data-type is the data type, array is the array name, and expression1 expression2

valued integer expressions that indicates the number of array elements associated with each subscript.

[expression n ];

expression n are positive-

Example-5

A program in C to print the output of MULTIPLICATION TABLE of size 5 #include<stdio.h> #include<conio.h> #define ROWS 5 #define COLUMNS 5

36

CSC-102: Programming in C (B.Sc.CSIT)

void main()

{

int product[ROWS][COLUMNS]; int i,j;

clrscr(); printf("MULTIPLACTION TABLE\n\n");

for(i=0;i<ROWS;i++)

 { for(j=1;j<=COLUMNS;j++) { product[i][j]=(i+1)*j; printf("%4d ",product[i][j]); } printf("\n"); }

getch();

}

Example-6

A program in C to print a new matrix by adding 10 for each element of old matrix

#include <stdio.h> #include <conio.h>

#define ROWS 4 #define COLUMNS 4 void print_matrix(int matrix[][COLUMNS]); main()

{

int i,j; int matrix[ROWS][COLUMNS]= {

clrscr();

{1,2,3,4},

{5,6,7,8},

{9,10,11,12},

{13,14,15,16}

};

printf("MATRIX BEFORE MODIFICATION\n");

for(i=0;i<=COLUMNS-1;i++)

{

for(j=0;j<=ROWS-1;j++)

printf("%2d ",matrix[i][j]); printf("\n");

}

for(i=0;i<= ROWS-1;i++) for(j=0;j<= COLUMNS-1;j++)

matrix[i][j]=matrix[i][j]+10;

printf("MATRIX AFTER MODIFICATION\n");

for(i=0;i<=COLUMNS-1;i++)

{

for(j=0;j<=ROWS-1;j++)

printf("%2d ",matrix[i][j]);

37

CSC-102: Programming in C (B.Sc.CSIT)

}

getch();

}

printf("\n");

6.8 ­ Declaring and processing character array (Strings)

String can be represented as a one-dimensional character-type array. Each character within the string will be stored within one element of the array. For string manipulation most C compilers include library functions that allow string to be compared, copied or concatenated (i.e., combined one behind another). Other library functions permit operation on individual characters within strings; e.g., they allow individual characters to be located within strings, and so on.

A string variable is any valid C variable name and is always declared as any array. The general form of declaration of a

string variable is

char string_name[size];

The size determines the number of characters in the string_name. Some declaration samples are:

char city[10]; char name[30]; Character arrays may be initialized when they are declared. C permits a character array to be initialized in either of the following two forms:

static char city[9] = “NEW YORK ”; static char city[9] = {‘N’, ’E’, ‘W’, ‘ ’, ‘Y’, ‘O’, ’R’, ‘K’, ‘\0’};

C also permits us to initialize a character array without specifying the number of elements. In such cases, the size of the

array will be determined automatically, based on the number of elements initialized. For example, the statement string[] = {‘G’, ‘O’, ‘O’, ‘D’, ‘\0’}; defines the array string as five element array.

char

6.8.1 ­ Standard Library functions to perform string operations

With every C compiler a large set of useful string handling library functions are provided. We generally use <string.h> header file to perform several operations on string data. The following table lists the commonly used string handling functions along with their purpose.

 Function Use strlen Finds length of string strlwr Converts a string to lowercase strupr Converts a string to uppercase strcat Appends one string at the end of another strncat Appends first n character of a string at the end of another strcpy Copies a string into another strncpy Copies first n character of a string into another strcmp Compares two string strncmp Compares first n character of two string strcmpi Compares two string without regard to case(“i” denotes that this function ignores case) stricmp Compares two string without regard to case(identical to strcmpi) strnicmp Compares first n characters of two strings without regard to case strdup Duplicates a string strchr Finds first occurrence of a given character in a string strrchr Finds last occurrence of a given character in a string strstr Finds first occurrence of a given string in another string strset Sets all characters of string to a given character strnset Sets first n characters of string to a given character strrev Reverses string

38

CSC-102: Programming in C (B.Sc.CSIT)

Example–7

A program written in C that will count the occurrence of vowels and consonants from a line of text

#include<stdio.h>

#include<conio.h>

#include<ctype.h>

void main()

{

int count,vowels,consonants; char linetxt[80]; clrscr(); printf("\nEnter a line of text\n"); gets(linetxt);

vowels=0;

consonants=0;

count=0;

while(linetxt[count]!='\0')

{

if(isalpha(linetxt[count])) if(tolower(linetxt[count])=='a' || tolower(linetxt[count])=='e' || tolower(linetxt[count])=='i' || tolower(linetxt[count])=='o' || tolower(linetxt[count])=='u') ++vowels; else ++consonants; count++;

}

printf("\nNumber of Vowels = %d",vowels); printf("\nNumber of consonants = %d",consonants); getch();

}

Example-8

A C program that uses strlen function to count the number of characters in a string.

#include<stdio.h>

#include<string.h>

#include<conio.h>

void main()

{

char str1[] = "MyString"; int len1, len2; clrscr();

len1 = strlen(str1); len2 = strlen("Hello World"); printf("\nstring1 = %s length= %d",str1, len1); printf("\nstring2 = %s length= %d","Hello World", len2); getch();

}

39

CSC-102: Programming in C (B.Sc.CSIT)

Example-9

A C program that uses strcpy function to copy the contents of one string into another.

#include<stdio.h>

#include<string.h>

#include<conio.h>

void main()

{

char source[] = "MyString"; char target[20]; clrscr(); strcpy(target, source); printf("\nsource= %s",source); printf("\ntarget= %s",target); getch();

}

Example-10

A C program that uses strcat function to concatenate the source string at the end of the target string.

#include<stdio.h>

#include<string.h>

#include<conio.h>

void main()

{

char source[] = "World"; char target[20] = "Hello ";

clrscr(); printf("\ntarget before strcat= %s", source); strcat(target,source); printf("\ntarget after strcat = %s", target); getch();

}

6.8.2 ­ Comparing two strings

The function strcmp() compares two strings to find out whether they are same or different. If the two strings are identical, strcmp() returns a value zero. If they’re not, it returns the numeric difference between the ascii values of the non- matching characters.

Example-11

A program in C that compares two strings and returns the appropriate value in the calling section.

#include<stdio.h>

#include<string.h>

#include<conio.h>

void main()

{

char string1[] = "Jerry"; char string2[] = "Ferry"; int i,j,k; clrscr(); i= strcmp(string1,"Jerry");

40

CSC-102: Programming in C (B.Sc.CSIT)

j= strcmp(string1,string2); k= strcmp(string1,"Jerry boy");

printf("\n%d %d %d",i,j,k); getch();

}

6.8.2 ­ Sorting list of strings

Example-12

A program written in C that sorts the list of names of 5 persons in alphabetical order.

#include<stdio.h> #include<string.h> #include<conio.h> void main()

 { int i=0,j=0; char string[5][20],dummy[20]; clrscr(); printf("Enter name of %d items\n",5); while(i<5) scanf("%s",string[i++]); for(i=1;i<5;i++)/*Outer loop begins*/ { for(j=i;j<5;j++) /*Inner loop begins*/ { if(strcmp(string[j-1],string[j])>0) { /*Exchange of contents*/ strcpy(dummy,string[j-1]); strcpy(string[j-1],string[j]); strcpy(string[j],dummy); } }/*Inner loop ends*/ }/*Outer loop ends*/ /*Sorting completed*/ printf("\nSorted list\n\n"); for(i=0;i<5;i++) printf("%s\n",string[i]); getch(); }

6.8.3 ­ Counting words in a text

We assume that a word is a sequence of any characters, except escape characters and blanks, and that two words are separated by one blank character. The algorithm for counting words is as follows:

1. Read a line of text

2. Beginning from the first character in the line, look for a blank. If blank is found, increment words by 1.

3. Continue steps 1 and 2 until the last line is completed.

The implementation of this algorithm is given below.

Example-13

A C program that counts numbers of words in a given text.

#include <stdio.h>

41

CSC-102: Programming in C (B.Sc.CSIT)

#include <string.h> #include <conio.h> void main()

{

char txt[80]; int i, words; clrscr(); puts("Enter a line of text:"); gets(txt);

/*Counting the words in a line*/ words= 0;

if(txt[0]!='\0')

{

for(i=0;txt[i]!='\0';i++)

if(txt[i]==' ' || txt[i]=='\t')

words++;

words++;

}

clrscr(); printf("\n%s",txt); printf("\nNumber of words = %d",words); getch();

}

7. Function

7.1 ­ Introduction

A function in C language is a block of code that performs a specific task. It has a name and it is reusable i.e. it can be executed from as many different parts in a C Program as required. It also optionally returns a value to the calling program.

There are many advantages in using functions in a program they are:

 It makes possible top down modular programming. In this style of programming, the high level logic of the overall problem is solved first while the details of each lower level functions is addressed later. The length of the source program can be reduced by using functions at appropriate places. It becomes uncomplicated to locate and separate a faulty function for further study. A function may be used later by many other programs this means that a c programmer can use function written by others, instead of starting over from scratch. A function can be used to keep away from rewriting the same block of codes which we are going use two or more locations in a program. This is especially useful if the code involved is long or complicated.

7.2 ­ Different Types of functions in C language

A function may belong to any one of the following categories:

1. Functions with no arguments and no return values.

2. Functions with arguments and no return values.

3. Functions with arguments and return values.

4. Functions that return multiple values.

5. Functions with no arguments and return values.

A function can belong to either standard C library file or user defined

42

CSC-102: Programming in C (B.Sc.CSIT)

1. Library Functions: The C language is accompanied by a number of library functions that carry out various commonly used operations or calculations. The standard library files in C are supplied as a part of each C compiler.

2. User defined functions: C allows programmers to define their own functions for carrying out various individual tasks. The use of programmer-defined functions allows a large program to be broken down into a number of smaller, self-contained components, each of which has some unique, identifiable purpose.

7.3 ­ C Library Functions

Most versions of C include a collection of header files that provide necessary information in support of various library functions. Each file generally contains information in support of a group of related library functions. These files are entered into the program via an #include statement at the beginning of the program. A library function is accessed simply by writing the function name, followed by a list of arguments that represent information being passed to the function. The argument must be enclosed in parentheses and separated by commas. The argument can be constants, variable names, or more complex expressions. A list of standard library functions which are more popularly used are listed below

Arithmetic Functions <math.h, complex.h>

 abs Returns the absolute value of an integer cos Calculates cosine cosh Calculates hyperbolic cosine exp Raises the exponential e to the xth power fabs Finds absolute value floor finds largest integer less than or equal to argument fmod Finds floating-point remainder hypot Calculates hypotenuse of right triangle log Calculates natural logarithm log10 Calculates base 10 logarithm modf Breaks down argument into integer and fractional parts pow Calculates a value raised to a power sin Calculates hyperbolic sine sqrt Finds square root tan Calculates tangent tanh Calculates hyperbolic tangent

Data Conversion Functions <math.h, stdlib.h>

 atof Converts string to float atoi Converts string to int atol Converts string to long ecvt Converts double string fevt Converts double to string gevt Converts double to string itoa Converts int to string itoa Converts long to string strtod Converts string to double strtol Converts string to long integer strtoul Converts string to an unsigned long integer ultoa Converts unsigned long to string

Character Classification Functions <ctype.h>

 isalnum Tests for alphanumeric character isalpha Tests for alphabetic character isdigit Tests for decimal digit islower Tests for lowercase character isspace Tests for white space character isupper Tests for uppercase character isxdigit Tests for hexadecimal digit

43

CSC-102: Programming in C (B.Sc.CSIT)

 tolower Tests character and converts to lowercase if uppercase toupper Tests character and converts to uppercase if lowercase

String Manipulation Functions <string.h>

 strcat Appends one string to another strchr Finds first occurrence of a given character in a string strcmp Compares two strings strcmpi Compares two strings without regard to case strcpy Copies one string to another strdup Duplicates a string stricmp Compares two strings without regard to case (identical to strcmpi) strlen Finds length of a string strlwr Converts a string strncat Appends a portion of one string to another stricmp Compares a portion of one string with portion of another string strncpy Copies a given number of characters of one string to another strnicmp Compares a portion of one string with a portion of another without regard to case strrchr Finds last occurrence of a given character in a string strrev Reverses a string strset Sets all characters in a given character strstr Finds first occurrence of a given string in another string strupr Converts a string to uppercase

Searching and sorting functions <search.h>

 bsearch Performs binary search lfind Performs linear search for a given value qsort Performs quick sort

I/o Functions <stdio.h>

44

CSC-102: Programming in C (B.Sc.CSIT)

 putch Writes a character to the screen putchar Writes a character to screen (macro version ) puts Writes a line to file read Reads date from a file rewind Repositions file pointer to beginning of a file scanf Reads formatted data from keyboard sscanf Reads formatted output to a string tell Gets current file pointer position write Writes data to a file

File Handling Functions

<stdio.h>

 remove Deletes file rename Renames file unlink Deletes file

Directory Control Functions

<dir.h>

 chdir Changes current working directory getcwd Gets current working directory fnsplit Splits a full path name into its components findfirst Searches a disk directory findnext Continues findfirst search mkdir Makes a new directory rmdir Removes a directory

Buffer Manipulation Functions <mem.h, string.h>

 memchr Returns a pointer to the first occurrence, within a specified number of characters, of a given character in memcmp the buffer. Compares a specified number of characters from two buffers memcpy Copies a specified number of characters from one buffer to another memicmp Compares a specified number of characters from two buffers without regard to the case of the letters memmove Copies a specified number of characters from one buffer to another memset Uses a give character to initialise a special number of bytes in the buffer

Disk I/O Functions

<direct.h, dos.h, dir.h>

 absread Reads absolute disk sectors abswrite Writes absolute disk sectors biosdisk BIOS disk services getdisk Gets current drive number setdisk Sets current disk drive

Memory Allocation Functions <malloc.h>

 calloc Allocates a block of memory farmallock Allocates memory from far heap farfree frees a block from far heap free Frees a block allocated with malloc malloc Allocates a block of memory realloc Reallocates a block of memory

Process Control Functions <process.h>

 abort Aborts a process atexit Executes function at program termination execl Executes child process exit Terminates the process spawnl Executes child process with argument list spawnlp Executes child process using PATH variable and argument list system Executes an MS-DOS command

45

CSC-102: Programming in C (B.Sc.CSIT)

Graphic Functions <graphics.h>

 arc Draws an arc ellipse Draws an ellipse floodfill Fills an area of the screen with the current color getimage Stores a screen image in memory getlinestyle Obtains the current line style getpixel Obtains the pixel’s value lineto Draws a line from the current graphic output position to the specified point moveto moves the current graphic output position to a specified point pieslic Draws a pie-slice-shaped figure putimage Retrieves an image from memory and display it rectangle Draws a rectangle setcolor Sets the current color setlinestyle Sets the current line style putpixel Sets a pixel’s value setviewport Limits graphic output and positions the logical origin within the limited area

Time Related Functions <time.h>

 clock Returns the elapsed CPU time for a process difftime Computes the difference between two times ftime Gets currents system time as structure strdate Returns the current system date as string strtime Returns the current system time as string time Gets current system time as long integer setdate Stts DOS date getdate Gets system date

Miscellaneous Functions <dos.h, stdlib.h>

 delay Suspends execution for an interval (milliseconds) getenv Gets value of environment variable getpsp Gets the program Segment Prefix perror Prints error message putenv Adds or modifies value of environment variable random Generates random numbers randomize Initializes random number generation with a random value based on time sound Turns PC speaker on at specified frequency nsound Turns PC speaker off

DOS Interface Functions <dos.h>

 FP_OFF Returns offset portion of a far pointer FP_SEG Returns segment portion of a far pointer getvect Gets the current value of the specified interrupt vector keep Installs terminate-and-stay-resident (TSR) programs int86 Invoke MS-DOS interrupts int86x Invoke MS-DOS interrupt with segment register values intdos Invoke MS-DOS services using register other than DX and AL intdosx Invoke MS-DOS services with segment register values MK_FP Makes a far pointer segred Returns current values of segment registers setvect Sets the current value of the specified interrupt vector

Some commonly used C library functions

 Function Type Purpose abs(i) int Return the absolute value of i. cos(d) double Return to the cosine of d.
 46 CSC-102: Programming in C (B.Sc.CSIT) cosh(d) double Return the hyperbolic cosine of d. exp(d) double Raise e to the power d(e = 2.7182818 of logarithms). is the base of the natural (Naperian) system fabs(d) double Return the absolute value of d. floor(d) double Round down to the next integer value (the largest integer that does not exceed d). fmod(d1,d2) double Return the remainder (i.e., the noninteger part of the quotient) of d1/d2, with same sign as d1. log(d) double Return the natural logarithm of d. pow(d1,d2) double Return d1 raised to the d2 power. rand() int Return a random positive integer sin(d) double Return the sign of d. sqrt(d) double Return the square root of d. srand(u) void Initialize the random number generator. tan(d) double Return the tangent of d. toascii(c) int Convert value of argument to ASCII. tolower(c) int Convert letter to lowercase. toupper(c) int Convert letter to uppercase.

Note:

type refers to the data type of the quantity that is returned by the function.

 c denotes a character-type argument i denotes an integer argument d denotes a double-precision argument u denotes an unsigned integer argument

7.4 ­ Declaring and defining user ­ defined function

 A user-defined function has two principle components: the function declaration statement, and the body of the function. In general terms, the function declaration statement can be written as

data-type name(type1 arg1, type2 arg2,

, type n arg n) ;

Where data-type represents the data type of the item that is returned by the function, name represents the function name,

and type1, type2,

, type n represent the data type of the arguments arg1, arg2,

, arg n .

The arguments that we pass in the body of the function are called formal arguments, because they represent the names of data items that are transferred into the function from the calling portion of the program. The body of the function consists of compound statement that defines the action to be taken by the function.

Example-1

/* This program adds two digits using a programmer defined function */

#include <stdio.h> #include <conio.h>

void main()

{

float x ,y;

clrscr(); printf("Please enter value for x and y: "); scanf("%f %f",&x, &y); printf("\nThe sum of %f and %f is %f",x,y,add(x,y)); getch();

}

{

float sum;

47

CSC-102: Programming in C (B.Sc.CSIT)

sum = x+y; return sum;

}

7.4.1 ­ Function Declaration and prototypes

Any C function by default returns an int value. More specifically, whenever a call is made to a function, the compiler assumes that this function would return a value of type int. If we desire that a function should return a value other than int, then it is necessary to explicitly mention so in the calling function as well as in the called function. To specify that no value is returned, use the void keyword.

Function prototypes are usually written at the beginning of a program, ahead of any programmer-defined functions (including main). The general form of a function prototype is

type n arg n);

data-type name(type1 arg1, type2 arg2,

,

Where data-type represents the data type of the item that is returned by the function, name represents the function name,

. The arguments names can be omitted; however, the argument data types are essential. The data types of the actual arguments must conform to the data types of the arguments within the prototype. Here are some complete function prototypes:

and type1, type2,

, type n represent the data type of the arguments arg1, arg2,

,arg

n

int f1(void); float f3(float, int, char, double); void f4(void);

// Returns an int, takes no arguments // Returns a float // Takes no arguments, returns nothing

To return a value from a function, you use the return statement. return exits the function back to the point right after the function call. If return has an argument, that argument becomes the return value of the function. If a function says that it will return a particular type, then each return statement must return that type. You can have more than one return statement in a function definition

7.4.2 ­ Calling a function in a C program

A function can be called by specifying its name, followed by a list of arguments enclosed in parentheses and separated by commas. If the function call does not require any arguments, an empty pair of parentheses must follow the name of the function. The function call may be a part of a simple expression (such as assignment statement), or it may be one of the operands within a more complex expression.

Example-2

/* This program calculates the factorial of n */

#include <stdio.h> #include <conio.h>

long int factorial(int n);

void main()

{

int i; long int fact; clrscr(); printf("Please enter value between 1 to 10: "); scanf("%d" ,&i);

if (i<0 || i>10)

printf("Invalid number\n"); else

{

fact = factorial(i);

48

CSC-102: Programming in C (B.Sc.CSIT)

printf("\nThe factorial of %d is %ld",i,fact);

}

}

getch();

long int factorial(int n)

{

int i; long int prod = 1; if (n>1)

for(i =2; i<=n; ++i) prod *=i;

return(prod);

}

There may be several different calls to the same function from various places within a program. Within each function call, the number of actual arguments must be the same as the number of formal arguments, and each actual argument must be of the same data type as its corresponding formal argument.

7.4.3 ­ Passing arguments to a function in C

Arguments can be passed in function in one of the following two ways

1. Passing by value (sending the values of the arguments)

In the first method the ‘value’ of each actual argument in the calling function is copied into corresponding formal argument of the called function. With this method, changes made to the formal arguments in the called function have no effect on the values of the actual arguments in the calling function. In the second method (call by reference) the address of actual arguments in the calling function are copied into formal arguments of the called function. This that using the formal arguments in the called function we can make changes in the actual arguments of the calling function. The following program illustrates this fact.

Example-3

The following program illustrate the function ‘Call by value’.

#include <stdio.h> #include <conio.h> void swapv(int x, int y);

void main()

{

int a =5; int b= 10; clrscr(); printf("\nBefore calling swapv()"); printf("\na= %d ",a); printf("\nb= %d",b); swapv(a,b); printf("\nAfter calling swapv()");

printf("\na= %d ",a); printf("\nb= %d",b); getch();

}

void swapv(int x, int y)

{

int temp;

49

CSC-102: Programming in C (B.Sc.CSIT)

temp=x;

x=y;

y=temp; printf("\nInside swapv()"); printf("\na= %d ",x); printf("\nb= %d",y);

}

The output of the above program will be:

x=10

y=5

a=5

b=10

Note that values of a and b remain unchanged even after exchanging the values of x and y.

Example-4

The following program illustrate the function ‘Call by reference.

#include <stdio.h> #include <conio.h>

void swapr(int *x, int *y);

void main()

{

int a =5; int b= 10;

clrscr(); printf("\nBefore calling swapv()"); printf("\na= %d ",a); printf("\nb= %d",b); swapr(&a,&b); printf(“\nAfter calling swapr()”); printf(“\na= %d ”,a); printf(“\nb= %d”,b); getch();

}

void swapr(int *x, int *y)

{

int temp;

temp= *x;

*x= *y;

*y= temp;

printf(“\nInside swapr()”); printf(“\na= %d ”,*x); printf(“\nb= %d”,*y);

}

The output of the above program will be:

x=10

y=5

a=10

b=5

Here that values of a and b are hanged after exchanging the values of x and y.

50

CSC-102: Programming in C (B.Sc.CSIT)

Some rules governing return statement in C:

1. On executing the return statement it immediately transfers the control back to the calling program.

2. It returns the value present in the parentheses after return, to the calling program.

3. There is no restriction on the number of return statements that may be present in a function. Also the return statement need not always be present at the end of the called function.

4. A function can return only one value at a time.

5. If we want that a called function should not return any value, in this case, we must mention so by using the keyword void as shown below.

6. If the value of a formal argument is changed in the called function, the corresponding change does not take place in the calling function.

7.5 ­ Defining and using recursive function in C

Recursion is a process by which a function calls itself repeatedly, until some specified condition has been satisfied. The process is used for repetitive computations in which each action is stated in terms of a previous result. Recursive functions are useful in evaluating certain types of mathematical function In order to solve a problem recursively, two conditions must be satisfied.

1. First, the problem must be written in a recursive form,

2. and second, the problem statement must include a stopping condition.

Care must be taken to define functions which will not call themselves indefinitely, otherwise your program will never

finish.

Example-5

An example of defining and using recursive function called power.

#include <stdio.h> #include <conio.h> double power(float val, unsigned pow);

void main()

{

int n;

float x;

clrscr();

printf("\n Base= "); scanf("%f",&x); printf("\nPower= "); scanf("%d",&n); printf("\n%f Power %d = %lf",x,n,power(x,n)); getch();

}

double power(float val, unsigned pow)

 { if(pow == 0) /* pow(x, 0) returns 1 */ return(1.0); else return(power(val, pow - 1) * val); }

Example-6

An example of defining and using recursive function called factorial.

#include <stdio.h> #include <conio.h>

long int factorial(int n);

51

CSC-102: Programming in C (B.Sc.CSIT)

void main()

{

int n;

clrscr();

printf("n= ");

scanf("%d",&n); printf("n! = %ld\n",factorial(n)); getch();

}

long int factorial(int n)

{

if(n<=1)

else

return(1);

return(n*factorial(n-1));

}

7.6 ­ Passing array in a function

We can pass an entire array to a function as an argument. To pass an array to a function, the array name must appear by itself, without subscripts, as an actual argument within the function call. Some care is required when writing function prototypes that include array arguments. An empty pair of square brackets must follow the name of each array argument, thus indicating that the argument is an array if argument names are not included in a function declaration, then an empty pair of square brackets must follow the array argument data type.

7.6.1 ­ Passing one dimensional numeric array in a function

Example-7

A sample program in C that calculates the maximum, minimum and average elements of an array using user-defined function.

#include <stdio.h> #include <conio.h> float findmax(float a[],int n); float findmin(float a[],int n); float findavg(float a[],int n);

void main()

{

float x[]={12,32,87,90,5,4,7,2,101,9},max, min, avg;

int i;

clrscr(); max=findmax(x, 9); min=findmin(x, 9); avg=findavg(x, 9);

printf("\nArray's elements are:\n");

for(i=0;i<=9;i++)

printf("%.2f\t",x[i]);

printf("Minimum element of this array is %.2f\n",min); printf("Maximum element of this array is %.2f\n",max); printf("Avrage element of this array is %.2f\n",avg); getch();

}

52

CSC-102: Programming in C (B.Sc.CSIT)

float findmax(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;

}

float findmin(float a[],int n)

{

int i; float min;

min=a[0];

for(i=1;i<=n;i++)

if(min>a[i])

min=a[i];

return min;

}

float findavg(float a[],int n)

{

int i;

float avg;

avg=0;

for(i=0;i<=n;i++)

avg=avg+a[i]; avg=avg/n; return avg;

}

7.6.2 ­ Passing multi dimensional numeric array in a function

Example-8

A program that will display all elements of a matrix using a function called print_matrix.

#include <stdio.h> #include <conio.h>

void print_matrix(int matrix[][4]); void main()

{

int matrix[4][4]= {

};

{1,2,3,4},

{5,6,7,8},

{9,10,11,12},

{13,14,15,16}

clrscr(); printf("\n\n-------------------\n"); printf("MATRIX ELEMENTS\n"); print_matrix(matrix); getch();

53

CSC-102: Programming in C (B.Sc.CSIT)

}

void print_matrix(int matrix[][4])

 { int i,j; printf("-------------------\n"); for(i=0;i<=4-1;i++) { for(j=0;j<=4-1;j++) printf("%2d | ",matrix[i][j]); printf("\n"); } }

7.6.3 ­ Passing character array in a function

Example-9

A program that counts the occurrence of vowels of a line of text using a programmer defined function called count vowels.

#include <stdio.h> #include <conio.h> #include <ctype.h> int countvowel(char x[]);

void main()

{

int vowels; char linetxt[80]; clrscr(); printf("\nEnter a line of text\n"); gets(linetxt); vowels=countvowel(linetxt);

printf("\nNumber of Vowels = %d",vowels); getch();

}

int countvowel(char x[])

{

int count,v;

v=0;

count=0;

while(x[count]!='\0')

{

if(isalpha(x[count])) if(tolower(x[count])=='a' ||

tolower(x[count])=='e' || tolower(x[count])=='i' || tolower(x[count])=='o' || tolower(x[count])=='u') v++; count++;

}

return (v);

}