C Program Learning Part-9 - Engineer Simple

Search This Blog

C Program Learning Part-9

 Character Arrays and Strings

Declaration and Initializing String Variables: 

C does not support strings as a data type. It allows us to represent strings as character arrays. The general form of declaration of a string variable is:

C Program Exercise Part-09


char string_name[size];

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

char city[10];

char name[30];

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’};

Reading String from Terminal:

The familiar input function scanf can be used with %s format specification to read in a string of character. Example:

char address[10]

scanf(“%s”,address);

If the following line of text is typed in at the terminal

NEW YORK

then only the string “NEW” will be read into the array address, since the blank space after the word “NEW” will terminate the reading of string. The address array is created in the memory as shown below:

N

E

W

\0

?

?

?

?

?

?

  0             1               2               3                4              5                  6              7            8                   9

If we want to read the entire line “NEW YORK”, then we may use two character arrays of appropriate sizes. That is,

char adr1[5],adr2[5];

scanf(“%s %s”, adr1,adr2);

String Handling Function:

strcat() Function:

The strcat function joins two strings together. It takes the following forms:

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 the string1 and placing string2 from there. The string at string2 remains unchanged. 

For example, consider the following three strings:

 

                   0          1         2           3        4        5             6          7            8            9        0            1          

Part1=

V

E

R

Y

 

\0

 

 

 

 

 

 

Part2=

G

O

O

D

\0

 

 

 

                      0               1            2            3                  4                    5                   6

Part3=

B

A

D

\0

 

 

 

Execute the statement: strcat(part1, part2);

Will result in

 

                     0            1          2           3             4        5             6          7            8            9        0            1           

Part1=

V

E

R

Y

 

G

O

O

D

\0

 

 

strcmp() Function:

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 non matching characters in the strings.

It takes the form:

strcmp(string1, string2);

string1 and string2 may be string variableor string constants. Examples are:

strcmp(name1,name2);

strcmp(name1, “john”);

strcmp(“Rom”, “Ram”);

strcpy() Function:

The strcpy function worksalmost like a string assignment operator.

It takes the form:

strcpy(string1, string2);

and assignthe content of string2 to string1.

For example, the statement strcpy(city, “DHAKA”);

will assignthe string “DHAKA” to the string variablecity.

strlen() Function:

This function counts and returns the number of character 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.

strncpy() Function:

It copies only the left-most n characters of the source string to the target string variable. This is a three parameter function and is invoked as follows:

strncpy(s1, s2, 5);

This statement copies the first 5 characters of the source string s2 into the target string s1. Since the first 5 characters may not include the terminating null character, we haveto place it explicitly in the 6 th position of s2 as shown below:

s1[6] = ‘\0’ ;

Now s1 contains a proper string.

strncmp Function:

This function has three parameters as illustrated below:

strncmp(s1, s2, n);

this compares the left most n characters of s1 to s2 and returns.

(a) 0 if they are equal

(b) negative number, if s1 sub-string is less than s2; and

(c) positive number, otherwise.

strncat Function:

This is concatenation function that takes three parameters as shown below;

strncat(s1, s2, n);

This call will concatenate the left most n characters of s2 to the end of the s1.

Example

                     0            1          2           3             4        5             6          7            8            9        0            1          

s1=

B

A

L

A

\0

 

 

 

 

 

 

 

 

 

                      0            1          2           3             4        5             6          7            8           

s1=

G

U

R

U

S

A

M

Y

\0

After strncat(s1, s2, 4); execute

 

 

                             0            1            2         3                  4          5              6          7            8           

s1=

B

A

L

A

G

U

R

U

\0

 

What is Header Files?

Header files are helping file of C program which holds the definitions of various functions and their associated variables that needs to be imported into C program with the help of pre-processor #include statement. All the header file have a '.h' an extension that contains C function declaration and macro definitions. In other words, the header files can be requested using the preprocessor directive #include. The default the header file that comes with the C compiler is the stdio.h. Including a header file means that using the content of header file in your source program. A straightforward practice while programming in C or C++ programs is that you can keep every macro, global variables, constants, and other function prototypes in the header files. The basic syntax of using these header files is:

Syntax:

#include<file>

Library Function:

We have used printf function to print something on screen and the function definition is defined by the complier. We simply call the function when we need in our program. Hence we need to use #include so that it can provide function prototype for that function. Such kind of function is called library function. For example:

clrscr(), scanf(),sqrt(), strcat()etc.

User Defined Function:

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 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. This independently coded programs are called functions or user defined functions.

An example :

#include<stdio.h>

#include<stdlib.h>

void printline(void);

int main()

{

printline();

printf("Hello world!\n");

printline();

 }

void printline(void)

{

int i;

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

{

printf("-");

}

printf("\n");

}


Elements of user defined functions:

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

1. Function definition

2. Function call

3. Function declaration

Definition of Functions:

A function definition shall include the following elements:


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

function_type function_name(parameter list)

{

local variable declaration;

executable statement1;

executable statement2;

…………

………….

return statement;

}

Function Calls:

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”,y);

}

When the complier encounters a function call, the control is transmitted to the function mul(). This function is then executed line by line and a value is returned when a return statement is encountered. This value is assigned to y. This is illustrated below:

main()

{

int y;

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

printf(“%d”,y);

}

int mul( int x, int y)

{

int p;            /* Local variable */ 

p = x * y;        /* x =10, y = 5 */

return (p);

}

What is 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 calls itself. A very simple example of recursion is presented below:

main()

{

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

main();

}

When executed, the program will produce a output something like this:

This is an example of recursion

This is an example of recursion

 

Write a program for Factorial of a number?

long factorial(int n);

void main()

{

int number;

long fact;

printf(“Enter a number:”);

scanf(“%d”, &number);

fact =factorial(number);

printf(“Factorial of %d is %d\n”, number, fact);

}

long factorial(intn)

{

if(n == 1)

{

return 1;

}

else

{

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

}

}

 


Next Post Previous Post
No Comment
Add Comment
comment url