Wednesday, 7 December 2022

Bharat College C Programming 3rd Unit

 

Unit-3

 

Functions: We know that one of the strengths of C language is that C functions are easy to define and use. A function definition shall include the following elements.

  1. Function name
  2. Function type
  3. List of parameters
  4. Local variable declarations
  5. Function statements
  6. A return statement

All the six elements are grouped into two parts, namely.

  • Function header ( First three elements)
  • Function body ( Second three elements)

A general format of a function definition to implement these two parts is given below:

            Function type function name (parameter list)

            {

                        Local variable declaration;

                        Executable statements;

                        Executable statements;

                        ……………………….

                        ………………………

                        Return statement;

            }

Function Header---- The function header consists of three parts: The function type (also known as return type), the function name and the formal parameter list.     

Name and type----The function type specifies the type of value (like float or double) 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. Remember, void is one of the fundamental data types in C.

            The function name is any valid C identifier and therefore must follow the same rules of formation as other variable names in C. The name should be appropriate to the task performed by the function.

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. These parameters can also be used to send values to the calling programs. The parameters are also known as arguments.

            The parameter list contains declaration of variables separated by commas and surrounded by parenthesis. Examples :

            Float quadratic ( int a, int b, int c)

            {

            ………………….

            }

            Double power (double x, int n)

            {

            …………………..

            }

            Int sum( int a, int b)

            {

            ………………….

            }

Remember, there is no semicolon after the closing parenthesis. A function need not always receive values from the calling program. In such cases, functions have no formal parameters. To indicate that the parameter list is empty , we use the keyword void between the parenthesis as in

            Void printline(void)

            {

            ………………

            }

Function body---- The function body contains the declarations and statements necessary for performing the required task. The body enclosed in braces, contains three parts, in the order given below:

  1. Local declarations that specify the variables needed by the functions.
  2. Function statements that perform the task of the function.
  3. 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. However, note that its return type should be specified as void. Again, it is nice to have a return statement even for void functions.

For example:

            Float mul (float x, float y)

            {

                        Float result;

                        Result = x*y;

                        Return (result);

            }

 

Categories of functions: C functions can be classified into two categories, namely, Library Functions and User Defined Functions. Main is an example of user-defined functions, printf and scanf belong to the category of library functions. The main distinction between these two categories is that library functions are not required to be written by us whereas a user-defined function has to be developed by the user at the time of writing a program. However, a user-defined function can later become a part of the C program library.

            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:

Category 1:

 

 

User defined and library functions: Main () is a specially recognized function in C. Every program must have a main function to indicate where the program has to begin its execution. While it is possible to code any program utilizing only main function, it leads to a number of problems. The problem may become too large and complex and as a result the task of debugging, testing and maintaining becomes difficult. If a problem is divided into functional parts, then each part may be independently coded and later combined into a single unit. These subprograms called functions are much easier to understand, debug and test.

            There are times when certain type of operations or calculations is repeated at many points through out a program. Another approach is to design a function that can be called and used whenever required. This saves both time and space.

Advantages:

  1. It facilitates top-down modular programming. In this programming style, the high level logic of the overall problem is solved first while the details of each lower-level function are addressed later.
  2. 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.
  3. It is easy to locate and isolate a faulty function for further investigations.
  4. A function may be used by many other programs. This means that a C programmer can build on what others have already done, instead of starting all over again from scratch.

As you know, functions are classified as one of the derived data types in C programs. It is therefore not a surprise to note that there exist some similarities between functions and variables in C.

  • Both function names and variable names are considered identifiers and therefore they must adhere to the rules for identifiers.
  • Like variables, functions have types (such as int) associated with them.
  • Like variables, function names and their types must be declared and defined before they are used in a program.

In order to make use of a user-defined function, we need to establish three elements that are related to functions.

  1. Function definition
  2. Function call
  3. Function declaration

The function definition is an independent program module that is specially written to implement the requirements of the function. In order to use this function we need to invoke it at a required place in the program. This is known as the function call. The program (or a function) that calls the function is referred to as the calling program or calling function. The calling program should declare any function (like declaration of a variable) that is to be used later in the program. This is known as the function declaration or function prototype.

Recursion: When a called function in turn calls another function a process of chaining occurs. Recursion is a special case of this process, where a function call itself. A very simple example of recursion is presented below:

            Main()

            {

                        Printf(“This is an example of recursion\n”);

                        Main();

            }

When executed, this program will produce an output something like this:

            This is an example of recursion

            This is an example of recursion

            This is an ex

           

Execution is terminated abruptly; otherwise, the execution will continue indefinitely.

Another useful example of recursion is the evaluation of factorials of a given number. The factorial of a number n is expressed as a series of repetitive multiplication as shown below:

            Factorial of n = n(n-1) (n-2)………..

A function to evaluate factorial of n is as follows:

            Factorial (int n)

            {

                        Int fact;

                        If (n = = 1)

                        Return (1);

                        Else

                        Fact= n*factorial (n-1);

                        Return(fact);

            }

Recursive functions can be effectively used to solve problems where solution is expressed in terms of successively applying the same solution to subsets of the problem. When we write recursive functions, we must have an if statement somewhere to force the function to return without the recursive call being executed. Otherwise, the function will never return.

Function arguments:- 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.

            Category 1: Functions with no arguments and no return values.

            Category 2: Functions with arguments and no return values.

            Category 3: Functions with arguments and one return values.

            Category 4: Functions with no arguments but return a value.

            Category 5: 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. In effect, there is no data transfer between the calling function and the called function. For example:

            Function1()

            {

            ---------------------

            ---------------------

            Function2()

            -----------------

            -----------------

            }

            Function2()

            {

            -----------------

            -----------------

            -----------------

            -----------------

            }

Arguments but No return values:------ The nature of data communication between the calling function and the called function with arguments but no return value. For example

            Function1()

            {

            -------------------

            Function2(a)

            ----------------------

            ----------------------

            }

            Function2(f)

            {

            -----------------

            -----------------

            }

            Void printline(char ch)

            Void value(float p, float r, int n)

The arguments ch, p, r, and n are called the formal arguments. Now, the calling function can send values to these arguments using function calls containing appropriate arguments. For example, the function call

            Value(5000, 0.12,5)

Would send the values 500, 0.12 and 5 to the function

            Void value(float p, float r, int n)

And assign 500 to p, 0.12 to r and 5 to n. The values 500, 0.12 and 5 are the actual arguments, which becomes the values of the formal arguments inside the called function.

The actual and formal arguments should match in number, 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.

Arguments with return values:----- To assure a high degree of portability between programs, a function should generally be coded without involving any I/O operations. For example, different programs may require different output formats for display of results. These shortcomings can be overcome by handling over the result of a function to its calling function where the returned value can be used as required by the program.

            A self-contained and independent function should behave like a ‘black box’ that receives a predefined form of input and outputs a desired value. Such functions will have two way data communication as shown in figure:

            Function1()

            {

            -----------------

            Function2(a)

            -----------------

            ----------------

            }

            Function2(f)

            {

            --------------------

            ---------------------

            --------------------

            Return (e)

            }

No arguments but return a value:------ There could be occasion where you may need to design function that may not take any arguments but returns a value to the calling function. A typical example is the getchar function declared in the header file <stdio.h>. The getchar function has no parameters but it returns an integer type data that represents a character.

            You can design similar functions and use in our programs. Example:

            Int get_number(void);

            Main

            {

                        Int m = get_number();

                        Printf(“%d”, m);

            }

            Int get_number(void)

            {

                        Int number;

                        Scanf(“%d”, &number);

                        Return(number);

            }

Functions that return multiple values:----- normally functions return just one value using a return statement. That is because, a return statement can return only value. However, suppose that you want to get more information from a function. You can do this in C using the arguments not only to receive information but also to send back information to the calling function. The arguments that are used to “send out” information are called output parameters.

            The mechanism of sending back information through arguments is achieved using what are known as the address operator (&) and indirection operator(*). For example:

            Void marthoperation(int x, int y, int *s, Int *d);

            Main()

            {

                        Int x=20, y=10, s, d;

                        Mathoperation(x, y, &s, &d);

                        Printf(“s= %d\n d=%d\n”, s, d)

            }

            Void mathoperation (int a, int b, int *sum, Int *diff)

            {

                        *sum= a+b;

                        *diff=a-b;

            }

The actual arguments x and y are input arguments, s and d are output arguments. In the function call, while we pass the actual values of x and y to the function, we pass the address of locations where the values of s and d are stored in the memory. When the function is called the following assignments occur:

            Value of x to a

            Value of y to b

            Address of s to sum

            Address of d to diff

Note that indirection operator * in the declaration of sum and diff in the header indicates these variables are to store addresses, not actual values of variables. Now, the variables sum and diff point to the memory locations of s and d respectively. (The operator * is known as indirection operator because it gives an indirect reference to a variable through its address.) The variables *sum and *diff are known as pointers and sum and diff as pointer variables. Since they are declared as int, they can point to locations of int type data.

 

Return values: - A function may or may not send back any value to the calling function. If it does, it is done through the return statement. While it is possible to pass to the called function any number of values, the called function can only return one value per call, at the most.

The return statement can take one of the following forms.

            Return;

            Or

            Return (expression);

The first form of return does not return any value, it acts much as the closing brace of the function. When a return is encountered, the control is immediately passed back to the calling function. For example:

            If (error)

            Return;

The second form of return with an expression return the value of the expression. For example:

            Int mul(int x, int y)

            {

                        Int p;

                        P=x*y;

                        Return(p);

            }

A function may have more than one return statements. This situation arises when the value returned is based on certain conditions. For example:

            If (x<=0)

            Return(0);

            Else

            Return(1);

 

 What type of data does a function return? All functions by default return int type data. But what happens if a function must return some other type? We can force a function to return a particular type of data by using a type specifier in the function header. When a value is returned, it is automatically cast to the function’s type. For example,

            Int product (void)

            {

                        Return(2.5*3.0);

            }

Will return the value 7, only the integer part of the result.

 

Nesting of Functions: - C permits nesting of functions freely, main can call function1, which calls function2, which calls function3, ……… and so on. There is in principle no limit as to how deeply functions can be nested. For example:

            Float ratio (int x, int y, int z);

            Int difference (int x, int y);

            Main()

            {

                        Int a, b, c;

                        Scanf(“%d %d %d”, &a, &b, &c);

                        Printf(“%f \n”, ration(a, b, c));

            }

            Float ration(int x, int y, int z)

            {

                        If difference (y, z)

                        Return (x/(y-z));

                        Else

                        Return (0.0);

            }

            Int difference (int p, int q)

            {

                        If (p!=q)

                        Return (1);

                        Else

                        Return(0);

            }

 

           

Calling of Functions: A function can be called by simply using the function name followed by a list of actual parameters (or arguments), if any, enclosed in parenthesis. For example:

            Main()

            {         

                        Int y;

                        Y=mul(10, 5);             /* Function Call */

                        Printf(“%d\n”, y);

            }

When the complier 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. For example:

            Main()

            {

                        Int y;

                        Y=mul(10,5); /* call */

            }

                        Int mul(int x, int y);

            {

                        Int p;   /* local variable */

                        P=x*y;

                        Return (p);

            }

There are many different ways to call a function. Listed below are some of the ways the function mul can be invoked.

Mul(10 5)

Mul(m, 5)

Mul(10, n)

Mul(m, n)

Mul(m+5, 10)

Mul (10, mul(m, n))

Mul (expression1 expression2)

Note that the sixth call uses its own call as its one of the parameters. When we use expression, they should be evaluated to single values that can be passed as actual arguments.

           

Scope and life of variables- local and global variable:- The variable which has been declared before the main is called global variable. It can be used in all the functions in the program. It need not be declared in ither functions. A global variable is also known as an external variable. The variable which has been declared inside a function is called local variable. Local variables are visible and meaningful only inside the functions in which they are declared. They are not known to other functions.

            Variables in C differ in behaviour from those in most languages. For example, in a BASIC program, a variable retains its value throughout the program. It is not always the  case in C. It all depends on the storage class a variable may assume. The following variable storage classes are most relevant to functions:

  1. Automatic variables
  2. External variables
  3. Static variables
  4. Register variables

Automatic Variables:----- Automatic variables are declared inside a function in which they are to be utilized. They are created when the function is called and destroyed automatically when the function is exited, hence the name automatic. Automatic variables are therefore private (or local) to the function in which they are declared. Because of this property, automatic variables are also referred to as local or internal variables. For example:

            Main()

            {

                        Auto int number;

                        …………………

                        ………………….

            }

There are two consequences of the scope and longevity of auto variables worth remembering. First, any variable local to main will normally alive throughout the whole program, although it is active only in main. Secondly, during recursion, the nested variables are unique auto variables, a situation similar to function-nested auto variables with identical names.

External Variables:-----Variables that are both alive and active throughout the entire program are known as external variables. They are also known as global variables. Unlike local variables, global variables can be accessed by any function in the program. External variables are declared outside a function. For example:

            int number;

            float length = 7.5;

            main()

            {

            ------------------

            -------------------

            }

            function1()

            {

            ....................

            .....................

            }

            Function2()

            {

            ………………

            ……………….

            }

The variables number and length are available for use in all three functions.

Static Variables:------ As the name suggests, the value of static variables persists until the end of the program. A variable can be declared static using the keyword static like

            Static int x;

            Static float y;

A static variable may be either an internal type or an external type depending on the place of declaration.

            Internal static variables are those which are declared inside a function. The scope of internal static variables extend up to the end of the function in which they are defined. Therefore, internal static variables are similar to auto variables, except that they remain in existence (alive) throughout the remainder of the program. Therefore, internal static variables can be used to retain values between function calls. For example, it can be used to count the number of calls made to a function.

            Void stat(void);

            Main()

            {

                        Int I;

                        For (i=1; i<=3; i++)

                        Stat();

            }

            Void stat (void)

            {

                        Static int x=0;

                        X=x+1;

                        Printf (“x = %d\n”, x);

            }

            An external static variable is 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.

            It is also possible to control the scope of a function. For example, we would like a particular function accessible only to the functions in the file in which it is defined, and not to any function in other files. This can be accomplished by defining ‘that’ function with the storage class static.

Register Variables:----- We can tell the complier that a variable should be kept in one of the machine’s registers, instead of keeping in the memory (where normal variables are stored). Since a register access is much faster than a memory access, keeping the frequently accessed variables in the register will lead to faster execution of programs. This is done as follows:

            Register int count;

Although, ANSI standard does not restrict its application to any particular data type, most compliers allow only int or char variables to be placed in the register. Since only a few variables can be placed in the register, it is important to carefully select the variables for this purpose. However, C will automatically convert register variables into non-register variables once the limit is reached.

Storage Class Specified- Auto, Extern, Static, Register: - Variable in C can have not only data type but also storage class that provides information about their location and visibility. The storage class decides the portion of the program within which the variables are recognized. For example:

            Int m;

            Main()

            {

                        Int I;

                        Float balance;

                        ……………..

                        ……………..

                        Function1();

            }

            Function 1()

            {

                        Int I;

                        Float sum;

                        …………….

                        …………….

            }

C provides a variety of storage class specifiers that can be used to declare explicitly the scope and lifetime of variables. The concepts of scope and lifetime are important only in multifunction and multiple file programs. There are four storage class specifiers (auto, register, static, and extern) whose meaning are given in table:

Storage Class

Meaning

Auto

Local variables known only in the function in which it is declared. Default is auto.

Static

Local variable which exists and retains its value even after the control is transferred to the calling function.

Extern

Global variable known to all functions in the file.

Register

Local variable which is stored in the register.

 

The storage class is another qualifier that can be added to a variable declaration as shown below:

            Auto int count;

            Register char ch;

            Static int x;

            Extern long total;

Static and external (extern) variables are automatically to zero. Automatic (auto) variables contain undefined values (known as garbage) unless they are initialized explicitly.       

Arrays:- C supports a rich set of derived and user-defined data types in addition to a variety of fundamental types as shown below:

Data types

Derived Types

Fundamental Types

User-Defined Types

Arrays

Integer Types

Structures

Functions

Float Types

Unions

Pointers

Character Types

Enumerations

An array is fixed-size sequenced collection of elements of the same data type. It is simply a grouping of like-type data. In its simplest form, an array can be used to represent a list of numbers, or a list of names. For example:

  • List of temperatures recorded every hour in a day, or a month, or a year.
  • List of employees in an organization
  • List of products and their cost sold by a store.
  • Test scores of a class of students
  • List of customers and their telephone numbers
  • Table of daily rainfall data

And so on.

            Since an array provides a convenient structure for representing data, it is classified as one of the data structure in C. Other data structures include structures, lists, queues and trees. An array is a sequenced collection of related data items that share a common name. For instance, we can use an array name salary to represent a set of salaries of a group of employees in an organization. We can refer to the individual salaries by writing a number called index or subscript in brackets after the array name.

For example:

            Salary[10]

Represents the salary of 10th employee. While the complete set of values is referred to as an array, individual values are called elements. We can use arrays to represent not only simple lists of values but also tables of data in two or three or more dimensions. There are three types of array.

  • One-dimensional arrays
  • Two-dimensional arrays
  • Multidimensional arrays

One Dimensional Arrays:---- A list of items can be given one variable name using only one subscript and such a variable is called a single-subscripted variables or a one-dimensional array. In C, single-subscripted variable xi can be expressed as

            X[1], x[2], x[3]……………….x[n]

The subscript can begin with number 0. That is

            X[0]

Is allowed. For example, if we want to represent a set of five numbers, say (35, 40,20,57,19), by an array variable number, then we may declare the variable number as follows:

            Int number[5];

The subscripts of an array can be integer constants, integer variables like I, or expressions that yield integers.

Declaration of One-Dimensional Arrays : Like any other variable, arrays must be declared before they are used. The general form of array declaration is:

Type variable-name[size];

The type specifies the type of element that will be contained in the array, such as int, float or char and the size indicates the maximum number of elemwents that can be stored inside the array. For example:

            Float height[50];

declares the height to be an array to containing 50 real elements. Any subscripts 0 to 49 are valid.

            The C language treats character strings, simply as arrays of characters. The size in a character string represents the maximum number of characters that the string can hold. For example:

            Char name[10];

Declares the name as a character array (string) variable that can hold a maximum of 10 characters. When the complier sees a character string, it terminates it with an additional null character. Thus the element name[10] holds the null character ‘\0’. When declaring  character arrays, we must allow one extra element space for the null terminator.

Initialization of One-Dimensional Arrays:- After an array is declared, its elements must be initialized. Otherwise, they will contain “garbage”. An array can be initialized at either of the following stages

  • At compile time
  • At run time

Compile Time Initialization:------- You can initialize the elements of arrays in the same way as the ordinary variables when they are declared. The general form of initialization of array is:

            Type array-name[size]={list of values};

The values in the list are separated by commas. For example,

            Int number[3]={0,0,0};

Character arrays may be initialized in a similar manner. Thus, the statement

            Char name [ ]= {‘J’, ‘O’, ‘H’, ‘N’, ‘\0’};

declares the name to be an array of five elements, initialized with the string “John” ending with the null character.

Run Time Initialization:----An array can be explicitly initialized at run time. This approach is usually applied for initializing large arrays. For example,

            ---------------------

            ----------------------

            For (i=0; i<100; i=i+1)

            {

                        If (i<50)

                        Sum[i]=0.0;

                        Else

                        Sum[i]= 1.0;

            }

            ---------------------------

            ----------------------------

The first 50 elements of the array sum are initialized to zero while the remaining 50 elements are initialized to 1.0 at run time.

 

2D Arrays:-  We know that the array variables can store a list of values. There could be situations where a table of values will have to be stored. In mathematics, we represent a particular value in a matrix by using two subscripts such as vij. Here v denotes the entire matrix and vij refers to the value in the ith row and jth column. C allows us to define such tables of items by using two-dimensional arrays. Two-dimensional arrays are declared as follows:

            Type array_name [row_size][column_size];

Two-dimensional arrays are stored in memory as shown in figure:

 

Column 0

Column 1

Column 2

 

[0][0]

[0][1]

[0][2]

Row 0

310

275

365

 

[1][0]

[1][1]

[1][2]

Row 1

10

190

325

 

[2][0]

[2][1]

[2][2]

Row 2

405

235

240

 

[3][0]

[3][1]

[3][2]

Row 3

310

275

365

As with the single- dimensional arrays, each dimension of the array is indexed from zero to its maximum size minus one, the first index selects the rwo and the second index selects the column within that row.

Initializing Two-Dimensional Arrays:----- Like the one-dimensional arrays, two dimensional arrays may be initialized by following their declaration with a list of initial values enclosed in braces. For example:

            Int table [2][3] = {0,0,0,1,1,1);

Initializes the elements of the first row to zero and the second row to one. The initialization is done row by row. The above statement can be equivalent written as

            Int table [2][3] = {{0,0,0},{1,1,1}};

 3D Array:- C allows arrays of three or more dimensions. The exact limit is determined by the complier. The general form of a multi-dimensional array is:

            Type array_name [s1][s2][s3]……[sn];

Where s, is the size of the ith dimension. Some example are:

            Int survey [3][5][12];

            Float table [5][4][5][3];

Survey is a three-dimensional array declared to contain 180 integer type-elements. Similarly table is a four-dimensional array containing 300 elements of floating-point type.

ANSI C does not specify any limit for array dimension. However, most compliers permit seven to ten dimensions. Some allow even more.   

String:- 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. For example:

            “Man is obviously made to think.”

If you want to include a double quote in the string to be printed, then we may use it with a back slash as shown below.

            “\”Man is obviously made to think.\” said Pascal”.

For example,

            Printf(“\” Well Done !”\”);

will output the string “Well Done!”

Character strings are often used to build meaningful and readable programs. 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

Declaration and Initialization :- C does not support strings as a 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. The general form of declaration of a string variables is

            Char string_name[size];

The size determines the number of characters in the string_name. For example:

            Char city[10];

            Char name[30];

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 size should be equal to the maximum number of characters in the string plus one.

            Like numeric arrays, character arrays may be initialized when they are declared. C permits a character array to be initialized in either of the following two forms:

            Char city[9] = “ New York”;

            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.

 

String Function:- Fortunately, the C library supports a large number of string-handling functions that can be used to carry out many of the string manipulations:

Strcat:- The strcat function joins two strings together. It takes the following form:

            Strcat(string1, string2);

String1 and string2 are character arrays. When the function strcat is executed, string2 is appended to string1. It does so by removing the null character at the end of string1 and placing string2 from there. The string at string2 remains unchanged. For example:

            Part 1 = |v|        |E|        |R|       |Y|       | |        |\0|      | |        | |        | |       | |

            Part 2 = |G|      |O|        |O|        |D|        |\0|

            Part 3 = |B|      |A|        |D|        |\0|

Execution of the statement

            Strcat(part1, part2);

            Part 1 = |V|      |E|        |R|        |Y|        | |         |G|        |O|        |O|        |D|

            Part 2 = |G|      |O|        |O|        |D|        |\0|

While the statement

            Strcat(part 1, part 3);

Will result in:

            Part 1 = |V|      |E|        |R|        |Y|        | |         |B|        |A|        |D|

            Part 3 = |B|      |A|        |D|        |\0|

We must make sure that the size of string1( to which string2 is appended) is large enough to accommodate the final string.

 

Strcmp:- The strcmp function compares two strings identified by the arguments and has a value 0 if they are equal. If they are not, it has the numeric difference between the first nonmatching characters in the strings. It takes the form:

            Strcmp(string1, string2);

String1 and string2 may be string variables or string constants. For example:

            Strcmp(name1, name2);

            Strcmp(name1, “John”);

            Strcmp(“Rom”, “Ram”);

Our major concern is to determine whether the strings are equal; if not, which is alphabetically above. The value of mismatch is rarely important. For example, the statement

            Strcmp(“their”,”there”);

Will return a value of -9 which is the numeric difference between ASCII “I” and ASCII “r”. That is, “i” minus “r” in ASCII code is -9. If the value is negative, string1 is alphabetically above string2.

 

Strcpy:- The strcpy function works almost like a string-assignment operator. It takes the form

            Strcpy(string1, string2);

And assigns the contents of string2 to string1. String2 may be a character array variable or a string constant. For example, the statement

            Strcpy(city, “DELHI”);

Will assign the contents of the string variable city2 to the string variable city1. The size of the array city1 should be large enough to receive the contents of city2.

Strlen:- This function counts and returns the number of characters in a string. It takes the form

            N= strlen(string);

Where n is an integer variable, which receives the value of the length of the string. The argument may be a string constant. The counting ends at the first null character.

For example:  s1, s2 and s3 are three string variables. Write a program to read two string constant into s1 and s2 and compare whether they are equal or not. If they are not, join them together. Then copy the contents of s1 to the variables s3. At the end, the program should print the contents of all the three variables and their lengths.

            #include <string.h>

            Main()

            {

                        Char s1[20], s2[20], s3[20;

                        Int x, l1, l2, l3;

                        Printf(“\n \n Enter two string constants \n”);

                        Printf(“?”);

                        Scanf(“%s %s”, s1, s2);

                        X = strcmp(s1, s2);

                        If (x != 0)

                        {

                        Printf(“\n\n Strings are not equal \n”);

                        Strcat(s1, s2);

                        }

                        Else

                                    Printf(“\n\n Strings are equal \n”);

                        Strcpy(s3, s1);

                        L1 = strlen(s1);

                        L2 = strlen(s2);

                        L3 = strlen)s3);

                        Printf(“\n s1= %s\t length = %d characters\n”, s1, l1);

                        Printf(“\n s2 = %s\t length = %d characters\n”, s2, l2);

                        Printf(“\n s3 = %s \t length = %d characters\n”, s3, l3);

                        }

Output:

Enter two string constants

? New York

Strings are not equal

S1 = NewYork            length = 7 characters

S2 = York       length = 4 characters

S3 = NewYork            length = 7 characters

 

Strstr:- It is a two-parameter function that can be used to locate a sub-string in a string. This takes the forms:

            Strstr(s1, s2);

            Strstr(s1, “ABC”);

The function strstr searches the string s1 to see whether the string s2 is contained in s1. If yes, the function returns the position of the first occurrence of the sub-string. Otherwise, it returns a NULL pointer. Example

            If (strstr(s1, s2) = = NULL)

            Printf (“ substring is not found”);

            Else

            Printf(“s2 is a substring of s1”);

No comments:

Post a Comment