Saturday, November 14, 2009

C Programming Language - An Overview

Overview of C
 C is a programming language. It it is a structured high level, machine independent language.
 Dennis Ritchie invented C language.
 It supports the programmer with a rich set of built-in functions and operators.
 C is highly portable. C programs written on one computer can run on other computer without making any changes in the program.
 Structured programming concept is well supported in C, this helps in dividing the programs into function modules or code blocks.

Basic structure of C programs
Header file declaration
Global declaration Section
Void Main() function section
{
Declaration Part;
Executable Part;
}
User defined function()
{
Stmts;
}

 Every C program must have one main function. Enclosed in the main function is the declaration and executable parts.
 In the declaration part we have all the variables.
 There is atleast one statement in the executable part.
 The two parts must appear between the opening and closing braces
 User-defined functions are generally placed immediately after the main function although they may appear in any order.

For example
#include
main()
{
/* Printing begins here */
printf (“C is a very good programming language.”);
/* Printing ends here */
}
 The first line is a preprocessor command which adds the stdio header file into our program. Actually stdio stands for standard input out, this header file supports the input-output functions in a program.
 The second line main() tell the compiler that it is the starting point of the program, The opening and closing braces indicates the beginning and ending of the program. All the statements between these two braces form the function body. These statements are actually the C code which tells the computer to do something. Each statement is a instruction for the computer to perform specific task.
 The /* .... */ is a comment and will not be executed, the compiler simply ignores this statement. These are essential since it enhances the readability and understandability of the program. It is a very good practice to include comments in all the programs to make the users understand what is being done in the program.
 The printf() function is a standard inbuild function for printing a given line which appears inside the double quotes. Therefore in the standard output device we can see the following line
C is a very good programming language.
 The next line is again a comment statement as explained earlier.
 The closing brace indicates the end of the program.

The following basic steps is carried out in executing a C Program.
1. Type the C lanuage program.
2. Store the program by giving a suitable name and following it with an extension .c
3. Compile the program
4. Debug the errors if any, that is displayed during compile.
5. Run the program.

Character Set
The character set in C Language can be grouped into the following categories.
1. Letters – Upper case A-Z & Lower Case a-z
2. Digits - 0-9
3. Special Characters – Like , * : ; etc
4. White Spaces
 Blank Space
 Horizontal Tab
 Carriage Return
 New Line
 Form Feed
Keywords and Identifiers

 Every word in C language is a keyword or an identifier. Keywords in C language cannot be used as a variable name. They are specifically used by the compiler for its own purpose and they serve as building blocks of a c program.

The following are the Keyword set of C language.
.auto .else .register .union
.break .enum .return .unsigned
.case .extern .short .void
.char .float .signed .volatile
.const .for .size of .while
.continue .goto .static .
.default .if .struct .
.do .int .switch .
.double .long .typedef .

 some compilers may have additional keywords listed in C manual.

Identifiers or variables
 Identifiers refers to the name of user-defined variables, array and functions.
 A variable is a value that can change any time.
 It is a memory location used to store a data value
The identifiers must conform to the following rules.
1. First character must be an alphabet (or underscore)
2. Identifier names must consists of only letters, digits and underscore.
3. A identifier name should have less than 31 characters.
4. Any standard C language keyword cannot be used as a variable name.
5. A identifier should not contain a space.

Example of variable names are

Sun
Emp_name
average1

Examples of Invalid Variable names are

1s3
(area)
%abc
Declaration of Variables
 Every variable used in the program should be declared to the compiler. The declaration does two things.

1. Tells the compiler the variables name.
2. Specifies what type of data the variable will hold.

The general format of any declaration

datatype v1, v2, v3, ……….. vn;

Where v1, v2, v3 are variable names. Variables are separated by commas. A declaration statement must end with a semicolon.

Example:
Int sum;
Int number, salary;
Double average, mean;
Declaring Variable as Constant
 The values of some variable may be required to remain constant through-out the program. We can do this by using the qualifier const at the time of initialization.

Example:
onst int class_size = 40;
 The const data type qualifier tells the compiler that the value of the int variable class_size may not be modified in the program.

Volatile Variable
 A volatile variable is the one whose values may be changed at any time by some external sources.

Example:
volatile int num;

The value of data may be altered by some external factor, even if it does not appear on the left hand side of the assignment statement. When we declare a variable as volatile the compiler will examine the value of the variable each time it is encountered to see if an external factor has changed the value.

Constants
 A constant value is the one which does not change during the execution of a program.
Types of Constants

1.Integer Constants
2.Real Constants
3.Single Character Constants
4. String Constants

Integer Constants
 An integer constant is a sequence of digits.
 There are 3 types of integers namely decimal integer, octal integers and hexadecimal integer.
 For example int a=7;

Real Constants
 Real Constants consists of a fractional part in their representation.
 Example of real constants are
0.0026
-0.97
435.29
+487.0
Single Character Constants
 A Single Character constant represent a single character which is enclosed in a pair of single quotation symbols.
 All character constants have an equivalent integer value which are called ASCII Values.
 Example for character constants are
'5'
'x'

String Constants
 A string constant is a set of characters enclosed in double quotation marks.
 The characters in a string constant sequence may be a alphabet, number, special character and blank space.
 Example of string constants are
"VISHAL"
"1234"
"God Bless"
"!.....?"

Data Types

 It tells what type of value in the variable
 A data type that can have only one value at a time
 C language data types can be broadly classified as
Primary data type
Derived data type
User-defined data type

Primary data type
All C Compilers accept the following fundamental data types
Data type Specification Range of values

Integer int -32768 to +32767

Character Char -128 to 127

Floating Point float 3.4 e-38 to 3.4 e+38

Double double 1.7 e-308 to 1.7 e+308

Void void


Defining Symbolic Constants

 A symbolic constant value can be defined as a preprocessor statement and used in the program as any other constant value.
 The general form of a symbolic constant is

# define symbolic_name value of constant

Valid examples of constant definitions are :

# define marks 100
# define total 50
# define pi 3.14159
 These values may appear anywhere in the program, but must come before it is referenced in the program.
Introduction to Operators
 An operator is a symbol which helps the user to command the computer to do a certain mathematical or logical manipulations.
 Operators are used in C language program to operate on data and variables.
 C has a rich set of operators which can be classified as

1. Arithmetic operators
2. Relational Operators
3. Logical Operators
4. Assignment Operators
5. Increments and Decrement Operators
6. Conditional Operators
7. Bitwise Operators
8. Special Operators

Arithmetic Operators
 All the basic arithmetic operations can be carried out in C.
 Both unary and binary operations are available in C language.
 Unary operations operate on a singe operand, therefore the number 5 when operated by unary – will have the value –5.
 Binary needs at least two operand
 The operators are + , - , * , / , % (Modulus)
 Examples of arithmetic operators are

x + y
x - y
-x + y
a * b + c
-a * b etc.,
here a, b, c, x, y are known as operands.
 The modulus operator is a special operator in C language which evaluates the remainder of the operands after division.

Example
#include
void main()
{
int numb1, num2, sum, sub, mul, div, mod; //declaration of variables
scanf (“%d %d”, &num1, &num2); //inputs the operands

sum = num1+num2; //addition of numbers and storing in sum.
printf(“\n Thu sum is = %d”, sum); //display the output

sub = num1-num2; //subtraction of numbers and storing in sub.
printf(“\n Thu difference is = %d”, sub); //display the output

mul = num1*num2; //multiplication of numbers and storing in mul.
printf(“\n Thu product is = %d”, mul); //display the output

div = num1/num2; //division of numbers and storing in div.
printf(“\n Thu division is = %d”, div); //display the output

mod = num1%num2; //modulus of numbers and storing in mod.
printf(“\n Thu modulus is = %d”, mod); //display the output
}

Relational Operators
 it is required to compare the relationship between operands and bring out a decision and program accordingly.
 The relational operators are <,> , <=, >= ,==, !=
 A simple relational expression contains only one relational operator and takes the following form.

exp1 relational operator exp2

Where exp1 and exp2 are expressions, which may be simple constants, variables or combination of them.
Logical Operators
 Logical operators are used to compare or evaluate logical and relational expressions.
 Logical operators are && (AND),|| (OR) , !(Not)
 Logical AND (&&)
o This operator is used to evaluate 2 conditions or expressions with relational operators simultaneously. If both the expressions to the left and to the right of the logical operator is true then the whole compound expression is true.
Example a > b && x = = 10
The expression to the left is a > b and that on the right is x == 10 the whole expression is true only if both expressions are true i.e., if a is greater than b and x is equal to 10.
 Logical OR (||)
o The logical OR is used to combine 2 expressions or the condition evaluates to true if any one of the 2 expressions is true.
Example a < are =",+=",*=",-=",/=",%="" oper =" exp;" x =" a" m =" 5;" y =" ++m;" m =" 5;" y =" m++;" a =" 10;" b =" 15;" x =" (a"> b) ? a : b

Here x will be assigned to the value of b. The condition follows that the expression is false therefore b is assigned to x.
o/P
nput 2 integers : 34 45
The largest of two numbers is 45

Bitwise Operators
 C has a distinction of supporting special operators known as bitwise operators for manipulation data at bit level.
 A bitwise operator operates on each bit of data.
 Those operators are used for testing, complementing or shifting bits to the right on left.
 Bitwise operators may not be applied to a float or double.
 Bitwise operators are &{AND),|{OR}, ^(EXCLUSIVE), >> (shift right)
<< (shift left) Special Operators  The Comma Operator  The size of Operator The Comma Operator  The comma operator can be used to link related expressions together.  A comma-linked list of expressions are evaluated left to right and 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 10 to x and 5 to y and finally assigns 15 to value. Since comma has the lowest precedence in operators the parenthesis is necessary. Some examples of omma operator are In for loops: for (n=1, m=10, n <=m; n++,m++) In while loops While (c=getchar(), c != ‘10’) Exchanging values t = x, x = y, y = t; The size of Operator  The operator size of gives the size of the data type or variable in terms of bytes occupied in the memory.  the operand may be a variable, a constant or a data type qualifier.  Example m = sizeof (sum); n = sizeof (long int); k = sizeof (235L);  The size of operator is normally used to determine the lengths of arrays and structures when their sizes are not known to the programmer.  It is also used to allocate memory space dynamically to variables during the execution of the program. Decision Making – Branching Branching  C language provides statements that can alter the flow of a sequence of instructions. These statements are called control statements.  These statements help to jump from one part of the program to another. The control transfer may be conditional or unconditional. if Statement:  The simplest form of the control statement is the If statement.  It is very frequently used in decision making and allowing the flow of program execution. The If structure has the following syntax if (condition) statement;  The statement is any valid C’ language statement and the condition is any valid C’ language expression,frequently logical operators are used in the condition statement.  The condition part should not end with a semicolon, since the condition and statement should be put together as a single statement.  If the condition is true then perform the following statement  If the condition is fake the computer skips the statement and moves on to the next instruction in the program. Example program int i; printf ("Type in an integer"); scanf ("%ld",&i); if (i == 0) printf ("The number was zero"); if (i > 0) printf ("The number was positive");
if (i <> 0)
{
printf ("That number was positive!");
}
else
{
printf ("That number was negative or zero!");
}

Nested if Statement
 The if statement may itself contain another if statement is known as nested if statement.

Syntax:
if (condition1)
if (condition2)
statement-1;
else
statement-2;
else
statement-3;

 One block of code will only be executed if two conditions are true. Condition 1 is tested first and then condition 2 is tested.
 The second if condition is nested in the first.
 The second if condition is tested only when the first condition is true else the program flow will skip to the corresponding else statement.
 For example
if (i > 2)
{
if (i <> 10 && b > 20 && c < a =" 10"> //include the standard stdio.h header file
void main () //start the function main
{
int marks //variable declaration

printf ("Enter marks\n") //message to the user
scanf ("%d", &marks) //read and store the input marks.

if (marks <= 100 && marks >= 70) //check whether marks is less than 100 or greater than 70
printf ("\n Distinction") //print Distinction if condition is True
else if (marks >= 60) //else if the previous condition fails Check
printf("\n First class") //whether marks is > 60 if true print Statement
else if (marks >= 50) //else if marks is greater than 50 print
printf ("\n second class") //Second class
else if (marks >= 35) //else if marks is greater than 35 print
printf ("\n pass class") //pass class
else
printf ("Fail") //If all condition fail apply default condition print Fail

The Switch Statement:
 The switch statement allows a program to select one statement for execution out of a set of alternatives.
 During the execution of the switch statement only one of the possible statements will be executed the remaining statements will be skipped.
 The usage of multiple If else statement increases the complexity of the program since when the number of If else statements increase it affects the readability of the program and makes it difficult to follow the program.
 The switch statement removes these disadvantages by using a simple and straight forward approach.

The general format of the Switch Statement is :
switch (int or char expression)
{
case constant : statement;
break; /* optional */

case constant : statement;
break;
case constant : statement;
break;

default : statement;
break;
}

 When the switch statement is executed the control expression is evaluated first and the value is compared with the case label values in the given order.
 If the label matches with the value of the expression then the control is transferred directly to the group of statements which follow the label.
 If none of the statements matches then the statement against the default is executed.
 Sample Code
#include
void main ()
{
int num1, num2, result
char operator

printf ("Enter two numbers")
scanf ("%d %d", &num1, &num2)
printf ("Enter an operator")
scanf ("%c", &operator)
switch (operator)
{
case '+':
result = num1 + num2
break
case '-':
result = num1 - num2
break
default:
printf ("\n unknown operator")
result = 0

break
}
printf ("%d", result)
}
 In the above program the break statement is need after the case statement to break out of the loop and prevent the program from executing other cases.

Decision Making – Looping
 During looping a set of statements are executed until some conditions for termination of the loop is encountered.
 In looping process in general would include the following four steps
1. Setting and initialization of a counter
2. Exertion of the statements in the loop
3. Test for a specified conditions for the execution of the loop
4. Incrementing the counter
 The test may be either to determine whether the loop has repeated the specified number of times or to determine whether the particular condition has been met.
The While Statement:
The simplest of all looping structure in C is the while statement. The general format of the while statement is:

while (test condition)
{
body of the loop
}

 Here the given test condition is evaluated and if the condition is true then the body of the loop is executed.
 After the 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 program for generating ‘N’ Natural numbers using while loop:

void main()
{
int i;
i=0;
while(i < 10)
{
printf ("Hello\n");
i++;
}}
 The while loop then checks whether the value of I is less than n i.e., the user entered number if it is true then the control enters the loop body and prints the value of I using the printf statement and increments the value of I to the next natural number this process repeats till the value of I becomes equal to or greater than the number given by the user.
The Do while statement:
 The do while loop tests at the bottom of the loop after executing the body of the loop. Since the body of the loop is executed first and then the loop condition is checked we can be assured that the body of the loop is executed at least once.
 The syntax of the do while loop is:

Do
{
statement;
}
while(expression);
 the statement is executed, then expression is evaluated. If the condition expression is true then the body is executed again and this process continues till the conditional expression becomes false.
 When the expression becomes false. When the expression becomes false the loop terminates.
For example
void main()
{
int i;
i=0;
do
{
printf ("Hello\n");
i++;
}while(i < 10);

For Loop:
 The for loop provides a more concise loop control structure. The general form of the for loop is:
for (initialization; test condition; increment/decrement)
{
body of the loop
}
 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.
 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.
For example
void main()
{
int i;
for (i = 0; i < 10; i++)
printf ("Hello\n");
}

No comments:

Post a Comment