Showing posts with label C. Show all posts
Showing posts with label C. Show all posts

Wednesday, 11 April 2012

C Programming - Sample - 5 - Basic Structure Of C Programs

BASIC STRUCTURE OF C PROGRAMS :

The examples discussed so far illustrate that a C program can be viewed as a group of building blocks called functions. A function is a subroutine that may include one or more statements designed to perform a specific task. To write a C program, we first create functions and then put them together. A C program may contain one or more sections shown in Fig.




The documentation section consists of a set of comment lines giving the name of the program, the author and other details, which the programmer would like to use later. The link section provides instructions to the compiler to link functions from the system library. The definition section defines all symbolic constants.
There are sonic variables that are used in more than one function. Such variables are called global variables and are declared in the global declaration section that is outside of all the functions. This section also declares all the user-defined functions.

Every C program must have one main( ) function section. This section contains two parts, declara¬tion part and executable part. The declaration part declares all the variables used in the executable part. There is at least one statement in the executable part. These two parts must appear between the opening and the closing braces. The program execution begins at the opening brace and ends at the closing brace. The closing brace of the main function section is the logical end of the program. All statements in the declaration and executable parts end with a semicolon.

The subprogram section contains all the user-defined functions that are called in the main function. User-defined functions are generally placed immediately after the main function, although they may appear in any order.

All sections, except the main function section may be absent when they are not required.

Friday, 6 April 2012

C Programming - Sample - 4 - USE OF MATH FUNCTIONS

USE OF MATH FUNCTIONS :
We often use standard mathematical functions such as cos, sin, exp. etc. We shall see now the use of a mathematical function in a program. The standard mathematical functions are defined and kept as a part of C math library. If we want to use any of these mathematical functions, we must add an #include instruction in the program. Like #define, it is also a compiler directive that instructs the compiler to link the specified mathematical functions from the library. The instruction is of the form

#include <math.h>

math.h is the filename containing the required function. Figure illustrates the use of cosine func¬tion. The program calculates cosine values for angles 0, 10, 20 180 and prints out the results with headings.

Another #include instruction that is often required is

//include <stdio.h>

stdio.h refers to the standard 1/0 header file containing standard input and output functions




As mentioned earlier, C programs are divided into modules or functions. Some functions are written by users like us and many others are stored in the C library. Library functions are grouped category-wise and stored in different files known as header files. If we want to access the functions stored in the library, it is necessary to tell the compiler about the files to be accessed.

This is achieved by using the preprocessor directive #include as follows: 

#include < filename >

filename is the name of the library file that contains the required function defini¬tion. Preprocessor directives are placed at the beginning of a program. '



Thursday, 29 March 2012

C Programming - Sample - 3 - Use Of Subroutines

USE OF SUBROUTINES:

So far, we have used only printf function that has been provided for us by the C system. The program shown in Fig. uses a user defined function. A function defined by the user is equivalent to a subroutine in FORTRAN or subprogram in BASIC.

Figure presents a very simple program that uses a mul ( ) function. The program will print the following output.


Multiplication of 5 and 10 is 50


The mul ( 1 function multiplies the values of x and y and the result is returned to the main ( ) function when it is called in the statement

c = mul (a, b);
The mul ( ) has two arguments x and y that are declared as integers. The values of a and b are passed on to x and y respectively when the function mul ( ) is called.

Thursday, 22 March 2012

C Programming - Sample - 2 - Interest Calculation

Interest Calculation Programming

The program in Fig. calculates the value of money at the end of each year of investment, assuming an interest rate of 11 percent and prints the year, and the corresponding amount, in two columns. The output is shown in Fig.  for a period of 10 years with an initial investment of 5000.00. The pro¬gram uses the following formula: 

Value at the end of year = Value at start of year (1 + interest rate) 

In the program, the variable value represents the value of money at the end of the year while amount represents the value of money at the start of the year. The statement

amount = value 

makes the value at the end of the current year as the value at start of the next year.


Interest Calculation


 Let us consider the new features introduced in this program. The second and third lines begin with #detine instructions. A #define instruction defines value to a symbolic constant for use in the pro-gram. Whenever a symbolic name is encountered, the compiler substitutes the value associated with the name automatically. To change the value, we have to simply change the definition. In this exam-ple, we have defined two symbolic constants PERIOD and PRINCIPAL and assigned values 10 and 5000.00 respectively. These values remain constant throughout the execution of the program.

Investment Program Output


The #Define Directive:
A #define is a preprocessor compiler directive and not a statement. Therefore #define lines should not end with a semicolon. Symbolic constants are generally written in uppercase so that they are easily distinguished from lowercase variable names. #define instructions are usually placed at the beginning before the main() function. Symbolic constants are not declared in declaration section.

We must note that the defined constants are not variables. We may not change their values within the program by using an assignment statement. For example, the statement

PRINCIPAL = 10000.00;
is illegal.
The declaration section declares year as integer and amount, value and inrate as floating point numbers. Note all the floating-point variables are declared in one statement. They can also be declared as

fl oat amount ;

fl oat value; 
float inrate;


When two or more variables are declared in one statement, they are separated by a comma.
All computations and printing are accomplished in a while loop, while is a mechanism for evalu¬ating repeatedly a statement or a group of statements. In this case as long as the value of year is less than or equal to the value of PERIOD, the four statements that follow while are executed. Note that these four statements are grouped by braces. We exit the loop when year becomes greater than PERIOD. The concept and types of loops .
C supports the basic four arithmetic operators (—, +, /) along with several others.



Tuesday, 13 March 2012

C Programming - Sample - 1


Printing A Message:



main( )
1"       .pri nting beg i ns.
pri ntf ("I see, I remember") ; /*          ....printing          ends.....................*/


This program when executed will produce the following output:

I see, I remember

Let us have a close look at the program. The first line informs the system that the name of the program is main and the execution begins at this line. The main( ) is a special function used by the C system to tell the computer where the program starts. Every program must have exactly one main function. If we use more than one main function, the compiler cannot tell which one marks the begin¬ning of the program.
The empty pair of parentheses immediately following main indicates that the function main has no arguments (or parameters).

The opening brace "{ " in the second line marks the beginning of the function main and the closing brace "}" in the last line indicates the end of the function. In this case, the closing brace also marks the end of the program. All the statements between these two braces form the ftinction body. The function body contains a set of instructions to perform the given task.

In this case, the function body contains three statements out of which only the printf line is an executable statement. The lines beginning with /* and ending with */ are known as comment lines. These are used in a program to enhance its readability and understanding. Comment lines are not executable statements and therefore anything between /* and */ is ignored by the compiler. In gen¬eral, a comment can be inserted wherever blank spaces can occur--at the beginning, middle or end of a line—"but never in the middle of a word ".

Although comments can appear anywhere, they cannot be nested in C. That means, we cannot have comments inside comments. Once the compiler finds an opening token, it ignores everything until it finds a closing token. The comment line is not valid and therefore results in an error. Since comments do not affect the execution speed and the size of a compiled program, we should use them liberally in our programs. They help the programmers and other users in understanding the various functions and operations of a program and serve as an aid to debugging and testing. We shall see the use of comment lines more in the examples that follow.

Let us now look at the printf( function, the only executable statement of the program.
printf ("I see, I remember"); 


printf is a predefined standard C function for printing output. Predefined means that it is a function that has already been written and compiled. and linked together with our program at the time of linking. The concepts of compilation and linking are explained later in this chapter. The printf func¬tion causes everything between the starting and the ending quotation marks to be printed out In this case, the output will be:


I see, I remember 


Note that the print line ends with a semicolon. Ever), statement in C .thould end with a semicolon ( mark.
Suppose we want to print the above quotation in two lines as

I see,
 I remember !

This can be achieved by adding another printf function as shown below:


printf(I see, \n"); 
Iprintf( .I remember !

The information contained between the parentheses is called the argument of the function. This argument of the first printf function is" I see, \n" and the second is "I remetnber!". These arguments are simply strings of characters to be printed out

Notice that the argument of the first printf contains a combination of two characters \ and n at the end of the string. This combination is collectively catled the newline character. A new line character instructs the computer logo to the next (new) line. It is 'similar in concept to the carriage return key on a typewriter. After printing the character comma t.) the presence of the newline character VI causes the string "I remember!" to be printed on the next line. No space is allowed between I and n.

It we omit the newline character from the first printf statement, then the output vsi I again be a single line as shown below.


see J remember ! 

This is similar to the output of the progrimi in Fig I 2 However. note that there is no space between . and I

It is also possible to produce two ot nut/ e lines ot output by one printf statement with the use newline character at appropriate pla,s lttr eydmple, the statement printf ("I see, \n I remember I");


will output


I see, I remember! 


while the statement


Printf( "I\n.. see,\n_ _ _ I\n_ _ ... remember !"); 


will print out
 I 
.. see
 ... remember !

NOTE: Sonic authors i,commend the inclusion of the statement

#include <stdio.h>

at the beginning of all programs that use any input/output library functions. However, this is not necessary for the functions priori and scal#'which have been defined as a part of the C language. See Chapter 4 for more on input and output functions.
Before we proceed to discuss further examples, we must note one important point. C does make a distinction between uppercase and lowercase letters. For example, printf and PRINTF are not the same. In C. everything is written in lowercase letters. However, uppercase letters are used for sym¬bolic names representing constants. We may also use uppercase letters in output strings like "I SEE" and -I REMEMBER"
The above example that printed I see, I remember is one of the simplest programs. Figure  highlights the general format of such simple programs. All C programs need a main function.

The main Function

The main is a part of every C program. C permits different forms of main state¬ment. Following forms are allowed.
main()
int main()
void main()
main(void)
void main(void)
int main(void)
The empty pair of parentheses indicates that the function has no arguments. This may be explicitly indicated by using the keyword void inside the parentheses. We may also specify the keyword int or void before the word main. The key¬word void means that the function does not return any information to the operat¬ing system and int means that the function returns an integer value to the operating system. When int is specified, the last statement in the program must be "return 0". For the sake of simplicity, we use the first form in our programs.


Sunday, 11 March 2012

Importance Of C

C Importance:

1967
1970
1972
The increasing popularity of C is probably due to its many desirable qualities. It is a robust language whose rich set of built-in functions and operators can be used to write any complex program. The C compiler combines the capabilities of an assembly language with the features of a high-level lan-guage and therefore it is well suited for writing both system software and business packages. In tact. many of the C compilers available in the market are written in C.

Programs written in C are efficient and fast. This is due to its variety of data types 111`1 powerful operators. It is many times faster than BASIC. For example, a program to increment variable iffiin to 15000 takes about one second in C while it takes more than 50 secondsitt interpreter BASIC, There are only 32 keywords and its strength lies in its built-in functions. Several standard func¬:ions are available which can be used for developing programs.

C is highly portable. This means that C programs written for one computer can be run on another with little or no modification. Portability is important if we plan to use a new computer with a differ- nit operating system.

C language is well suited for structured programming, thus requiring the user to think of a problem in terms of function modules or blocks. A proper collection of these modules would make a complete program. This modular structure makes program debugging, testing and maintenance easier.

Another important feature of C is its ability to extend itself. A C program is basically a collection of functions that are supported by the C library. We can continuously add our own functions to C library. With the availability of a large number of functions, the programming task becomes simple.

Before discussing specific features of C, we shall look at some sample C programs, and analyze and understand how they work.