Learn more about IndiaStudyChannel
Install Alexa Toolbar
and earn more...
 
Communities Members BookmarksPolls Fresher Jobs Funny Pictures MCA Projects New Member FAQ  



My Profile
Active Members
TodayLast 7 Days more...



Awards & Gifts
Online Exams

Fresher Jobs


Our fresher job section is exclusively for fresh graduates! Find jobs for freshers in major Indian cities including Bangalore, Chennai, Hyderabad, Pune or Kochi

Resources


Find educational articles, blogs, discussion threads and other resources.

Colleges


Find details about any college in India or search for courses.

website counter




Overview of C:-


Posted Date: 03 Feb 2008    Resource Type: Articles/Knowledge Sharing    Category: Computer & Technology
Author: prakashMember Level: Silver    
Rating: Points: 5



Overview of C:

History of C:
‘C’ is one of the most popular computer language today. C was an offspring of the ‘ Basic Combined Programming Language’(BCPL) called B, developed in the 1960’s at Cambridge University. B Language was modified by Dennis Ritchie and was implemented at Bell Laboratories in 1972. The new Language was named C.
C language was developed along with the UNIX Operating System. This Operating System, which was also developed at Bell Laboratories, was coded almost entirely in C.

C was used mainly in academic environments, with the release of C compilers For commercial use and the increasing popularity of UNIX, it began to gain widespread support among computer professionals. Today, C is running under a number of Operating Systems including MS-DOS.

Importance of C:

C is a robust language whose rich set of built-in function and operators can be used to write any complex programs. The C compiler combines the capabilities of an assembly language with the features of high-level language, so it is well suited for writing both system software and business package. 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 and powerful operators. It is many times faster than BASIC. There are only 32 keywords and its strength lies in its built-in functions. Several standard functions are available for developing programs.

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

Basic Structure of C Program:
Consider the very simple program which prints one line of text
main()
{
/* printing begins */

printf(“ I BCA STUDENTS “);

/* printing ends */

}
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 beginning of the program.

The empty pair of parentheses immediately following main indicates that the function main has no arguments. The opening brace ‘ { ‘ and closing brace ‘ } ‘ indicates the beginning and ending of the function. All the statements between these two braces form the function body. The function body contains a set of instructions to perform the given task.

Comment Line

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.

Consider the printf( ), the only executable statement of the above program. 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 printf function prints everything between the starting and ending quotation marks to be printd out. In this case, the output will be:

I BCA STUDENTS
Note that the print line ends with a semicolon. Every statement in C should end with a semicolon (;) ;


Suppose we want to print the above quotation in two lines as

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

printf(“ I BCA, \n);
printf(“STUDENTS”);

It is possible to produce two or more lines of output by one printf statement with the use of newline characters at appropriate places. For example, the statement
printf(“ I BCA,\n STUDENTS”);
will output
I BCA
STUDENTS

Basic structure of 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.


An overview C program may contain one or more section shown below :

1. Documentation section
2. Link section
3. Definition section
4. Global declaration Section
5. main( ) function section
{




}

6. Subprogram section










The documentation section consists of a set of comment lines giving the name of the program, the author and other details ..

The link section provides instructions to the compiler to link functions from the system library.The definition section defines all symbolic constants.

There are some variables that are used in more than one function. Such variables are called global variables and are declared in the global declaration section.

Every C program must have one main( ) function, which has declaration 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.

Programming Sytle

C program statements are written in lowercase letters. Uppercase letters are used only for symbolic constants.
C is a free-form language , we can group statements together on one line. The statements

a = b;
x = y+1;
z = a+x;

can be written in one line as

a = b; x = y+1; z = a+x;
Executing a ‘C’ Program

Executing a program written in C involves a series of steps. These are

1. Creating the program
2. Compiling the program
3. Linking the program with functions that are needed from the C library.
4. Executing the program


CONSTANTS, VARIABLES, AND DATA TYPES:

A programming language is designed to help process certain kinds of data consisting of numbers, characters and strings and to provide useful output known as information. The task of processing of data is accomplished by executing a sequence of instructions called a program. These instructions are formed using certain symbols and words according to some rigid rules known as syntax rules (or grammar). Every program instruction must confirm the syntax rules of the language.

Character set:
C uses the following characters in order to develop its language. They are
(I) Alphabets : A……Z, a……..z
(II) Digits : 0 to 9
(III) Special characters : ! @ # $ % ^ & ( ) * { } [ ] ’ ” : ; / ? < > .
(IV) White spaces : blank space, new line, Horizontal tab, form feed
Carriage return.
C Tokens :
Individual words and punctuation marks are called tokens. In a C program the smallest individual units are known as C tokens. C has six types of tokens, programs are written using these tokens and the syntax of the language.














Keywords or Reserved words:

C word is classified as either a keyword or an identifier. All keywords have fixed meanings and these meanings cannot be changed. Keywords serve as basic building blocks for program statements. Keywords should be written in lowercase.
For example:
auto double int struct
break else long switch
case enum register typedef
char extern retun union
goto continue return void
do if while for
Identifiers:
Identifiers are names given to variables, functions, arrays and other user defined objects, these are user defined names. It consists of a sequence of letters and digits, with a letter as a first character. Both uppercase and lowercase letters are permitted.
Rules:
• Identifiers are formed with alphabets, digits and a special character
underscore( _ )
• The first character must be an alphabet
• No special characters are allowed other than underscore
• They are case sensitive. That is AA is different from aa
Example:
The following are some valid identifiers
A0, BASICPAY, basicpay, TOTAL_PAY, B12

The following are invalid identifiers
Variable Reason for invalidity
AB. Special character period (.) not allowed
9A The first character must be an alphabet
auto reserve word

CONSTANTS:
Constants are fixed values that do not change during the execution of a program . C supports several types of constants.










Numeric Constant:
A numeric constant is a constant made up of digits and some special characters. There are two types of numeric constant. They are
(I) Integer or fixed point constant
(II) Real or floating point constant
(I) Integer Constant:
Integer constant is a constant made up of digits without decimal point.
Rules:
• An integer constant is formed with digits 0 to 9.
• The constant can be preceded by + or – sign
• No special characters are allowed anywhere in the constant
There are three types of integer constant. They are
? Decimal integer constant
? Octal integer constant
? Hexadecimal integer constant
Decimal integer constant:
A decimal integer constant is made up of digits 0 to 9 in any combination. The first digit should not be zero.
Example:
The following are some valid decimal constants
10 +10 -5420 57/43
The following are invalid decimal integer constants
Constant Reason
5,734 Comma not allowed
0452 The first digit should not be zero
15.03 Decimal point not allowed
183 - The sign should precede the digits
Octal integer constant:
An octal integer constant is made up of digits 0 to 7 in any combination. To identify the constant as an octal constant it should begin with 0.
Example:
The following are some valid octal integer constant
0421 07562 0100

The following are invalid octal integer constant
Constant Reason
5743 The first digit should be zero
082574 The digit 8 not allowed
15.04 Decimal point not allowed
Hexadecimal integer constant:
A hexadecimal integer constant is made up of digits 0 to 9 and alphabets A to F in any combination. To identify the constant as a hexadecimal constant, it should begin with either OX or ox.
Example:
The following are some valid hexadecimal integer constant
OX532 OX1F ox1f
The following are invalid hexadecimal integer constant
Constant Reason
23A Should begin with OX
OX53.35C Decimal point not allowed
OXAC23Z The character Z not allowed

(II) Real Constant
Any number written with one decimal point is called real constant or floating point constant.
Rules:
(I) A real constant is formed with the digits 0 to 9 and a decimal point
(II) Digits before or after the decimal point can be omitted
(III)A number can be preceded by + or _ sign
(IV)No special characters are used other than decimal point.
A real constant can be expressed in any one of the following two forms
* Fractional form
* Exponent form
Fractional form:
A number written with one decimal point is called a real constant in fractional form.
Example:

The following are some valid real constant in fractional form
-0.157 .64 2.4
The following are invalid fractional real constant
Constant Reason
153 No decimal point
16.45.67 Two decimal points not allowed
5 / 3 Special character / not allowed
12,345.93 Comma not allowed

Exponent form
Exponent form is used to represent very large real constants. The general form is
mantissa e or E exponent
where
mantissa - either real or integer value
exponent - integer number
Rules:
(I) The mantissa and exponent may have a positive or negative sign
(II) Exponent should not have a decimal point
(III) Exponent must have atleast one digit
Example:
The following are some valid real constants in exponent form
(a) 7500000000 can be expressed as 7.5E9 or 75E8
(b) -0.000000368 can be expressed as -3.68E-7
(c) 3.14 can be expressed as .314E1



The following are some invalid real constants in exponent form
Constant Reason

.840E.5 Exponent should not have decimal point
80.40E17 Either + or _ sign should be used
50 Either a decimal point or an exponent must be present

Character constant:
There are two types of character constants. They are
(I) Direct
(II) Escape sequence
(I) Direct:
A direct character constant consists of a single character enclosed within single quotation marks. This gives the integer value of the enclosed character. This value is know as ASCII value.
For example:

‘5’ ‘x’ ‘;’ the character constant ‘5’ is not same as the number 5.
printf(“%d”, ‘a’); would print the number 97, the ASCII value of the letter a .
printf(“%c”, ‘97’); would output the letter a.

(II) Escape sequence:
An escape sequence consists of more than one character within single quotation marks. The first character must be a backslash(\)
Eventhough it has more than one character it represents only one.
Example:
Meaning Constant
bell (audiable alert) \a
backspace \b
form feed \f
newline \n
carriage return \r
horizontal tab \t
vertical tab \v
single quote \’
double quote \”
question mark \?
Backslash \\
null character \0

String Constant:
A string constant is a sequence of characters enclosed within double quotation marks. This can be formed with digits, alphabets and special characters.
Example:
“NAGERCOIL” “13-th-march” “12345” “5.3456”


VARIABLES:

A variable is a data name that may be used to store a data value. During the execution of the program , a variable may take different values at different times.
A variable name may be chosen by the programmer in a meaningful way so as to reflect its function or nature in the program.
For example: valid variable names
Total, Average, sum, temp, class_strength.
• Variable names may consists of letters, digits and underscore character.
• Following rules are considered while using the variable names:

? Variable names must begin with a letter. Some systems permit underscore as the first character.
? ANSI standard recognizes a length of 31 characters. The length should not be normally eight characters. Only the first eight characters are treated as significant by many compilers.
? Uppercase and lowercase letters are significant, the variable Total is not the same as the total or TOTAL.
? The variable name should not be a keyword.
? White space is not allowed.

The following are some valid variable names
A0 BASIC_PAY volume B12

The following are some invalid variable names
Variable Reason
AB. Special character (.) not allowed
9A The first character should be an alphabet
goto Reserved word

DATA TYPES:

C supports different types of data. Each type is represented differently within computers memory.
ANSI C supports four classes of data types:
1. Primary (or fundamental) data types
2. user-defined data types
3. Derived data types
4. Empty data set
All C compilers support four fundamental data types, namely integer(int), character(char), floating point(float) and double-precision floating point(double). Many of them also offer extended data types such as long int and long double.





PRIMARY DATA TYPES

Integral type

Integer Character


signed type unsigned type signed char unsigned char
int unsigned int
short int unsigned short int
long int unsigned long int








Size and Range of Basic Data Types :
data type range of values
char -128 to 127
int -32,768 to 32,767
float 3.4e-38 to 3.4e+38
double 1.7e-308 to 1.7e+308

In order to provide some control over the range of numbers and storage space, C has three classes of integer storage, namely short int, int and long int in both signed and unsigned forms.
Unsigned integers use all the bits for the magnitude of the number and are always positive. So the 16 bit machine , the range of unsigned integer numbers will be from 0 to 65,535.
We declare long and unsigned integers to increase the range of values. The use of qualifier signed on integers is optional because the declaration assumes a signed number.
Size and Range of Data Types on a 16-bit Machine

Type Size(bits) Range
char (or) signed char 8 -128 to 127
unsigned char 8 0 to 255
int (or) signed int 16 -32,768 to 32,767
unsigned int 16 0 to 65,535
short int (or) signed short int 8 128 to 127
unsigned short int 8 0 to 255
long int (or) signed long int 32 -2,147,483,648 to 2,147,483,647
unsigned long int 32 0 to 4,294,967,295
float 32 3.4E-38 to 3.4E+38
double 64 1.7E-308 to 1.7E+308
long double 80 3.4E-4932 to 1.1E+4932
Character Types:
A single character can be defined as a character(char) type data. Characters are usually stored in 8 bits(one byte) of internal storage. The qualifier signed or unsigned may be explicitly applied to char. While unsigned chars have values between 0 and 255, signed chars have values form -128 to 127.

DECLARATION OF VARIABLES:
All variables present in the program must be declared before it is used. This is done with the help of declaration statement.
Declaration does two things:
1. It tells the compiler what the variable name is.
2. It specifies what type of data the variable will hold.
*. A variable can be used to store a value of any data type.
The general form is
data-type v1,v2,….vn;
v1,v2,…vn are the names of variables. Variables are separated by commas. A declaration statement must end with a semicolon.

For example:
int count;
int number, total;
double ratio;
int and double are the keywords to represent integer type and real type data values respectively.
User-Defined Data Type:
? C supports a feature known as “type definition” that allows users to define an identifier that would represent an existing data type.
? It takes the general form:
typedef type identifier;
Explanation:
? type refers to an existing data type and identifier refers to the new name given to the data type.
Ex: typedef int units;
typedef float amount;
? They can be later used to declare variables as follows:
units a,b; amount n1, n2;
? Another user-defined data type is enumerated data type provided by C and it is defined as follows:
enum identifier {v1,v2,…vn};
? The identifier is a user-defined enumerated data type which can be used to declare variables that can have one of the values enclosed within the braces known as enumeration constants.
Ex: enum day {Monday, Tuesday,……….,Sunday};
enum day sday, eday;

sday = Monday;
eday = Friday;

DECLARATION OF STORAGE CLASS:
Storage class provides information about location and visibility of variables. The storage class decides the portion of the program within which the variables are recognized.
/* Example of storage classes */
int m;
main( )
{
int i;
float balance;

…..
Function1( );
}
Function1( )
{
int i;
float sum;
……
……..
}
The variable m is declared before the main( ) is called global variable. It can be used in all the functions in the program. It need not be declared in other functions. A global variable also known as an external variable.
The variables i, balance and sum are called local variables because they are declared inside the function.
Storage class specifiers are used to declare explicitly the scope and lifetime of a variable.
Storage classes and their meanings
auto local variable known to only to the function in which it
is declared. Default is auto.
static Local variable which exists and retains its value even
after the control is transferred to the calling function
extern Global variable known to all functions in the file.
register Local Variable which is stored in the register
For Example:
auto int count;
register char ch;
static int x;
extern long total;
Static and external variables are automatically initialized to zero. Automatic variables contain undefined values (known as ‘ garbage’) unless they are initialized explicitly.
ASSIGNING VALUES TO VARIABLES:
Values can be assigned to variables using the assignment operator =
as follows
variable_name = constant;
For example:
initial_value = 0;
final_value = 100;
total = 500;
C permits multiple assignments in one line.
For example:
initial_value = 0; final_value = 100;
During assignment operation , C converts the type of value on the right- hand side to the type on the left. This may involve truncation when real value is converted into an integer.
It is also possible to assign a value to a variable at the time the variable is declared.
data-type variable_name = constant;
For Example:
int final_value = 100;
char yes = ‘x’;
The process of giving initial values to variables is called initialization. C permits the initialization of more than one variables in one statement using multiple assignment operators.
For example:
p = q = s = 0;
x = y = z = MAX;
Declaring a variable as constant:
We may like the value of certain variables to remain constant during the execution of a program. It can be done with the qualifier const at the time of initialization.
Ex:const int total = 50;
Declaring a Variable as Volatile:
? The qualifier volatile can be used to tell explicitly the compiler that a variables value may be changed at any time by external sources.
E x: volatile int date;
? The value of date may be altered by some external factors.
Reading Data from Keyboard :
Another way of giving values to variables is to input data through keyboard using the scanf function. It is a general input function available in C and similar to printf function.
General format is
Scanf(“ control string “, &variable1, &variable2,..);
The control string contains the format of data being received. The symbol &
before each variable name is an operator that specifies the variable name’s address.
For example:
scanf(“%d”, &number);
When this statement is encountered by the computer, the execution stops and wait for the value of the variable number to be typed in. %d specifies that an integer value to be read from the terminal.
Defining Symbolic Constants:
? In a program some constants may appear repeatedly in a number of places in the program.
? A constant is defined as follows:


? Symbolic names are sometimes called constant identifiers. Since the symbolic names are constants, they do not appear in declaration.
? The following rules apply to define a symbolic constant.
1. Symbolic names have the same form as variable names.(Symbolic names are written in CAPITALS to visually distinguish them from the normal variable names)
2. No blank space between the pound sign ‘#’ and the word ‘define’ is permitted
3. ‘#’ must be the first character in the line.
4. A blank space is required between #define and symbolic name and between the symbolic name and the constant.
5. After definition, the symbolic name should not be assigned any other value with the program by using an assignment statement.
6. #define statements must not end with a semicolon.
7. Symbolic names are not declared for data types.
8. #define statements may appear anywhere in the program but before it is referenced in the program.
Examples
Valid Invalid
#define PI 3.14 #define PI=3.14( = sign not allowed)
#define MAX 10 #define MAX 10 (space between # and
define)
#define A 25 #define A 25, B 50( only one name allowed)
#define Price 100 #define Price 100; (semicolon not allowed)
#define SUM 10.98 #define SUM 10.98(Define in lowercase)
#define AMT 200 #define AMT$ 200
OPERATORS AND EXPRESSIONS:
OPERATORS:
An operator is a symbol which represents some operation that can be performed on data. There are eight operators available in c to carry out the operations. They are
(I) Arithmetic operators
(II) Relational operators
(III) Logical operators
(IV) Assignment operators
(V) Increment and decrement operators
(VI) Conditional operators
(VII) Bitwise operators
(VIII)Special operators
Arithmetic operators:
Arithmetic operators are used to do arithmetic calculations. There are two types
(I) Binary operators
(II) Unary operators
(I) Binary operators:
Binary operators need two operands for operations. They are
Operator Operation Example
+ addition x=5+3
- subtraction y=x-4
* multiplication z=9*2
/ division g=5/3 = 1 or 1.67
% (mod) remainder after integer
Division x=5%3=2
(II) Unary operator:
Unary operators need only one operands for operation. They are
Operator Operation Example
- Unary minus -10
++ Increment ++i
-- Decrement --i

Integer Arithmetic Expression:
When both the operands in a single arithmetic expression are integers, the expression is called an integer expression and the operation is called integer arithmetic. It always yields an integer value.
Example: if a = 14 and b = 4
a – b = 10 a * b = 56
a / b = 3 (decimal part truncated) a % b = 2 (remainder of division)
Real Arithmetic Expression:
An arithmetic operation involving only real operands is called real arithmetic. A real operand may assume values either in decimal or exponential notation.
Ex: X = 6.0 / 7.0 = 0.857
Y = -2.0 / 3.0 = -0.66667
Mixed-mode Arithmetic Expression:
? When one of the operands is real and the other is integer, the expression is called a mixed-mode arithmetic expression.
? If either operand is of the real type, then only the real operation is performed and the result is always a real number.
Ex: X = 15 / 10.0 = 1.5
Y = 15 / 10 = 1
Relational operators:

Relational operators are used to find out the relationship between two operands. They are
Operator Operation Example
> greater than A > B
< less than A < B
>= greater than equal to A >= B
<= less than equal to A <= B
= = equal to A = = B
!= not equal to A !=B

Logical operators:

Logical operators are used to find out the relationship between two or more relational expressions. They are

Operator Meaning
&& AND
|| OR
! NOT



Logical operators return results as indicated in the following table

X Y X&&Y X||Y
T T T T
T F F T
F T F T
F F F F
where
X,Y - relational expressions
T - true value 1
F - false value 0
Assignment operators:
Assignment operators are used to assign the result of an expression or variable
v op=exp is equal to v = v op (exp)
where
v - variable
op - operator
exp – expression
Example:
x + =y is equal to x = x + y
x = x + z
Increment and decrement operators:
There are two special operators in c to control the loops in an effective manner. These operators are called increment and decrement operators.

(I) Increment operator:
++ is the increment operator. This adds 1 to the value contained in the variable. The general form is
variable ++ OR ++variable
The first form (postfix) uses the variable and increments afterwards. The second form (prefix) increments the variable and then use it.
Example:
a++ means a = a + 1
++a means a = a + 1
a = b ++ means a = b and b = b + 1
a = ++ b means b = b +1 and a = b

(II) Decrement operator:
-- is the decrement operator. This subtracts 1 from the value contained in the variable. The general form
Variable -- OR -- variable
The first form (postfix) uses the variable and decrements afterwards. The second form (prefix) decrements the variable and then use it.
Example:
a-- means a = a - 1
--a means a = a - 1
a = b -- means a = b and b = b - 1
a = -- b means b = b -1 and a = b
Conditional operators:
The conditional operators ? and : are used to build simple conditional expression. It has three operands. So it is called ternary operator. The general form is
expression1 ? expression2 : expression3;
Expression1 is evaluated first. If it is true expression2 is evaluated. If expression1 is false expression3 is evaluated.
Example:
Big = a > b ? a : b
In this condition a > b is tested first. If it is true big = a else big = b.
Bitwise operators:
Bitwise operators are used to do bit by bit operation. The table given below lists the operators and its meaning
Operator Meaning
& bitwise AND
| bitwise OR
^ bitwise exclusive OR
>> bitwise right shift
<< bitwise left shift
~ bitwise complement
Bitwise AND (&)
This operation is carried out between two bit patterns.
Example:
Let x = 0101 and y = 1101
x & y = 0101
Bitwise OR (|)
This operation is carried out between two bit patterns.
Example:
Let x = 0101 and y = 1101
x & y = 1101
Bitwise exclusive OR (^)
This operation is carried out between two bit patterns.
Example:
Let x = 0010 and y = 1010
x ^ y = 1000
Bitwise left shift (<<)
This operation is used to shift the bit pattern left. This operation needs two operands.
(I) A bit pattern.
(II) An integer that represents the number of shifts.
Example:
Let x = 00110011
x << 2 = 00 110011 00
| |
Shifted out filled with zeros
The resulting bit pattern is 11001100
Bitwise right shift (>>)
This operation is used to shift the bit pattern right. This operation needs two operands.
op >> n
op? A bit pattern.
n? An integer that represents the number of shifts.
Example:
Let x = 00110011
x >> 2 = 00 110011 00
| |
filled with zeros shifted out
The resulting bit pattern is 00110011
Bitwise complement (~):
This operator changes all the zeroes to one and ones to zero in the bit pattern.
Example:
Let x = 1100
~x = 0011
Special Operators:
C supports some special operators
comma operator,
sizeof operator
The Comma Operator
? The comma operator can be used to link the related expressions together.
? Comma-linked lists of expressions are evaluated left to right and the value of right-most expression is the value of the combined expression.
? For example, the statement
value = ( x = 10, y = 5, x + y);
first assigns the value 10 to x, then assigns 5 to y and finally assigns 15 to value. Since comma operator has the lowest precedence of all operators, the paranthesis are necessary. Some applications of comma operator are :
In for loops: for ( a = 1, b = 10; a <= b; a++, b--)
In while loops: while ( a = b, b ! = 0)
In exchanging values: t = x, x = y, y = t;
The sizeof Operator
? The sizeof is a compile time operator and when used with an operand, it returns the number of bytes the operand occupies. The operand may be a variable, a constant or a data type qualifier.
Examples: m = sizeof(sum);
n = sizeof(int);
? The sizeof operator is used to determine the length of arrays and structures when the programmer does not know their sizes.
? It is also used to allocate memory space dynamically to variables during execution of a program.
Arithmetic Expressions:
An arithmetic expression is a combination of variables, constants and operators arranged as per the syntax of the language. C can handle any complex mathematical expressions.

Evaluation of Expressions:
Expressions are evaluated using an assignment statement of the form



Variable is any valid C variable name. When the statement is encountered, the expression is evaluated first and the result then replaces the previous value of the variable on the left-hand side. All variables used in the expression must be assigned values before evaluation started.
For example:
x = a+b*c;
total = m1+m2+m3+m4;
stock = purchase-sales;
Precedence of Arithmetic Operators:
An arithmetic expression without parentheses will be evaluated from left to right using the rules of precedence of operators. There are two priority levels:

High priority * / %
Low priority + -

The basic evaluation procedure includes two left-to-right passes through the expression. During the first pass, high-priority operators are evaluated and during the second pass low-priority operators are evaluated.

When a = 9, b = 12, and c = 3, the statement becomes
x = 9 – 12/3 + 3*2-1
and is evaluated as follows
First pass
Step1 : x = 9-4+3*2-1
Step2 : x = 9 – 4+6-1
Second pass
Step3 : x = 5+6-1
Step4 : x = 11-1
Step5 : x = 10
The order of evaluation can be changed by introducing parentheses into an expression. Consider the same expression with parentheses as shown below..
9-12/(3+3)*(2-1)
Whenever parentheses are used, the expressions within parentheses assume highest priority. If two or more sets of parentheses appear, the expression contained in the left-most set is evaluated first and the right-most is evaluated next.
First pass Step1 : 9-12/6 * (2-1)
Step2 : 9 – 12/6 * 1
Second pass Step3 : 9-2 * 1
Step4: 9-2
Third Pass Step5 : 7
Parentheses may be nested and in such cases, evaluation of expression will proceed outward from the innermost set of parentheses.
For example:
9 – (12 / (3 + 3) * 2) – 1 = 4
Where as
9 – ((12/3) + 3 * 2) -1 = -2
Type conversions in Expressions
Automatic Type Conversion:
If the operands are of different types, the lower type is automatically converted to the higher type before the operation proceeds. The result is of the higher type. The following are the rules that are applied while evaluating expressions.
1. All short and char are automatically converted to int.
2. All float are automatically converted to double.
The final result of an expression is converted to the type of the variable on the left of the assignment sign before assigning the value to it. The following changes are introduced during the final assignment.
1. float to int causes truncation of the fractional part.
2. double to float causes rounding of digits
3. long int to int causes dropping of the excess higher order bits.
Casting a Value:
The process of a local conversion is known as casting a value.
The general form of a cast is

Where type-name is one of the standard C data types. The expression may be a constant, variable or an expression.
Example Action
x = (int) 7.5 7.5 is converted to integer by
truncation
a = ( int ) 21.3/ (int) 4.5 evaluated as 21/4
y = (int) (a+b) the result of a+b is converted to int
x = (int) (y + 0.7) if y = 25.5, the result will be 26.

OPERATOR PRECEDENCE AND ASSOCIATIVITY:
Each operator in C has a precedence associated with it. This precedence is used to determine how an expression involving more than one operator is evaluated. The operator at the higher level of precedence are evaluated first . The operator of the same precedence are evaluated either from left to right or from right to left, depending on the level. This is known as the associativity property of an operator.
Consider the following conditional statement
if(x = = 10 + 15 && y < 10), the addition operator has a higher priority than the logical operator (&&) and the relational operator (= = and < ). The addition of 10 and 15 is executed first. if ( x = = 25 && y<10).
Suppose x =20 and y = 5, x = = 25 is false and y < 10 is true. The operator < gets high priority than the = =, so y < 10 is tested first and then x = =25 is tested. Finally we get if( FALSE && TRUE).
Because one of the conditions is FALSE, the complex condition is FALSE.
The summary of C operators:
Operator Description Associativity Rank
( )
[ ] Function Call
Array element reference Left to right 1
+
-
++
--
!
~
*
&
sizeof Unary Plus
Unary Minus
Increment
Decrement
Logical Notation
One’s Complement
Pointer reference
Address
Size of an object



Right to left



2
*
/
% Multiplication
Division
Modulus
Left to right
3
+
- Addition
Subtraction Left to right 4
<<
>> Left shift
Right shift Left to right 5
<
< =
>
>= Less than
Less than or equal to
Greater than
Greater than or equal to
Left to right
6
==
!= Equality
Inequality Left to right 7
& Bitwise AND Left to right 8
^ Bitwise XOR Left to right 9
| Bitwise OR Left to right 10
&& Logical AND Left to right 11
|| Logical OR Left to right 12
?: Conditional Expression Right to left 13
= *= / = %= += - = Assignment Operators Right to left 14
, Comma Operator Left to right 15

MATHEMATICAL FUNCTIONS:
Mathematical functions such as cos, sqrt, log etc are frequently used in analysis of real-life problems. Most of the C compilers support these basic math functions. In order to use any of the mathematical functions in a program, we should include the line:
#include

Function Meaning
sqrt(x) Square root of x
pow(x,y) x to the power of y
log(x) Natural log of x
fmod(x,y) Remainder of x/y
exp(x) e to the power x
fabs(x) Absolute value of x
ceil(x) x rounded up to nearest integer
floor(x) x rounded down to nearest integer
sin(x) Sine of x
cos(x) Cosine of x
tan(x) Tangent of x

MANAGING INPUT AND OUTPUT OPERATIONS:
Reading, processing, and writing of data are three essential functions of a computer system. There are two methods of providing data to the program variables.
1. Assign values to variables using Assignment Statement
2. input function scanf which can read data from a terminal
For outputting results printf functions can be used.
Each program that uses standard input/output function must contain the statement:
#include
The file name stdio.h is an abbrevation for standard input-output header file. The instruction #include tells the compiler ‘to search for a file named stdio.h and place its contents to the program.
Reading a Character:
getchar() function is used to read a single character from the keyboard. The general form is
variable name = getchar();
where
variable name - user defined character type name
Rules:
(I) variable name on the left hand side should be declared previously.
(II) Variable name should be of character type.
(III) The empty parentheses in the function are a must.
(IV) getchar() function is a part of I/O library. So the header file stdio.h should be included in the program.
Example:
char n;
n = getchar();



The following are character test functions.(we have to include #include)

Function Test
isalnum(c) Is c an alphanumeric character?
isalpha(c) Is c an alphabetic character?
isdigit(c) Is c a digit?
islower(c) Is c a lower case letter?
isprint(c) Is c a printable character?
ispunct(c) Is c a punctuation mark?
isspace(c) Is c a white space character?
isupper(c) Is c an upper case letter?

Writing a Character:
putchar() function
putchar() function is used to display a single character on the computer screen. The general form is
putchar(variable_name);
Example:
char n;
n = getchar();
putchar(n);
The first statement declares n as a character type variable. The second statement assigns a character value to n. the putchar() statement display the value of n on the screen.

FORMATTED INPUT AND OUTPUT:
Formatted Input
scanf() function
scanf() function is used to give data to the variables using keyboard. The general format is
scanf(“control string”,&var1,&var2,….varn);
where
(i) Control string gives the format of data to the variables. The general form is %w data-type
Where,
% - conversion specification indicator
w - width of input data (optional)
data-type - type of data given to the variables
(ii) The statement symbol (&) before each variable name is called address operator. This evaluates the address of the variable. In the case of a string data, the variable name is not preceded by the symbol &
Rules:
(I) Variable names should be separated by comma.
(II) The number of format specification contained in the control string should match with the number of variables in order.
(III) Format specification in the control string can be continuous or can be separated by blank space.
(IV) Each variable name must be preceded by an ampersand symbol (&) except string.
Conversion character table:
Character Meaning
c single character
d decimal integer
e floating point value
f floating point value
g short integer
i decimal / hexa decimal / octal integer
o octal integer
s string
u unsigned decimal integer
x hexa decimal integer
Example:
scanf (“%d”, &a);
This statements reads a integer data and assigns to variable a.
scanf (“%f”, &a);
This statements reads a floating point data and assigns to variable a.
scanf (“%d %f %d”, &a, &b, &c);
scanf (“%c”, & sex);
scanf (“%s %c”, name, &sex);
scanf (“%4d”, &a);
This statement is used to read a integer data of width 4. if the number exceeds four digits the first four digits will be assigned to the variable a.
scanf(“%5f”, &a);
This reads a five digit floating point number and assigns to variable a.
scanf (“%20s”, name);
This reads a 20 characters string and assigns to variable name. if the input exceeds 20 characters, the first 20 characters will be assigned.

Formatted output:
printf() function
printf() function is used to output the results of the program to the user through VDU. The general form is
printf(“control string”, list)
where
(I) Control string gives the format of data to be displayed on the VDU. The general form is
%w.p data-type
where
% - conversion specification indicator
w - width of output data (optional)
p - number of digits after decimal point or number of characters to be displayed from a string.
data-type – type of output data
(II) The list contains the list of variables , constants, array names to be print.
The general format of control string to output integer
%wd
Where
w = width of the data (optional)
d = conversion character for integer
Example:
The examples given below explains the output a number x=1999 under different formats
Format Meaning
printf(“%d”,x) 1999
printf(“%4d”,x) 1999
printf(“%5d”,x) 1999
printf(“%-5d”,x) 1999
printf(“%07d”,x) 0001999
printf(“%4d”,-x) -1999
Printing of real numbers:
The general form of control string to output real numbers is
%w.p f or e
Where
w - width of output data
p - number of digits after decimal point
f - conversion character for floating point without exponent
e - conversion character for floating point with exponent
Example:
The example given below explains the output of a number x=123.4678 under different formats.
Format Output
printf(“%8.4”, x); 123.4678
printf(“%f”, x) ; 123.467800
printf(“%8.2f”, x); 123.47
printf(“%e”, x); 1.234678e+02
printf(“%-8.2f”, x) 123.47
Printing strings:
The general format of control string to output string is
%w.ps
Example:
printf(“%s”, place); Nagercoil




Decision Making and Branching:
Decision making statements are used to skip or to execute a group of statements based on the result of some condition. The decision making statements are,
(I) simple if
(II) switch statement
(III) conditional operator statement
(IV) goto statement
Simple if
if(test condition)
{
Statement block;
}
Statement-x;
When this statement is executed, the computer first evaluates the value of the test condition. If the value is true, statement block and next statement are executed sequentially. If the value is false, statement block is skipped and execution starts from statement-x.
Example:
if(category = = SPORTS)
{
marks = marks + bonus_marks;
}
printf(“%f”, marks);
(I) IF……ELSE
if….else statement is used to execute one group of statements if the test condition is true or other group the test condition is false. The general form is
if(test condition)
{
Statement block1;
}
else
{
Statement block2;
}
Next statement
When this statement is executed, the computer first evaluates the value of the test condition. If the value is true, statement block1 is executed and the control is transferred to next statement to next statement. If the value is false, statement block2 is executed and the control is transferred to next statement.









NESTING OF IF……ELSE STATEMENTS
When a series of decisions are involved, we may have to use more than one if….else statement in nested form as follows:
General syntax is
if(test condition-1)
{
if(test condition-2)
{
Statement-1;
}
else
{
Statement-2;
}
}
else
{
statement-3;
}
statement-x;
Example:
if ( A > B)
{
if (A > C)
printf(“%f\n”, A);
else
printf(“%f\n”, C);
}
else
{
if(C>B)
printf( “%f\n”, C);
else
printf(“%f\n”, B);
}
(II) ELSE…IF
Else…if statement is used to take multiway decision. This statement is formed by joining if…..else statements in which each else contains another if…else. The general form is
if(condition1)
statement-1;
else if (condition2)
statement-2;
else if(condition3)
statement-3;
……..
else if(condition n)
statement-n;
else
defaut –statement;
statement-x;
The conditions are evaluated from top to downwards. As soon as a true condition is found , the statement associated with it is executed and the control is transferred to the statement-x. when all the conditions gets false, else part will gets execution.
Example:
if (marks > 79)
grade = “honour”;
else if( marks > 59 )
grade = “first class”;
else if( marks > 49 )
grade = “second class”;
else if( marks > 39 )
grade = “third class”;
else
grade = “Fail”;
printf(“%s\n”, grade);
SWITCH:
C has a built-in multiway decision statement known as switch. The switch statement tests the value of a given variable against a list of case values and when a match is found , a block of statements associated with that case is executed.
The general form is:
switch(expression)
{
case lable1 :
statement block1;
break;
case label2:
statement block2;
break;
…………………….
……………………..
case label n:
statement block n;
break;
}
next statement ;
Example:
#include
main()
{
int day;
printf(“Enter a number between 1 an 7\n”);
scanf(“%d”, &day);
switch(day)
{
case 1:
printf(“Moday”);
break;
……………..
………………
……………..
case 7:
pritnf(“Sunday”);
break;
default:
printf(“Enter a correct number”);
break;
}
}
Conditional operator statement
General format is :
Conditional expression ? expression 1: expression2
Conditional expression is evaluated first. If it is true expression1 is evaluated. If conditional expression is false expression2 is evaluated.
Example:
if (x <0)
flag = 0;
else
flag = 1;
can be written as
flag = (x <0) ? 0: 1;

Goto :
C supports the goto statement to branch unconditionally from one point to another in the program. The goto requires a label in order to identify the place where the branch is to be made. The general form is
goto label; label:
………… statement;
………… (or) …………
………… …………
label: …………
statement; goto label;

Example:
# include< stdio.h>
main()
{
double x,y;
read:
scanf(“%f”, &x);
if (x<0) goto read;
y=sqrt(x);
printf(“%f %f”, x,y);
goto read;
}
Decision Making and looping:
In looping, a sequence of statements are executed until some conditions for termination of the loop are satisfied. A program loop therefore consists of two segments :
1. Body of the loop
2. control statement
The control statement tests certain conditions and then directs the repeated execution of the statements contained in the body of the loop.
The C language provides three loop constructs for performing loop operations.
1. The while statement
2. The do statement
3. The for statement

WHILE STATEMENT
General format is :
while (test condition)
{
Body of the loop;
}

The while is an entry-controlled loop statement. The test-condition is evaluated and if the condition is true, then the body of the loop is executed. After execution of the body , the test condition is once again evaluated and if it is true , the body is executed once again. This process of repeated execution of the body continues until the test condition finally becomes false and the control is transferred out of the loop.
Example:
sum=0; n = 1;
while(n <= 10)
{
sum = sum + n * n;
n = n + 1;
}
printf(“sum = %d\n”, sum);

DO STATEMANT :
In while, the loop statements are executed only if the test condition gets true. The body of the loop may not be executed at once if the condition is not satisfied at the very first attempt.

General format is:
do
{
Body of the loop;
}while(test-condition);
Example: do
{
printf(“ input a number\n”);
number = getnum( );
}while( number > 0);

FOR STATEMENT:
General format is:
for( initialization; test-condition; increment)
{
Body of the loop;
}
Example:
for(i=0; i<5;i++)
{
printf(“%d”, i);
}
When the control enters for loop the variables used in for loop is initialized with the starting value such as I=0,count=0. The value which was initialized is then checked with the given test condition. The test condition is a relational expression, such as I < 5 that checks whether the given condition is satisfied or not if the given condition is satisfied the control enters the body of the loop or else it will exit the loop.
The body of the loop is entered only if the test condition is satisfied and after the completion of the execution of the loop the control is transferred back to the increment part of the loop. The control variable is incremented using an assignment statement such as I=I+1 or simply I++ and the new value of the control variable is again tested to check whether it satisfies the loop condition. If the value of the control variable satisfies then the body of the loop is again executed. The process goes on till the control variable fails to satisfy the condition.
Additional features of the for loop:
We can include multiple expressions in any of the fields of for loop provided that we separate such expressions by commas. For example in the for statement that begins
for( i = 0; j = 0; j < 10, j=j-10)
Sets up two index variables I and j the former initialized to zero and the latter to 100 before the loop begins. Each time after the body of the loop is executed, the value of I will be incremented by 1 while the value of j is decremented by 10.
Just as the need may arise to include more than one expression in a particular field of the for statement, so too may the need arise to omit on or more fields from the for statement. This can be done simply by omitting the desired filed, but by marking its place with a semicolon. The init_expression field can simply be “left blank” in such a case as long as the semicolon is still included:
for(;j!=100;++j)
* The following is an example that finds the sum of the first fifteen positive natural numbers*/
#include < stdio.h >
void main()
{
int I;
int sum=0,sum_of_squares=0;
for(I=0;I < = 30; I+=2) //for loop
{
sum+=I;
sum_of_squares+=I*I;
} //end of for loop
printf(“Sum of first 15 positive even numbers=%d\n”,sum);
printf(“Sum of their squares=%d\n”,sum_of_squares);
}
JUMPS IN LOOP
Jumping out of a loop:
It can be done through
1. break
2. go to
break Statement:
Sometimes while executing a loop it becomes desirable to skip a part of the loop or quit the loop as soon as certain condition occurs, for example consider searching a particular number in a set of 100 numbers as soon as the search number is found it is desirable to terminate the loop. C language permits a jump from one statement to another within a loop as well as to jump out of the loop. The break statement allows us to accomplish this task. A break statement provides an early exit from for, while, do and switch constructs. A break causes the innermost enclosing loop or switch to be exited immediately.
Example program to illustrate the use of break statement.
/* A program to find the average of the marks*/
#include < stdio.h >
void main( )
{
int I, num=0;
float sum=0,average;
printf(“Input the marks, -1 to end\n”);

while(1) // While loop starts
{
scanf(“%d”,&I);
if(I==-1)
break;
sum+=I;
num++ ;
}} end of the program
Continue statement:
During loop operations it may be necessary to skip a part of the body of the loop under certain conditions. Like the break statement C supports similar statement called continue statement. The continue statement causes the loop to be continued with the next iteration after skipping any statement in between. The continue with the next iteration the format of the continue statement is simply:
Skipping a part of a loop
Continue;
Consider the following program that finds the sum of five positive integers. If a negative number is entered, the sum is not performed since the remaining part of the loop is skipped using continue statement.
#include < stdio.h >
void main()
{
int I=1, num, sum=0;
for (I = 0; I < 5; I++)
{
printf(“Enter the integer”);
scanf(“%I”, &num);
if(num < 0)
{
printf(“You have entered a negative number”);
continue;
}
sum+=num;
}
printf(“The sum of positive numbers entered = %d”,sum);
}




Responses


No responses found. Be the first to respond and make money from revenue sharing program.

Feedbacks      
Popular Tags   What are tags ?   Search Tags  
(No tags found.)

Post Feedback


This is a strictly moderated forum. Only approved messages will appear in the site. Please use 'Spell Check' in Google toolbar before you submit.
You must Sign In to post a response.
Next Resource: Poniters and Arrays:-
Previous Resource: Computer - Arrays and Functions :-
Return to Discussion Resource Index
Post New Resource
Category: Computer & Technology


Post resources and earn money!
 
Related Resources

Watch TV Channels



Contact Us    Editors    Privacy Policy    Terms Of Use   

ISC Technologies. 2006 - 2008 All Rights Reserved.