C Programming rules part two

This post is in continuation with programming rules in c and better going through that post first for the sake of completeness.

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 main( ) is a function. Every function has a pair of parentheses ( ) associated with it.

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

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

Here ‘\n’ 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.

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.

IF STATEMENT

MULTIPLE STATEMENTS IN IF

IF AND ELSE

NESTED IF AND ELSE


BREAK

CONTINUE AND DO WHILE IN C LANGUAGE

SWITCH IN C PROGRAMMING

FUNCTIONS IN C PROGRAMMING


Functions and usage in C part two

Coding in C functions

No comments:

Post a Comment