Strings, Functions&Pointers
Strings, Functions&Pointers
So far you learn how to define arrays of one and two dimensional,how to initialize arrays, and how
to read and write strings.with this knowledge ,you should be ready to handle strings.
A string is a series of characters enclosed within the double quotations marks. A string may be
include letters ,digits, and various special characters such as +, -, *, / and $. String constants also
reffered as strings literals. All of the following are valid C literals:
“abcd”
“\””\n”
“ “
A double quote included in the literals as “\” regarded as part of the literal and not as deliminitor.
A pair of double quotes with nothing between them is called the NULL STRING. IT is stored as null
string and has length of 0.
C has no built-in string data type. A string in C is defined as an array of characters ending int the null
characters ending int the null character(“\0”). A string is an array of characters.The elements of the
characters array are stored in contiguous memory allocation. Strings are used in the programming
languages to manipulate text such as word and sentences.
A string variable must be declared as an array using the following general form:
char name[20];
char color[8];
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 int the string plus one.
Char city[]=”HYDERABAD”
The above declaration initialize a variable to the string “HYDERABAD”. It creates a 10-element array
city containing the characters .’H’,’Y’,’D’,’E’,’R’,’A’,’B’,’A’,’D’ and ‘\0’. The declaration
Char city[]=”HYDERABAD”
Each character in the array occupies one byte of memory. When declaring character array to
contain a string, the array must be large enough to store this string and its terminating null
character. The above declaration automatically determines the size of the array based on the
number of initializers in the initializer list.
Char city[10]=”HYDERABAD”;
H Y D E R A B A D
1.The scanf function can be used with %s format specification to read in a string of characters.
Scanf(“%s”,city);
Note that the array name is is used without a subscript and there is no ampersand (&) before the
array name. When an array name is specified in this manner, no & should be used .
The problem with the scanf function is that it is not capable of receiving multiword strings. The scanf
function is used only to read a single word at a time, where a word is define as being a sequence of
characters without any embedded white space.
Then only the string ”new” will be read into the array city , since the blank space after the word
‘new’ will terminate the string . The solution to this problem is to use gets () function .
If you wish to read in blanks as part of a string , you must use the %c conversion specifications.
Remember that if %c is used , the corresponding variable must be a single (subscripted)array
element preceded by an &.
2. The getchar function is used to read a single character at a time and never a string from the
keyboard.
The gets() function is used to read characters entered at the keyboard until you press enter any
key.Thus,spaces and tabs are perfectly acceptable as part aof the input string.The carriage return is
not stored,but replaces the\n with \n.
Gets(variable name);
3.1.4 Writing strings to screen
The printf function with %s conversion specification can be used to print strings on the
screen.The specification %s displays an array of characters that is terminated by the null
character.
For example,the statement
Printf(“%s”,city);
Can be used to display the entire contents of the array name.
There is a much easier way to display a string using printf(). Since the argument city to
printf() is a string,you simply use citty without any index as follows:
Printf(city);
If you wish to output a new line, you could output city like this:
Printf(“%s\n”,city);
Like the other specifications,%s can be used with a field width specifier and the minus sign
for left justification.for example,specification
%-12.6s
Indicates that the string is truncated to six characters and then printed left justified in a field
width of 12 colomns.
3.1.4.1 puts() function
The puts() function works exactly opposite to gets() function .it output a string to the
screen from memory that is from the array we declare until it reaches the null character.
The general form of the puts() function is
Puts(variable name);
it automatically appends a carriage return . The main reason to use puts() instead of printf()
to output a string is that puts() is much smaller and faster. Both gets() and puts() functions
use the header file stdio.h
3.2 .CHARACTER-HANDLING FUNCTIONS :-
The character handling functions perform useful tests and manipulations of charactered data .
each function receives a character –represented as an int-or EOF as an argument. EOF (END OF
FILE) normally has the value -1. The character handling functions manipulate characters as
integers. The character functions are contained in the header file ctype.h and therefore the
statement
#include<ctype.h>
Must be included in the program.
Character handling functions
Function isdigit determines whether the argument is a digit (0-9). Function isalpha determines
whether the argument is an uppercase letter (A-Z) or a lowercase letter(a-z). function isalnum
determines whether its arguments is an uppercase letter, a lowercase letter or digit. Function
islower determines whether its arguments is a lowercase letter(a-z). function isupper determines
whether its arguments is a uppercase letter(A-Z).
The string handling functions are contained in the header file string.h and therefore the statement
#include<string.h>
The c library supports a large number of string functions for string manipulations as below:
FUNCTION USE
Strcat Appends one string at the end of another.
Out of these functions we shall discuss the functions strcat(),strcmp(),strcpy(), and strlen(), since
these are the most commonly used functions .
The strcat(string concantation) function joins two strings to form a third string.
Strcat(string1,string2);
Where string1, and string2 are characters arrays. This function appends array string2 to array
string1 and terminates string1 with the null. The character originally ending string1 is overwritten by
the character of string2. The string to string2 remains unchanged. The strcat() functions returns
string1.
We must make sure that the size of string1 must be large enough to hold the concatated string( that
is,both the string1 and string2 together).
Strcat function may also append a string constant to a string variable. For example,
Strcat(string1,”pongal”);
Also we can concatenate more than one string by using nested concentration:
Strcat(strcat(string1,string2),string3);
Strncat(string1,string2,n);
When this function is executed ,first n characters of string2 is appended to string1. The first
character of string2 overwrites the terminating null charcter of string1. The value of string1 is
returned.
Concantates all three strings s1,s2 and s3 together. The resulting string is stored in s1.
Strcpy(string1,string2);
The strcpy(string copy) function is used to copy the contents of string2 into string1. The following
program segment will copy “This is a message” into string str.
Char str[30];
Strcpy(str,”This is a message”);
It general form is
Strncpy(string1,string2,n);
This function is used to copy the first n characters of string2 into array string1. The contents of
string1 are returned.
The strcmp(string comparision) function compares two strings to find out whether they are Same
or different.
Where string1 and string2 are characters arrays or strings constants. This function returns an
integer. Functions strcmp compares the first string argument string1 with its second string
arguments string2 character by character. The function returns a value zero if the two strings are the
same , a negative value if string1 is less than string2 and a positive value if string1 is greater than
string2.
The two strings are compared character by character lexicographically;that is in dictionary order
until there is mismatch or end of one of the strings is reached ,whichever occurs first. Therefore , a
string is said to be less than another when it comes before other is an alphabetized listening (that is
in dictionary ). The comparison is not based upon the length of the string. Also the comparison is
case-sensitive ,lowercase characters being greater than upper case. The value returned by strcmp
function usually is the numeric differences between the ASCII values of the unequal characters.
Strcmp(“be”,”btech”)’
Will return the value of -15 which is the numeric difference between ASCII “e” and ASCII “t”.
The strncmp function is equivalent to strcmp, except that strncmp compares up to a specified
number of characters. This function does not compare characters following a null characters in a
string .
Strncmp(string1,string2,n);
The strlen() function returns an integer specifies the number of characters in the string. That is, it
returns length of the string. It takes the form:
Strlen(string);
This functions does not count the null character. For example ,the statements
Strlen(“test”);
char name[15][12];
To access a string within a string table ,specify only first index. For example , to read a string from
the keyboard into the second string in name, use this statement.
Gets(name[1]);
Therefore , the syntax for accessing a particular string is name[i]; here, we do not need the second
index. Since a two-dimensional array is an array of arrays, we can access elements of the “outer”
array, each of which is an array, individually. To do this we don’t need the second index. This shows
that once an array is declared as two-dimensional ,it can be used like a one-dimensional array in the
further manipulations.
INTRODUCTION:
C functions can be classified in to two categories ,namely, library and user defined functions. The
functions supplied with the system are the library functions(already discussed). User –developed
functions are called user defined functions. Main is an example of user-defined functions .scanf and
printf belong to the category of library functions. The main() function is invoking other functions
belong to other functions to perfom the task. We have used other library functions such as sqrt,
pow, strlen, etc. instead of each user writing these functions , C compiler provide this built-in library
functions as a convenience to the users. The C standard library makes the programmer job easier
because the library functions provides many of the capabilities programmer need. The C standard
library cannot contain all the functions in all applications areas. This chapter is devoted to the
discussion of preparing and using the programmers own function. The main difference between the
library function and the user-defined functions is that library functions are not required to be
written by the user whereas a user-defined functions has to be developed by the user to define
specific task that may be used in to many points in a program. Later , a user-defined function can be
compiled into libraries and distributed. To the users of the library, these functions will act as library
functions. That is , these functions are predefined and precompiled ; the users need not worry about
hoe the functions work internally. Functions are main building blocks of “C” language.
NEED OF A FUNCTION
ADVANTAGES OF FUNCTIONS
1. Using functions one can avoid rewriting the same code again and again.
2. It is easy to write a function that does a particular job.
3. It facilitates top-down modular programming. In other words , the complexity of the entire
program can divide into simple subtasks and function subprograms can be written for each
sub tasks.
4. Efficient ,clear and compact source code.
5. The length of the source program can be reduced.
6. Saving memory space.
7. Easier to write, testing and debugging individual functions.
8. It increases program readability and helps documentation.
9. A function can be shared by others programs by compiling it separately and loading them
together.
10. In C, a function can call itself again. It is called recursiveness. Many calculations can be done
easily using recursive process such as calculations of sum of natural numbers, factorial of a
number, etc..
Argument declaration;
statements1;
statement2;
……………….
………………..
return(expression);
Here , type specifies the type of data that the function returns. A function may returns any type of
data except an array. The type, argument list and it associated argument declaration parts are
optional. An unspecified type is always assumed by the compiler to be int. in other words, int is
the default type when no type is specifier is present. However , when a functions returns a type
other than int , it must be explicity delared.
The function_name is any valid identifier. The argument list contains valid variables names are
separated by commas. The argument variables receive values from calling function. Thus they
provide the link between the main program and the function. Arguments are also known as
parameters. The parmeters provides the means for communicating information between functions.
We have two types of arguments :formal argument (or dummy argument) and actual arguments.
The formal arguments are defined in the function declaration in the calling function. The
data,which are passed from the calling function to the called function are called actual arguments.
The actual arguments are passed to the called function through a function call. A function maybe
without arguments,in which case the arguments list is empty. However ,even if there are no
arguments , the parentheses must be present. All argument variables must be declared for their
types after the function header and before the opening brace of the function body.
EXAMPLE:-
sum(a,b,c)
int total;
total=a+b+c;
return(total);
A function may or may not send a value back to the calling function. This value which is sent to the
calling function is the return value of the function. It is achieved through the return statement.
The return statement returns a value to the calling function. In the above function , the return
statement returns the value of total to main(). When a return statement is encountered, the
control is immediately passed back to the calling function.
The first line of the function is called the function header. The declaration and statements within
braces from the function body. The function body is also referred to as a block. A block is simply a
compound statement that may include declarations. Remember that a function can not be defined
inside another function under any circumstances. In C ,each function is declared almost like a main()
function,
A function can have any number of executable statements. A function that does nothing, may not
include any executive statements at all. For example:
Do_nothing() {}
CHARACTERISTICS OF A FUNCTION
Arguments to a function are usually passed in two ways. The first one is known
as(sending the values to the arguments)passing by value or call by value. When a single
value is passed to a function via an actual argument, the value of the actual is copied into
the function. Therefore , the value of the corresponding formal arguments can be changed
within the function, but the value of the actual arguments within the calling function will
not change. This procedure for passing the value of an argument of a function is known as
call by value. The second method is known as call by reference, in which the address of
each argument is passed to the function. By this method, the changes made to the
parameters of the function will effect the variables which called the function.
1. Call by value:
Call by value mechanism doesnot change the contents of the arguments variable in
the calling functions , even if they are changed in the calling function. This is because the
contents of the actual arguments in a calling function are copied to the formal
arguments in the called function. Any modifications made in the called function have a
reflect to the calling function.
2. Call by reference:
In this mechanism , instead of passing the value , the address of the arguments is
passed to a function. In the function, the address of the arguments is copied into the
memory location instead of the value. The dereferencing operator(*) is used t access the
variable in the called function. Any modifications made in the called function have
reflected to the calling function.
Information is returned from the function to the calling portion of the program via the return
statement.
The return statement also causes control to be returned to the point from which the function was
called.
A function may or may not send back any value to the calling function. It is an optional statement. It
absence indicates that no value is being returned to the accessing function.
The first form of return does not return a value. If the function does not return the result , control is
returned simply when the function-ending right brace {} is reached, or by executing the statement.
return;
The second form of return with an expression returns the value of expression to the caller. Thus , a
function can return only one value at a time to the accessing function via return.
Return 0;
Return(x*x);
Return(max);
Return ‘c’;
Return “true”;
Return sum;
Return 5.6+3.9;
A function can include any number of return statements, each containing a different expression.
However ,for every call ,only one of the returned. The return statement need not always be present
at the end of the function. It cn be placed anywhere in the function ; as soon as it is encountered ,
control will return to the calling program. Remember that in a function two return statements
should never occur successively.
CALLING A FUNCTION
A function can be called by specifying function 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 function’s name. in otherwords, a function gets called
when the function name is followed by a semicolon.
For example:
main()
message();
}
A function can be called any number of times. A functions which returns values can be used in
expressions like any other variable. A function that does not return any value cannot be used in an
expression.
Any function can be called from any other function. Even main() can be called from other functions.
FUNCTION CATEGORIES
A function , depends on whether arguments are present or not and whether a value is returned or
not, may belong to one of the following categories:
It is the simplest way of writing a user defined function in C. when a function has no
arguments, it does not receive any data from the data from the calling function. Similarly , when it
does not return a value , the calling function doesnot receive any data from the called function. In
effect, there is no data communication between a calling function and a called function.
These functions have some arguments which are passed to a function but the function does
not return back any value to the accessing function. It is a one way Data communication between
calling function and the called function.
These functions have a some arguments and are passed to a function from the calling
program and the computed values, if any, are transferred back to the called function. It is a two way
data communication between the calling function and the called functions. These functions receive a
predefined form of input and output a desired value .
There is no restriction in passing any number of values to a function; the restriction is only in the
return a value s from a function. Arrays can be passed to a function without any difficult , one
element at atime.
As ordinary variable with value , it is also possible to pass the values of an array element and even
an entire array as an argument to a function.
To pass an entire array to a function , it is only necessary to list the name of the array , without
brackets or subscripts , as an arguments within the function call. In otherwords, pass the whole
array , we simply use the array name as the actual parameter. In the called function , we declare that
the corresponding formal parameter in an array. When declaring a one dimensional array as a formal
argument, the array name is written with apair of empty square brackets. We do not need to specify
the number of elements within the formal argument declaration.
Remember that when an array is passed to a function as an argument , only the address of the first
element of the array is passed, but not the actual values of the array elements. This address is
assigned to the corresponding formal arguments when the function is called. The formal argument
therefore becomes pointer to the first element of the array. Arguments that are passed in this
manner are said to be passed by reference rather than by value.
Syntax:-
Statements;
A two-dimensional array elements may be passed to ab function jast as any ordinary variable or
one dimensional array element can.
An entire two-dimensional array can be passed to a function the same way that one – dimensional
array can. You simply list the name of the array.
When declaring a two-dimensional array as a formal parameter inside a function, the number of
rows in the number of columns in the array may be omitted, but the declaration must contain the
number of coumns in the array. To indicate arguments for a function is two-dimensional array, one
has to follow the syntax:
Here type represents the type of data returned by a function, function_name represents the
function name, and type1, type2,…,typen represents the data type of the arguments arg1, arg2,
….,argn.
The functions big and small do not return value and therefore the function small was
not delared in the main(). In C , such functions are called void functions. We can declare
it in the main() with the qualifier void.
If a function does not return value , you can declare it as void. This tells the compiler that the
function does not return value.
USE OF VOID()
RECURSION
Recursion is the process of defining something in terms of itself. This technique has been
implemented in recent high level languages only. The “C” language supports recursion. In C,
recursion means that a function calls itself repeatedly, but which halts at some point of avoid infinite
recursion. Such a function is known as recursive function. There is much difference between the
normal function and recursive function. The normal function will be called by the main() function
whenever the function name is used. On the otherhand, the recursive function will be called by
itself repeatedly,until some specified condition has been satisfied. This concept can be explained by
taking an example. This technique is used to solve problems whose solution is expressed in terms of
successively applying the same set of steps.
Definition:- A function, which invokes itself repeatedly until some condition is satisfied , is
called a “recursive function”.
ADVANTAGES OF RECURSION
DISADVANTAGES OF RECURSION
Local variables:-
Variables declared within the function are called “local variables”-they are known only in the
functions in which they are declared. They are not known to other functions.
Global variables:-
Variables are declared outside all the functions are called”global variables” and they may be
accessed by any function in the program. It need not be declared in the other functions. Usually,
global variables in C are declared at the beginning of a program, before the definition of the main
function. A global variable is also known as external variable. Global variables are declared.
2. These are known only in the functions These are declared at the beginning of
in which they are declared. the program before the main() function.
3. These are not known to other These variables may be accessed by any
functions i.e., scope is within the function i.e.,scope is throughout the
function. program.
4. The local variables in one function These variables provide two-way
have no relationship to the local communication among functions.
variables in another function.
POINTERS
INTRODUCTION
This chapter covers one of the most powerful features of C language, the pointer. Pointer are
used frequently in C, as they have a number of advantages. Some reasons to use pointers are as
follows:
1. Pointers enables us to access a variable that is defined outside the function. This is
because the memory addresses are global to all functions , whereas local variables
names are meaningful only within the functions in which they are declared.
2. Pointers reduce the length and complexity of a program. That is, pointers are used for
saving memory.
3. Pointers provide a way of return more than one value from a function.
4. Pointers can be used to pass arrays and strings more conveniently from one function to
another function.
5. Pointers are enables us to create and manipulate dynamic data structures.
6. Pointers are also closely associated with arrays and therefore provide an alternate way
to access individual array elements.
7. Pointers increase the program execution speed.
8. Pointers provide us dynamic memory allocation.
UNDERSTANDING POINTERS
We know that variables are stored in memory. The computers memory is a sequential collection of
memory cells. Each cell, commonly known as a byte , has a numeric address. The memory cells are
arranged in increasing order of addresses, starting from 0, and increases one by one. The last
address depend on the memory size.
Whenever we declare a variable , appropriate memory allocated to the variable by the compiler to
hold the value of the variable. This memory location will have its own address number.
This statement tells the C compiler to perform the following actions:
DEFINITION- POINTERS:
A pointer is a special type of variable , which contains the memory address of another
variable. That is , a pointer points to another variable , by storing its memory address.
A pointer is a variable that holds the memory address of other variable as it value.
Hence ,a variable name directly reference a value and a pointer indirectly references a value.
References a value through a pointer is called indirection. Pointers, like any other variables, must be
declared before they can be used. It is declared in a special way of preceding a “*” before the name
of the variable as shown in below.
The general form to declare a pointer variable is
Where data type is the base type of the pointer. It specifies the type of the object that the pointer
can pointer can point to. The asterisk before the variable name tells the compiler that a pointer
variable is being created. The declaration
Int *x,y;
States that ‘x’ is a pointer variable and is going to contain the address of a variable which is of
integer type(i.e.., a pointer to an integer value) and is read,”x is a pointer to int “, or “x points to an
object of type integer “. Also , the variable y is declared to be an integer, not a pointer to an
integer. The * only applies to x in the declaration. When * is used in this manner in a declaration , it
indicates that the variable being declared is a pointer. Similarly , the declaration
Float *a;
Initializing pointers
Pointers should be initialized either when they are declared (i.e., in the declaration itself) or in an
assignment. A value cannot be assigned to a pointer variable directly as an ordinary variable.
Instead it must be assigned a value of a variable which is already declared. A pointer variable can be
first declared and later assigned a value as shown below.
Int a;
Int *b;
b=&a;
In the above example the pointer variable ‘b’ is first declared and then the address of the variable is
assigned to it as value using the ‘&’ operator. A pointer can also be initialize at the place of
declaration as shown below.
Int a;
Int *b=&a;
A pointers may be initialized to 0, null or an address. Pointers with the value Null points to nothing.
NULL is a symbolic constant of defined in the header files(such as<stdio.h>). Initializing a pointer
to 0 is equivalent to initializing a pointer to null , but null is preferred. The value 0 is the only integer
value that can be assigned directly to a pointer variable.
We have already seen in the C language the elements of arrays can be accessed through index
manipulations. But “C” also provides a special way of array handling through pointers. There is a very
closer relation between arrays and pointers. An array name is a variable that can appear on the left
side of an assignment operator. Note that the array in C have the index 0. The array name without
an index has special meaning in C; it represents the address of the first element (index 0) of the
array.
Int a[5]={4,6,5,7,2};
When you use an array without an index, you are generating a pointer to the start of the array. This
is why no indexes are used when you read a string using gets() function . the gets() function is used
the pointer to load the array it points to with characters you enter at the keyboard.