BASICS OF THE LANGUAGE

WHERE C STANDS

All the programmming languages can be divided into two categories:

a)Problem oriented languages or High-level languages.These languages have been designed to give a better programming efficiency.i.e. faster program development.e.g. FORTRAN,BASIC,PASCAL etc.

b)Machine oriented languages or low-level languages.these languages have been designed to give a better machine efficiency.i.e. faster program execution.e.g. Assembly language and machine language.

C stands in between these two categories.that's why it is often called "MIDDLE LEVEL LANGUAGE"

Getting started with C



The only way to learn a new programming language is by writing programs in it.
The first program to write is the same for all languages:
Print the words:
hello, world This is a big hurdle; to leap over it you have to be able to create the program text somewhere, compile it successfully, load it, run it, and find out where your output went. With these mechanical details mastered, everything else is comparatively easy. In C, the program to print "hello, world" is

#include
main()
{
printf("hello, world\n");
}


Just how to run this program depends on the system you are using. As a specific example, on the UNIX operating system you must create the program in a file whose name ends in ``.c'', such as hello.c, then compile it with the command cc hello.c .If you haven't botched anything, such as omitting a character or misspelling something, the compilation will proceed silently, and make an executable file called a.out. If you run a.out by typing the command a.out it will print hello, world On other systems, the rules will be different; check with a local expert. Now, for some explanations about the program itself. A C program, whatever its size, consists of functions and variables. A function contains statements that specify the computing operations to be done, and variables store values used during the computation. C functions are like the subroutines and functions in Fortran or the procedures and functions of Pascal. Our example is a function named main. Normally you are at liberty to give functions whatever names you like, but ``main'' is special - your program begins executing at the beginning of main. This means that every program must have a main somewhere. main will usually call other functions to help perform its job, some that you wrote, and others from libraries that are provided for you. The first line of the program,
#include
tells the compiler to include information about the standard input/output library; the line appears at the beginning of many C source files. One method of communicating data between functions is for the calling function to provide a list of values, called arguments, to the function it calls. The parentheses after the function name surround the argument list. In this example, main is defined to be a function that expects no arguments, which is indicated by the empty list ( ).
#include ..........include information about standard library
main() ...........define a function called main that received no argument values
{ ...............statements of main are enclosed in braces
printf("hello, world\n"); ..........main calls library function printf to print this sequence of characters
} ..............\n represents the newline character
The statements of a function are enclosed in braces { }. The function main contains only one statement,
printf("hello, world\n");
A function is called by naming it, followed by a parenthesized list of arguments, so this calls the function printf
with the argument "hello, world\n". printf is a library function that prints output, in this case the string
of characters between the quotes.
A sequence of characters in double quotes, like "hello, world\n", is called a character string or string
constant. For the moment our only use of character strings will be as arguments for printf and other functions.
The sequence \n in the string is C notation for the newline character, which when printed advances the output to the left margin on the next line. If you leave out the \n (a worthwhile experiment), you will find that there is no line advance after the output is printed. You must use \n to include a newline character in the printf argument;
if you try something like
printf("hello, world"
);
the C compiler will produce an error message.
printf never supplies a newline character automatically, so several calls may be used to build up an output line
in stages. Our first program could just as well have been written


#include
main()
{
printf("hello, ");
printf("world");
printf("\n");
}


to produce identical output.
Notice that \n represents only a single character. An escape sequence like \n provides a general and extensible mechanism for representing hard-to-type or invisible characters. Among the others that C provides are \t for tab, \b for backspace, \" for the double quote and \\ for the backslash itself.

Types of C Constants

C constants can be divided into two major categories:
(a)Primary Constants
(b)Secondary Constants
primary constants :Integer constants,Real constants,Character constants
secondary constants :Array,pointer,structure,union,Enum etc.

Rules for Constructing Integer Constants

(a)An integer constant must have at least one digit.
(b)It must not have a decimal point.
(c)It can be either positive or negative.
(d)If no sign precedes an integer constant it is assumed to be positive.
(e)No commas or blanks are allowed within an integer constant.
(f)The allowable range for integer constants is -32768 to 32767.


Truly speaking the range of an Integer constant depends upon the compiler.
For a 16-bit compiler like Turbo C or Turbo C++ the range is –32768 to 32767.
For a 32-bit compiler the range would be even greater. Question like what exactly do you
mean by a 16-bit or a 32-bit compiler, what range of an Integer constant has to do with the
type of compiler and such questions are discussed in detail in Chapter 16. Till that time it
would be assumed that we are working with a 16-bit compiler.
Ex.: 426
+782
-8000
-7605

Rules for Constructing Real Constants

Real constants are often called Floating Point constants. The real constants could be written
in two forms—Fractional form and Exponential form.
Following rules must be observed while constructing real constants expressed in fractional form:

(a)A real constant must have at least one digit.
(b)It must have a decimal point.
(c)It could be either positive or negative.
(d)Default sign is positive.
(e)No commas or blanks are allowed within a real constant.

Ex.: +325.34
426.0
-32.76
-48.5792

The exponential form of representation of real constants is usually used if the value of the constant is either too small or too large. It however doesn’t restrict us in any way from using exponential form of representation for other real constants. In exponential form of representation, the real constant is represented in two parts. The part appearing before ‘e’ is called mantissa, whereas the part following ‘e’ is called exponent.
Following rules must be observed while constructing real constants expressed in exponential form:

(a)The mantissa part and the exponential part should be separated by a letter e.
(b)The mantissa part may have a positive or negative sign.
(c)Default sign of mantissa part is positive.
(d)The exponent must have at least one digit, which must be a positive or negative integer. Default sign is positive.
(e)Range of real constants expressed in exponential form is -3.4e38 to 3.4e38.

Ex.: +3.2e-5
4.1e8
-0.2e+3
-3.2e-5

Rules for Constructing Character Constants

A character constant is a single alphabet, a single digit or a single special symbol enclosed within single inverted commas.
Both the inverted commas should point to the left. For example, ’A’ is a valid character constant whereas ‘A’ is not.
The maximum length of a character constant can be 1 character.
Ex.: 'A'
'I'
'5'
'='

Types of C Variables

As we saw earlier, an entity that may vary during program execution is called a variable. Variable names are names given to locations in memory. These locations can contain integer, real or character constants. In any language, the types of variables that it can support depend on the types of constants that it can handle. This is because a particular type of variable can hold only the same type of constant. For example, an integer variable can hold only an integer constant, a real variable can hold only a real constant and a character variable can hold only a character constant. The rules for constructing different types of constants are different. However, for constructing variable names of all types the same set of rules apply.
These rules are given below.


Rules for Constructing Variable Names

(a)A variable name is any combination of 1 to 31 alphabets, digits or underscores.
(b) Some compilers allow variable names whose length could be up to 247 characters. Still, it would be safer to stick to the rule of 31 characters.
(c)Do not create unnecessarily long variable names as it adds to your typing effort.
(d)The first character in the variable name must be an alphabet or underscore.

No commas or blanks are allowed within a variable name. No special symbol other than an underscore (as in gross_sal) can be used in a variable name.


Ex.: si_int
m_hra
pop_e_89

These rules remain same for all the types of primary and secondary variables. Naturally, the question follows... how is C able to differentiate between these variables? This is a rather simple matter. C compiler is able to distinguish between the variable names by making it compulsory for you to declare the type of any variable name that you wish to use in a program. This type declaration is done at the beginning of the program.

Following are the examples of type declaration statements:
Ex.: int si, m_hra ;
float bassal ;
char code ;

Since, the maximum allowable length of a variable name is 31 characters, an enormous number of variable names can be constructed using the above-mentioned rules. It is a good practice to exploit this enormous choice in naming variables by using meaningful variable names. Thus, if we want to calculate simple interest, it is always advisable to construct meaningful variable names like prin, roi, noy to represent Principle, Rate of interest and Number of years rather than using the variables a, b, c.


C Keywords
Keywords are the words whose meaning has already been explained to the C compiler (or in a broad sense to the computer). The keywords cannot be used as variable names because if we do so we are trying to assign a new meaning to the keyword, which is not allowed by the computer. Some C compilers allow you to construct variable names that exactly resemble the keywords. However, it would be safer not to mix up the variable names and the keywords. The keywords are also called ‘Reserved words’. There are only 32 keywords available in C. Figure 1.5 gives a list of these keywords for your ready reference. A detailed discussion of each of these keywords would be taken up in later chapters wherever their use is relevant. Before we begin with our first C program do remember the following rules that are applicable to all C programs:

(a)Each instruction in a C program is written as a separate statement. Therefore a complete C program would comprise of a series of statements.
(b)The statements in a program must appear in the same order in which we wish them to be executed; unless of course the logic of the problem demands a deliberate ‘jump’ or transfer of control to a statement, which is out of sequence.
(c)Blank spaces may be inserted between two words to improve the readability of the statement. However, no blank spaces are allowed within a variable,
constant or keyword.
(d)All statements are entered in small case letters.
(e)C has no specific rules for the position at which a statement is to be written. That’s why it is often called a free-form language.
(f)Every C statement must end with a ;. Thus ; acts as a statement terminator.
Let us now write down our first C program. It would simply calculate simple interest for a set of values representing principle, number of years and rate of interest.


/* Calculation of simple interest */
/* Author gekay Date: 25/05/2004 */
main( )
{
int p, n ;
float r, si ;
p = 1000 ;
n = 3 ;
r = 8.5 ;
/* formula for simple interest */
si = p * n * r / 100 ;
printf ( "%f" , si ) ;
}


Now a few useful tips about the program...

- Comment about the program should be enclosed within /* */. For example, the first two statements in our program are comments.
- Though comments are not necessary, it is a good practice to begin a program with a comment indicating the purpose of the program, its author
and the date on which the program was written.
- Any number of comments can be written at any place in the program. For example, a comment can be written before the statement,
after the statement or within the statement as shown below:
/* formula */ si = p * n * r / 100 ;
si = p * n * r / 100 ; /* formula */
si = p * n * r / /* formula */ 100 ;
- Sometimes it is not so obvious as to what a particular statement in a program accomplishes. At such times it is worthwhile mentioning
the purpose of the statement (or a set of statements) using a comment. For example:
/* formula for simple interest */
si = p * n * r / 100 ;
- Often programmers seem to ignore writing of comments. But when a team is building big software well commented code is almost essential
for other team members to understand it.
- Although a lot of comments are probably not necessary in this program, it is usually the case that programmers tend to use too few comments
rather than too many. An adequate number of comments can save hours of misery and suffering when you later try to figure out what the program does.
- The normal language rules do not apply to text written within /* .. */. Thus we can type this text in small case, capital or a combination.
This is because the comments are solely given for the understanding of the programmer or the fellow programmers and are completely ignored by the compiler.
- Comments cannot be nested. For example,
/* Cal of SI /* Author sam date 01/01/2002 */ */
is invalid.
- A comment can be split over more than one line, as in,
/* This is
a jazzy
comment */
Such a comment is often called a multi-line comment.
- main( ) is a collective name given to a set of statements. This name has to be main( ),
it cannot be anything else. All statements that belong to main( )
are enclosed within a pair of braces { } as shown below.
main( )
{
statement 1 ;
statement 2 ;
statement 3 ;
}
- Technically speaking main( ) is a function. Every function has a pair of parentheses ( ) associated with it.
We would discuss functions and their working in great detail in Chapter 5.
- Any variable used in the program must be declared before using it. For example,
int p, n ;
float r, si ;
- Any C statement always ends with a ;
For example,
float r, si ;
r = 8.5 ;
- In the statement,
si = p * n * r / 100 ;
* and / are the arithmetic operators. The arithmetic operators available in C are +, -, * and /. C is very rich in operators.
There are about 45 operators available in C. Surprisingly there is no operator for exponentiation... a slip,
which can be forgiven considering the fact that C has been developed by an individual, not by a committee.
- Once the value of si is calculated it needs to be displayed on the screen. Unlike other languages,
C does not contain any instruction to display output on the screen. All output to screen is achieved using readymade library functions. One such
function is printf( ). We have used it display on the screen the value contained in si.
The general form of printf( ) function is,
printf ( "", ) ;
can contain,
%f for printing real values
%d for printing integer values
%c for printing character values
In addition to format specifiers like %f, %d and %c the format string may also contain any other characters.
These characters are printed as they are when the printf( ) is executed.
Following are some examples of usage of printf( ) function:
printf ( "%f", si ) ;
printf ( "%d %d %f %f", p, n, r, si ) ;
printf ( "Simple interest = Rs. %f", si ) ;
printf ( "Prin = %d \nRate = %f", p, r ) ;
The output of the last statement would look like this...
Prin = 1000
Rate = 8.5
What is ‘\n’ doing in this statement? It is called newline and it takes the cursor to the next line. Therefore,
you get the output split over two lines. ‘\n’ is one of the several Escape Sequences available in C.
These are discussed in detail in Chapter 11. Right now, all that we can say is ‘\n’ comes in
handy when we want to format the output properly on separate lines.
printf( ) can not only print values of variables, it can also print the result of an expression.
An expression is nothing but a valid combination of constants, variables and operators.
Thus, 3, 3 + 2, c and a + b * c – d all are valid expressions. The results of these expressions can be printed as shown below:
printf ( "%d %d %d %d", 3, 3 + 2, c, a + b * c – d ) ;
Note that 3 and c also represent valid expressions.


Compilation and Execution
Once you have written the program you need to type it and instruct the machine to execute it. To type your C program you need another program called Editor. Once the program has been typed it needs to be converted to machine language (0s and 1s) before the machine can execute it. To carry out this conversion we need another program called Compiler. Compiler vendors provide an Integrated Development Environment (IDE) which consists of an Editor as well as the Compiler. There are several such IDEs available in the market targeted towards different operating systems. For example, Turbo C, Turbo C++ and Microsoft C are some of the popular compilers that work under MS-DOS; Visual C++ and Borland C++ are the compilers that work under Windows, whereas gcc compiler works under Linux. Note that Turbo C++, Microsoft C++ and Borland C++ software also contain a C compiler bundled with them. If you are a beginner you would be better off using a simple compiler like Turbo C or Turbo C++. Once you have mastered the language elements you can then switch over to more sophisticated compilers like Visual C++ under Windows or gcc under Linux. Most of the programs in this book would work with all the compilers. Wherever there is a deviation I would point it out that time. Assuming that you are using a Turbo C or Turbo C++ compiler here are the steps that you need to follow to compile and execute your first C program…


(a)Start the compiler at C> prompt. The compiler (TC.EXE is usually present in C:\TC\BIN directory).
(b)Select New from the File menu
(c)Type the program.
(d)Save the program using F2 under a proper name
(e)Use Ctrl + F9 to compile and execute the program.
(f)Use Alt + F5 to view the output.


Note that on compiling the program its machine language equivalent is stored as an EXE file (Program1.EXE) on the disk. This file is called an executable file. If we copy this file to another machine we can execute it there without being required to recompile it. In fact the other machine need not even have a compiler to be able to execute the file.
A word of caution! If you run this program in Turbo C++ compiler, you may get an error — “The function printf should have a prototype”.
To get rid of this error, perform the following steps and then recompile the program.
Select ‘Options’ menu and then select ‘Compiler | C++ Options’. In the dialog box that pops up, select ‘CPP always’ in the ‘Use C++ Compiler’ options.
Again select ‘Options’ menu and then select ‘Environment | Editor’. Make sure that the default extension is ‘C’ rather than ‘CPP’.


Receiving Input

In the program discussed above we assumed the values of p, n and r to be 1000, 3 and 8.5. Every time we run the program we would get the same value for simple interest. If we want to calculate simple interest for some other set of values then we are required to make the relevant change in the program, and again compile and execute it. Thus the program is not general enough to calculate simple interest for any set of values without being required to make a change in the program. Moreover, if you distribute the EXE file of this program to somebody he would not even be able to make changes in the program. Hence it is a good practice to create a program that is general enough to work for any set of values. To make the program general the program itself should ask the user to supply the values of p, n and r through the keyboard during execution. This can be achieved using a function called scanf( ). This function is a counter-part of the printf( ) function. printf( ) outputs the values to the screen whereas scanf( ) receives them from the keyboard. This is illustrated in the program shown below.


/* Calculation of simple interest */
/* Author gekay Date 25/05/2004 */
main( )
{
int p, n ;
float r, si ;
printf ( "Enter values of p, n, r" ) ;
scanf ( "%d %d %f", &p, &n, &r ) ;
si = p * n * r / 100 ;
printf ( "%f" , si ) ;
}


The first printf( ) outputs the message ‘Enter values of p, n, r’ on the screen. Here we have not used any expression in printf( ) which means that using expressions in printf( ) is optional. Note that the ampersand (&) before the variables in the scanf( ) function is a must. & is an ‘Address of’ operator. It gives the location number used by the variable in memory. When we say &a, we are telling scanf( ) at which memory location should it store the value supplied by the user from the keyboard. Note that a blank, a tab or a new line must separate the values supplied to scanf( ). Note that a blank is creating using a spacebar,
tab using the Tab key and new line using the Enter key. This is shown below:

Ex.: The three values separated by blank
1000 5 15.5
Ex.: The three values separated by tab.
1000 5 15.5
Ex.: The three values separated by newline.
1000
5
15.5
So much for the tips. How about another program to give you a feel of things...


/* Just for fun. Author: Bozo */
main( )
{
int num ;
printf ( "Enter a number" ) ;
scanf ( "%d", &num ) ;
printf ( "Now I am letting you on a secret..." ) ;
printf ( "You have just entered the number %d", num ) ;
}



Type Declaration Instruction

This instruction is used to declare the type of variables being used in the program. Any variable used in the program must be declared before using it in any statement. The type declaration statement is written at the beginning of main( ) function.

Ex.: int bas ;
float rs, grosssal ;
char name, code ;

There are several subtle variations of the type declaration instruction. These are discussed below:

(a)While declaring the type of variable we can also initialize it as shown below.
int i = 10, j = 25 ;
float a = 1.5, b = 1.99 + 2.4 * 1.44 ;

(b)The order in which we define the variables is sometimes important sometimes not. For example,
int i = 10, j = 25 ;
is same as
int j = 25, j = 10 ;
However,
float a = 1.5, b = a + 3.1 ;
is alright, but
float b = a + 3.1, a = 1.5 ;
is not. This is because here we are trying to use a even before defining it.

(c)The following statements would work
int a, b, c, d ;
a = b = c = 10 ;
However, the following statement would not work
int a = b = c = d = 10 ;
Once again we are trying to use b (to assign to a) before defining it.


Arithmetic Instruction

A C arithmetic instruction consists of a variable name on the left hand side of = and variable names & constants on the right hand side of =. The variables and constants appearing on the right hand side of = are connected by arithmetic operators like +, -, *, and /.

Ex.: int ad ;
float kot, deta, alpha, beta, gamma ;
ad = 3200 ;
kot = 0.0056 ;
deta = alpha * beta / gamma + 3.2 * 2 / 5 ;
Here,
*, /, -, + are the arithmetic operators.
= is the assignment operator.
2, 5 and 3200 are integer constants.
3.2 and 0.0056 are real constants.
ad is an integer variable.
kot, deta, alpha, beta, gamma are real variables.

The variables and constants together are called ‘operands’ that are operated upon by the ‘arithmetic operators’ and the result is assigned, using the assignment operator, to the variable on left-hand side. A C arithmetic statement could be of three types. These are as follows:

(a)Integer mode arithmetic statement - This is an arithmetic statement in which all operands are either integer variables or integer constants.
Ex.: int i, king, issac, noteit ;
i = i + 1 ;
king = issac * 234 + noteit - 7689 ;
(b)Real mode arithmetic statement - This is an arithmetic statement in which all operands are either real constants or real variables.
Ex.: float qbee, antink, si, prin, anoy, roi ;
qbee = antink + 23.123 / 4.5 * 0.3442 ;
si = prin * anoy * roi / 100.0 ;
(c)Mixed mode arithmetic statement - This is an arithmetic statement in which some of the operands are integers and some of the operands are real.
Ex.: float si, prin, anoy, roi, avg ;
int a, b, c, num ;
si = prin * anoy * roi / 100.0 ;
avg = ( a + b + c + num ) / 4 ;
It is very important to understand how the execution of an arithmetic statement takes place. Firstly, the right hand side is evaluated using constants and the numerical values stored in the variable names. This value is then assigned to the variable on the left-hand side. Though Arithmetic instructions look simple to use one often commits mistakes in writing them. Let us take a closer look at these statements. Note the following points carefully.

(a)C allows only one variable on left-hand side of =. That is, z = k * l is legal, whereas k * l = z is illegal.
(b)In addition to the division operator C also provides a modular division operator. This operator returns the remainder on dividing one integer
with another.
Thus the expression 10 / 2 yields 5, whereas, 10 % 2 yields 0. Note that the modulus operator (%) cannot be applied on a float.
Also note that on using % the sign of the remainder is always same as the sign of the numerator. Thus –5 % 2 yields –1, whereas, 5 % -2 yields 1.
(c)An arithmetic instruction is often used for storing character constants in character variables.
char a, b, d ;
a = 'F' ;
b = 'G' ;
d = '+' ;
When we do this the ASCII values of the characters are stored in the variables.
ASCII values are used to represent any character in memory. The ASCII values of ‘F’ and ‘G’ are 70 and 71 (refer the ASCII Table in Appendix E).
(d)Arithmetic operations can be performed on ints, floats and chars.
Thus the statements,
char x, y ;
int z ;
x = 'a' ;
y = 'b' ;
z = x + y ;
are perfectly valid, since the addition is performed on the ASCII values of the characters and not on characters themselves.
The ASCII values of ‘a’ and ‘b’ are 97 and 98, and hence can definitely be added.
(e)No operator is assumed to be present. It must be written explicitly. In the following example,
the multiplication operator after b must be explicitly written.
a = c.d.b(xy) ..............usual arithmetic statement
b = c * d * b * ( x * y )................. C statement
(f) Unlike other high level languages, there is no operator for performing exponentiation operation.
Thus following statements are invalid.
a = 3 ** 2 ;
b = 3 ^ 2 ;

If we want to do the exponentiation we can get it done this way:


#include
main( )
{
int a ;
a = pow ( 3, 2 ) ;
printf ( “%d”, a ) ;
}

The Decision Control Structure

A decision control instruction can be implemented in C using :
a).The if statement
syntax:


if(this condition is true)
{
execute this statement;
}



b).The if else statement
syntax:


if(this condition is true)
{ execute this;
}
else
{execute that;
}



Nested if else statements

C Program


/* A quick demo of nested if-else */
main( )
{
int i ;
printf ( "Enter either 1 or 2 " ) ;
scanf ( "%d", &i ) ;
if ( i == 1 )
printf ( "You would go to heaven !" ) ;
else
{
if ( i == 2 )
printf ( "Hell was created with you in mind" ) ;
else
printf ( "How about mother earth !" ) ;
}
}



THE LOOP CONTROL STRUCTURE

Three types


While loop syntax:


while(condition)
{
statement;
}


till the condition is true statement wil be executed.


For loop

set loop counter to initial value.
giving it a target value.
till not target value is achieved ,increase value each time of loop counter.

Do while loop syntax :


do
{
this;
and this;
}while(this condition is true);


Case control structure

Decisions Using switch
The control statement that allows us to make a decision from the number of choices is called a switch, or more correctly a switch-case-default, since these three keywords go together to make up the control statement. They most often appear as follows:



switch ( integer expression )
{
case constant 1 :
do this ;
case constant 2 :
do this ;
case constant 3 :
do this ;
default :
do this ;
}


The integer expression following the keyword switch is any C expression that will yield an integer value. It could be an integer constant like 1, 2 or 3, or an expression that evaluates to aninteger. The keyword case is followed by an integer or a character constant. Each constant in each case must be different from all the others. The “do this” lines in the above form of switch represent any valid C statement.
Consider the following program:


main( )
{
int i = 2 ;
switch ( i )
{
case 1 :
printf ( "I am in case 1 \n" ) ;
case 2 :
printf ( "I am in case 2 \n" ) ;
case 3 :
printf ( "I am in case 3 \n" ) ;
default :
printf ( "I am in default \n" ) ;
}
}


The output of this program would be:
I am in case 2
I am in case 3
I am in default

The output is definitely not what we expected! We didn’t expect the second and third line in the above output. The program prints case 2 and 3 and the default case. Well, yes. We said the switch executes the case where a match is found and all the subsequent cases and the default as well. If you want that only case 2 should get executed, it is upto you to get out of the switch then and there by using a break statement. The following example shows how this is done. Note that there is no need for a break statement after the default, since the control comes out of the switch anyway.


main( )
{
int i = 2 ;
switch ( i )
{
case 1 :
printf ( "I am in case 1 \n" ) ;
break ;
case 2 :
printf ( "I am in case 2 \n" ) ;
break ;
case 3 :
printf ( "I am in case 3 \n" ) ;
break ;
default :
printf ( "I am in default \n" ) ;
}
}


The output of this program would be:
I am in case 2


FUNCTIONS
What is a Function
function is a self-contained block of statements that perform a coherent task of some kind. Every C program can be thought of as a collection of these functions. As we noted earlier, using a function is something like hiring a person to do a specific job for you. Sometimes the interaction with this person is very simple; sometimes it’s complex. Let us now look at a simple C function that operates in much the same way as the mechanic. Actually, we will be looking at two things—a function that calls or activates the function and the function itself.


main( )
{
message( ) ;
printf ( "\nCry, and you stop the monotony!" ) ;
}
message( )
{
printf ( "\nSmile, and the world smiles with you..." ) ;
}


And here’s the output...
Smile, and the world smiles with you...
Cry, and you stop the monotony!
Here, main( ) itself is a function and through it we are calling the function message( ). What do we mean when we say that main( ) ‘calls’ the function message( )? We mean that the control passes to the function message( ). The activity of main( ) is temporarily suspended; it falls asleep while the message( ) function wakes up and goes to work. When the message( ) function runs out of statements to execute, the control returns to main( ), which comes to life again and begins executing its code at the exact point where it left off. Thus, main( ) becomes the ‘calling’ function, whereas message( ) becomes the ‘called’ function.If you have grasped the concept of ‘calling’ a function you are prepared for a call to more than one function. Consider the following example:


main( )
{
printf ( "\nI am in main" ) ;
italy( ) ;
brazil( ) ;
argentina( ) ;
}
italy( )
{
printf ( "\nI am in italy" ) ;
}
brazil( )
{
printf ( "\nI am in brazil" ) ;
}
argentina( )
{
printf ( "\nI am in argentina" ) ;
}


The output of the above program when executed would be as under:
I am in main
I am in italy
I am in brazil
I am in argentina
From this program a number of conclusions can be drawn:
- Any C program contains at least one function.
- If a program contains only one function, it must be main( ).
- If a C program contains more than one function, then one (and only one) of these functions must be main( ),
because program execution always begins with main( ).
- There is no limit on the number of functions that might be present in a C program.
- Each function in a program is called in the sequence specified by the function calls in main( ).
- After each function has done its thing, control returns to main( ).When main( ) runs out of function calls, the program ends.

Passing Values between Functions

The functions that we have used so far haven’t been very flexible. We call them and they do what they are designed to do. Like our mechanic who always services the motorbike in exactly the same way, we haven’t been able to influence the functions in the way they carry out their tasks. It would be nice to have a little more control over what functions do, in the same way it would be nice to be able to tell the mechanic, “Also change the engine oil, I am going for an outing”. In short, now we want to communicate between the ‘calling’ and the ‘called’ functions.
The mechanism used to convey information to the function is the ‘argument’. You have unknowingly used the arguments in the printf( ) and scanf( ) functions; the format string and the list of variables used inside the parentheses in these functions are arguments. The arguments are sometimes also called ‘parameters’. Consider the following program. In this program, in main( ) we receive the values of a, b and c through the keyboard and then output the sum of a, b and c. However, the calculation of sum is done in a different function called calsum( ). If sum is to be calculated in calsum( ) and values of a, b and c are received in main( ), then we must pass on these values to calsum( ), and once calsum( ) calculates the sum we must return it from calsum( ) back to main( ).



/* Sending and receiving values between functions */
main( )
{
int a, b, c, sum ;
printf ( "\nEnter any three numbers " ) ;
scanf ( "%d %d %d", &a, &b, &c ) ;
sum = calsum ( a, b, c ) ;
printf ( "\nSum = %d", sum ) ;
}
calsum ( x, y, z )
int x, y, z ;
{
int d ;
d = x + y + z ;
return ( d ) ;
}


And here is the output...
Enter any three numbers 10 20 30
Sum = 60
There are a number of things to note about this program:
In this program, from the function main( ) the values of a, b and c are passed on to the function calsum( ), by making a call to the function calsum( ) and mentioning a, b and c in the parentheses:
sum = calsum ( a, b, c ) ;
In the calsum( ) function these values get collected in three variables x, y and z:
calsum ( x, y, z )
int x, y, z ;
The variables a, b and c are called ‘actual arguments’, whereas the variables x, y and z are called ‘formal arguments’.
Any number of arguments can be passed to a function being called. However, the type, order and number of the actual and formal arguments must always be same. Instead of using different variable names x, y and z, we could have used the same variable names a, b and c. But the compiler would still treat them as different variables since they are in different functions. There are two methods of declaring the formal arguments. The one that we have used in our program is known as Kernighan and Ritchie (or just K & R) method.
calsum ( x, y, z )
int x, y, z ;
Another method is,
calsum ( int x, int y, int z )

This method is called ANSI method and is more commonly used these days. In the earlier programs the moment closing brace ( } ) of the called function was encountered the control returned to the calling function. No separate return statement was necessary to send back the control. This approach is fine if the called function is not going to return any meaningful value to the calling function. In the above program, however, we want to return the sum of x, y and z. Therefore, it is necessary to use the return statement. The return statement serves two purposes:

(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.

In the above program the value of sum of three numbers is being returned. 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. The following program illustrates these facts.


fun( )
{
char ch ;
printf ( "\nEnter any alphabet " ) ;
scanf ( "%c", &ch ) ;
if ( ch >= 65 && ch <= 90 )
return ( ch ) ;
else
return ( ch + 32 ) ;
}


In this function different return statements will be executed depending on whether ch is capital or not.
Whenever the control returns from a function some value is definitely returned. If a meaningful value is returned then it should be accepted in the calling program by equating the called function to some variable. For example,
sum = calsum ( a, b, c ) ;
All the following are valid return statements.
return ( a ) ;
return ( 23 ) ;
return ( 12.34 ) ;
return ;
In the last statement a garbage value is returned to the calling function since we are not returning any specific value. Note that in this case the parentheses after return are dropped. If we want that a called function should not return any value, in that case, we must mention so by using the keyword void as shown below.


void display( )
{
printf ( "\nHeads I win..." ) ;
printf ( "\nTails you lose" ) ;
}


A function can return only one value at a time. Thus, the following statements are invalid.
return ( a, b ) ;
return ( x, 12 ) ;
There is a way to get around this limitation, which would be discussed later in this chapter when we learn pointers. If the value of a formal argument is changed in the called function, the corresponding change does not take place in the calling function. For example,


main( )
{
int a = 30 ;
fun ( a ) ;
printf ( "\n%d", a ) ;
}
fun ( int b )
{
b = 60 ;
printf ( "\n%d", b ) ;
}


The output of the above program would be:
60
30
Thus, even though the value of b is changed in fun( ), the value of a in main( ) remains unchanged. This means that when values are passed to a called function the values present in actual arguments are not physically moved to the formal arguments; just a photocopy of values in actual argument is made into formal arguments.

Scope Rule of Functions

Look at the following program


main( )
{
int i = 20 ;
display ( i ) ;
}
display ( int j )
{

int k = 35 ;
printf ( "\n%d", j ) ;
printf ( "\n%d", k ) ;
}


In this program is it necessary to pass the value of the variable i to the function display( )? Will it not become automatically available to the function display( )? No. Because by default the scope of a variable is local to the function in which it is defined.
The presence of i is known only to the function main( ) and not to any other function. Similarly, the variable k is local to the function display( ) and hence it is not available to main( ). That is why to make the value of i available to display( ) we have to explicitly pass it to display( ). Likewise, if we want k to be available to main( ) we will have to return it to main( ) using the return statement.
In general we can say that the scope of a variable is local to the function in which it is defined.

Calling Convention

Calling convention indicates the order in which arguments are passed to a function when a function call is encountered. There are two possibilities here:

(a)Arguments might be passed from left to right
(b)Arguments might be passed from right to left
.
C language follows the second order.
Consider the following function call:
fun (a, b, c, d ) ;
In this call it doesn’t matter whether the arguments are passed from left to right or from right to left. However, in some function call the order of passing arguments becomes an important consideration. For example:
int a = 1 ;
printf ( "%d %d %d", a, ++a, a++ ) ;
It appears that this printf( ) would output 1 2 3.
This however is not the case. Surprisingly, it outputs 3 3 1. This is because C’s calling convention is from right to left.

Advanced Features of Functions

With a sound basis of the preliminaries of C functions, let us now get into their intricacies. Following advanced topics would be considered here.

(a) Function Declaration and Prototypes.
(b) Calling functions by value or by reference.
(c) Recursion

Let us understand these features one by one.
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 the type int. If we desire that a function should return a value other than an int, then it is necessary to explicitly mention so in the calling function as well as in the called function. Suppose we want to find out square of a number using a function. This is how this simple program would look like:


main( )
{
float a, b ;
printf ( "\nEnter any number " ) ;
scanf ( "%f", &a ) ;
b = square ( a ) ;
printf ( "\nSquare of %f is %f", a, b ) ;
}
square ( float x )
{
float y ;
y = x * x ;
return ( y ) ;
}


And here are three sample runs of this program...
Enter any number 3
Square of 3 is 9.000000
Enter any number 1.5
Square of 1.5 is 2.000000
Enter any number 2.5
Square of 2.5 is 6.000000

The first of these answers is correct. But square of 1.5 is definitely not 2. Neither is 6 a square of 2.5. This happened because any C function, by default, always returns an integer value. Therefore, even though the function square( ) calculates the square of 1.5 as 2.25, the problem crops up when this 2.25 is to be returned to main( ). square( ) is not capable of returning a float value. How do we overcome this? The following program segment illustrates how to make square( ) capable of returning a float value.


main( )
{
float square ( float ) ;
float a, b ;
printf ( "\nEnter any number " ) ;
scanf ( "%f", &a ) ;
b = square ( a ) ;
printf ( "\nSquare of %f is %f", a, b ) ;
}
float square ( float x )
{
float y ;
y = x * x ;
return ( y ) ;
}


And here is the output...
Enter any number 1.5
Square of 1.5 is 2.250000
Enter any number 2.5
Square of 2.5 is 6.250000

Powered by Blog - Widget
Face Upward - Widget