C – LANGUAGE

Introduction to programming languages:-
All the programming languages can be divided into two categories.
Machine oriented languages (or) Low level languages:-
These languages have been designed to give a better machine efficiency,
i.e., Faster program execution.
Eg. : Assembly language, Machine Language.
Problem Oriented Languages (or) High Level Languages :-
These languages have been designed to give a better programming efficiency,
i.e., faster program development.
Eg. : FORTRAN, BASIC, PASCAL etc.,
Steps to learning English language:-

Steps to learning computer (programming) language :-



Introduction to C Language :-
C is a programming language developed at AT & T’s Bell Laboratories of USA in 1972. It was designed and written by a man named “Dennis Ritchie”.
C stands in between the above two [(a) & (b)] categories of languages. That is why it is often called a middle level language, since it was designed to have both: a relatively good programming efficiency (as compared to Machine Oriented Languages) and a relatively good machine efficiency (as a compared to problem oriented languages).
The C character set :
A character denotes any alphabet, digit, or a special symbol used to represent information. Following table shows the valid alphabets, numbers and special symbols allowed in C:

Alphabets A, B, C ... Z
and
a, b, c ... z
Digits 0, 1, 2, 3, 4, 5, 6, 7, 8, 9
Special Symbols ~ à Tilde
! à Exclamation mark
# à Harsh
% à Percentage
^ à Cap or Crown or Carrot
& à Ampersand
* à Asterisk
( à Open parentheses
) à Closing parentheses
_ à Underscore
- à Minus
+ à Plus
= à Equal
| à Pipe
\ à Backward slash { à Open brace
} à Closing brace
[àOpen bracket
] àClosing bracket
: à Colon
; à Semi colon
“à Double quotation mark
’ à Single quotation mark
< à Less than
> à Greater than
, à Comma
. à Dot
? à Question mark
/ à Forward slash

Constants, Variables (Identifiers): -
The alphabets, numbers and special symbols when properly combined form constants, variables and keywords. Let us see what are constants and variables in C. A constant is a quantity that does not change. This quantity can be stored at a location in the memory of the computer. A variable can be considered as a name given to the location in memory where this constant is stored. Naturally that content of the variable can change.
Eg. : 3x2 + 4x + 5 = 0
Here, 3,4, 5 and 0 cannot change, they are called constants, whereas the quantities x can vary or change hence this is called a variable.
Types of C constants :-
C constants can be divided into two major categories:
Primary constants,
Secondary constants

Rules for constructing Integer Constants :
An integer constant must have at least one digit.
It must not have a decimal point
It could be either positive or negative
If no sign precedes an integer constant it is assumed to be positive
No commas and blanks are allowed within an integer constant.
The allowable range for integer constants is –32768 to +32767 (Because an integer constant occupies 2 bytes of memory in computer).
Integer constants must fall within this range because the IBM compatible microcomputers are usually 16 bit computers which cannot support a number falling out side the above mentioned range. For a 32 bit computer of course the range would be much larger.
E.g. 450, + 590, -267
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.


Rules for fractional form:-
A real constant must have at least one digit
It must have a decimal point
It could be either positive or negative. Default sign is positive
No commas & blanks are allowed within a real constant.
E.g. 296.0, +1.272, -48.01
Rules for Exponential form:-
The exponential form of representation of real constants is usually used if the value of the constant is either too small or too large. If however does not 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.
The mantissa part and the exponential part should be separated by a letter ‘e’
The mantissa part may have a positive or negative sign. Default sign is positive.
The exponent must have at least one digit which must be a positive or negative integer. Default sign is positive.
Range of real constants expressed in exponential form is –3.4e38 to 3.4e38. (Because a floating point constant occupies 4 bytes of memory in computers).
Eg. : +5.2e-7,
4.5e8,
-0.2e+3
Note: 5.2e-7 = 5.2 x 10-7
4.5e8 = 4.5 x 108
Rules for constructing character constants :-
A character constant is either 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( ’ ).
Eg. : ‘A’ is not a valid character constant
’A’ is a valid character constant.
The maximum length of a character constant can be 1 Character.
Range of character constants expressed in signed integers is –128 to +127 (or) expressed in unsigned integers is 0 to 255. Because a character constant occupies 1 byte of memory in computer.
Rules for constructing variable names :-
A variable name is any combination of 1 to 8 alphabets, digits, or underscores ( _ ). Some compilers allow variable names whose length could be up to 40 characters. Still, it would be safer to stick to the rule of 8 characters.
The 1st character in the variable name must be an alphabet.
No commas or blanks are allowed within a variable name.
No special symbol other than an underscore ( _ ) can be used in a variable name.
Eg. : empname, bas_sal, varl …. etc.
Data Types of C Variables :-
In C, a quantity which may vary during program execution is called a variable. Variable names are names given to locations in the memory of computer where different data are stored. These locations can contain integer, real or character constants. In any language, the type of variables that it can support depends on the types of data that is can handle. This is because a data stores in a location with a particular type of variable name can hold only that type of data. For example, a data stored in a memory location with an integer variable name, must be an integer data, one stored in location with a real variable name must be a real data and the one stored in location with a character variable name must be a character data. The following are the keywords for these data types.
Integer data type à int
Real data type à float
Character data type à char


C Keywords:
Keywords are the words whose meaning has already been explained to the C compiler (or in abroad 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. The keywords are also called “Reserved Words”. There are only 32 keywords available in C, following is the list of keywords in C.
auto double if static
break else int struct
case enum long switch
char extern near typedef
const float register union
continue far return unsigned
default for short void
do goto signed while
C Instructions ( Expressions (or) Statements):
There are basically four types of instructions in C.
(a) Type Declaration Instruction
(b) Input / Output Instruction
(c) Arithmetic Instruction
(d) Control Instruction
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 usually written at the beginning of the C program.
Eg. : int basic;
float hra, ta, da;
char gender;


Input / Output Instruction :
These are used to perform the function of supplying input data to a program and obtaining the output results from it.
Eg. : scanf (“%d”,&basic); /* input instruction .*/
printf (“%d”, basic); /* output instruction.*/
Arithmetic Instructions :
A C arithmetic instruction consists of a variable name on the left hand side of = and variable names and 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 /.
Eg. : perimet = 2 * (b+l);
Here, *, + are arithmetic operators,
= is the assignment operator,
2 is an integer constant,
perimet, b, l are the variables, which are declared in declaration section.
The variables and constants together are called ‘operands’ which are operated upon by the “arithmetic operators” and the result is assigned, using the assignment operator (=), to the variable on left hand side.
Note :
* C allows only one variable on left hand side of =
i.e. z = k*l is legal,
Whereas k*l = z is illegal
* A statement similar to arithmetic instruction is many times used for storing character constants in character variables.
i.e. a = ’F’ is also an arithmetic instruction.
* Arithmetic operations can be performed on ints, floats, and chars.
i.e. z = ’x’ + ’y’ is perfectly valid.
Since the addition is performed on the ASCII values of the characters and not on characters themselves. The ASCII (American Secret (Standard) Code for Information Interchange) of ‘x’ and ‘y’ are 120 and 121, and hence can definitely be added.
Operators:-
1) Unary Operators :-
Any operator which operates on only one operand is called Unary operator. These are :
- à Unary minus, used to negate any number
++ à Increment by 1
-- à Decrement by 1
sizeof (variable) à This is used to return the memory size of variable in no. of bytes.
Eg. : (i) a = -a;
a++; This is called post increment
++a; This is called pre increment
a--; This is called post decrement
--a; This is called pre decrement
a = sizeof (int); which returns 2
i.e., The memory size of integer.
(2) Binary (or) Arithmetic Operators :-
Any operator which operates on two operands is called binary operator. Arithmetic operators are used to calculate arithmetic expressions. The operators are :
* à Multiplication
/ à Division
% à Modulus (or) Remainder Operator
+ à Addition
- à Subtraction
. Eg. : a = 25%4; which gives the value 1 for a
(3) Relational Operators :-
These operators are used to compare two variables.
< à Less than
< = à Less than & equal to
> à Greater than
> = à Greater than or equal to
= = à Equal to
! = à Not equal to
(4) Logical Operators :
These operators are used to compare multiple conditions at a time.
&& à And
|| à Or
! à Not
Assignment Operators :
These operators are used to store values of some variables into another.
=, *=, /=, %=, +=, - =, &=, ^=, |=, <<=, >>=
Eg. : (i) a = 15%4;
(ii) a * = 4; which is also written as a=a*4; which means that a is multiplied by 4 and restores it.
Bitwise Operators :
These operators are used to operate with bits (i.e. 0’s and 1’s).
~ à One’s complement
<< à Left Shift
>> à Right Shift
& à Bitwise AND
^ à Bitwise XOR (Exclusive OR)
| à Bitwise OR
Structure of C :
C language has a structured way for constructing a C program, that is why C is called a structured programming language.



[ Documentation Section ]
[ Linkage Section ]
[Global declaration section ]
< main ( )
{
Local declaration section;
……………………..
……………………..
Body of main ( ) ;
……………………..
……………………..
} >

[ Function definition section ]
Documentation section :
This section is used to give the information about the program to other users.
This is also called comments section
Comment about programme should be enclosed within /*...*/.
Any no. of comments can be given at any place in the program.
Comments cannot be nested
i.e., /* calculation of /* simple x/ interest */ is invalid.
A comment can be split over more than one line.
Eg. : /* calculation of simple interest.
Author : Y. Kanitkar
Date : 25-07-2005 */
Linkage Section:
This linkage section is used to link one file to another. For this we use the preprocessor directive #include. This directive causes one file to be included in another. The preprocessor command for file inclusion books like this :
# include “filename” (or) # include <>
And it simply causes the entire contents of filename to be inserted into the source code at that point in the program.
The meanings of each of these forms :
# include “filename” : This command would look for the given file in the current directory as well as the specified list of directories as mentioned in the include search path that might have been set up.
E.g:- # include “C:\TC\decimal.C”
# include : This command would look for the given file in the specified list of directories only.
Eg. : # include
Global declaration section :
This section is used to declare the global variables i.e., This global variables are used in entire program.
Eg. : int sal;
float hra;
In this section we have another feature, that is macro definition #define directive or more commonly just a “macro”.
Syntax for macro definition.
# define
Eg. : #define PI 3.1415
Here, PI is called macro template,
3.1415 is called macro expansion
In C programming it is customary to use capital letters for macro templates.
Macro templates and macro expansions are separated by blanks or tabs.
Space between # and define is optional
Macro definition is never to be terminated by a semi colon (;).
main ( ) :
Any C program is nothing but a combination of functions. main ( ) is one such functions. Empty parentheses {( )} after main are necessary.
The set of statements belonging to a function are enclosed within a pair of braces ({}).
Any variable used in the program must be declared before using it.
Eg. : int p, n;
float r, si;
Function definition section :
This section is used to define user defined functions, if necessary.
In the above structure of C, the documentation section, linkage section, global declaration section, and function definition section are optional, and the main ( ) block is essential for every C program.
Note :
Statement in between [ ] is optional
Statement in between < > is essential
Rules for constructing C program :
Blank spaces may be inserted between two words to improve the readability of the statement. However, the blank spaces are not allowed within a variable, constant or keyword.
Usually all statements are entered in small case letters.
C has no specific rules for the position at which a statement is to be written. That is why it is often called a free-form language.
Any C statement always ends with a semi colon (;)
First C Program :
/* Purpose : Calculation of simple interest.
Author : Y. Kanitkar
Date : 25-7-2005
*/
# include <>
main ( )
{
int p, n;
float r, si;
p = 5000; /* Principle value */
n = 5; /* No. of years */
r = 8.5; /* Rate of interest */
si = p*n*r/100; /* Formula for simple interest */
printf (“Simple Interest is :%f”, si);
}
Note :
printf ( ) : it is used to print values of the variables on the screen.
The general form,
printf (“”, );
Format string could be
%f for real values (float)
%d for integer values
%c for character values.
Calculation of simple interest, using scanf() function.
main ( )
{
int p, n;
float r, si;
printf (“\n Enter principle, no.of years, rate:”) ;
scanf (“%d %d %f”, &p, &n, &r);
si = p*n*r/100;
printf (“\n simple interest = Rs. %f /-“, si);
}
Note :
scanf ( ) : This function is used to take values from keyboard. The ampersand (&) before the variable in the scanf statement is a must. & is a pointer operator, it is called address of value operator.
CONTROL INSTRUCTIONS IN C
As the name suggests the “Control Instructions” enables us to specify the order in which the various instructions in a program are to be executed by the computer. In other words the control instructions determine the “flow of control” in a program. There are 4 types of control instructions in C. They are :
Sequence control instruction,
Selection or Decision control instruction,
Repetition or loop control instruction,
Case control instruction.
(a) Sequence Control Instruction :
The Sequence Control Instruction ensures that the instructions are executed in the same order in which they appear in the program.
The flow of control looks like this :









(b) Selection or Decision Control Instruction :
Decision control instruction allow the computer to take a decision as to which instruction is to be executed next depending on condition, hence is called conditional statement.
if :-
Syntax :- if ()
Statement(s);
Here, if the given condition is true then the statements in if block will execute, otherwise that statements will ignore by the compiler.
Eg. : if (a = = o)
printf (“ a is vanish”);

(2) if .. else :-
Syntax : if ()
statement(s);
else
statement(s);


Here, if the given condition is true then the if block will execute, or if the condition is false then the else block will executed.
Eg : if (a < 0)
printf (“a is a –ve value”);
else
printf (“a is a +ve value”);
(3) if.. else if :-
syntax : if ()
statements1;
else if ()
statements2;
else
statements3;
Eg. : if (a < 0)
printf (“a is –ve”);
else if (a>0)
printf (“a is +ve”);
else
printf (“a is zero”);
(4) Nested if … else :-
Syntax :- if ()
{
statements ;
if ()
statements;
……
……
else
statements;
}
else
statements;
else if ladder :-
Syntax :-
if ()
Statements;
else if ()
Statements;
else if ()
Statements;
……….
……….
else
Statements;
Conditional operator (or) Ternary Operator :-
The conditional operators ? and : are some times called ternary operators since they take three arguments. In fact, they form a kind of foreshortened if .. then .. else.
Syntax :- Expression 1? Expression 2 : expression 3;
Here, if expression 1 is true (that is if the value is non-zero), then the value returned will be expression 2 otherwise the value returned will be expression 3.
Eg. : (i) (a<0) ? printf (“a is –ve”) : printf (“a is +ve”);
(ii) y = ((a>=65 && a<=90) ? 1:0);
Repetition & Loop Control Instructions :-
The Loop Control Instructions helps computer to execute a group of statements repeatedly. The versatility of the computer lies in its ability to perform a set of instruction repeatedly. This involves repeating some portion of the program either a specified number of times or until a particular condition is being satisfied. This repetitive operation is done through a loop control structure.
C allows us three types of loop contract structures viz.,
while
do…while
for
while :-
Syntax : -
[initialize counter;]
while (condition)
{
Body of loop;
[Increment/decrement counter;]
}
Here, the statements within the pair of braces called body of the loop. The parentheses after the while contains a condition. So long as this condition remains true all statements within the body of the loop keep getting executed repeatedly. The variable counter is many a times called either a ‘Loop Counter’ or an ‘index variable’.
Eg. : This loop is used to print 1 to 1000 numbers on the screen.
i = 1;
while (i< = 1000)
{
printf (“\n %d”, i);
i++;
}
do … while :-
Syntax :- do
{
body of do…while;
}while (condition);
The do..while loop works like a while loop. The do…while tests the condition after having executed the statements within the loop. This means that do…while would execute its statements at least once, even if the condition fails for the 1st time itself.
Eg. :- i = 1
do
{
printf (“\n %d”, i);
i ++;
}while (i<=1000);


for :-
This is probably the most popular looping control. The for allows us to specify three things about in a single line :
setting a loop counter to an initial value.
Testing the loop counter to determine whether its value has reached the number of repetitions desired.
Increasing the value of loop counter each time the program segment within the loop has been executed.
Syntax :-
for ([initialize counter]; ; [increment/decrement counter])
{
body of loop;
}







Eg. :
for (i = 1; i< = 1000; i++)
printf (“\n %d”, i);
Multiple initializations in the for loop :
* The initialize counter expression can contain more than one statement separated by a comma,
Eg. : for (i = 2, j = 1; j<=10; j++)
* Multiple statements can also be used in the increment /decrement counter expression of loop.
Eg. : for (i = 2; j = 1; j< = 10; i++; j++)
* Only one expression is allowed in condition expression. This expression may contain several conditions linked together using logical operators.
Eg. : for (i = 2, j = 1; (j<=10 && i<=20); i++, j++)
Nesting of Loops :-
Any loops within another loops are called nested loops.
Eg. :
for (i = 1; i < = 3; i++)
{
for (j = 1; j<=3; j++)
printf (“ %d”, i);
printf (“\n”);
}
The Odd Loop :
The loops that we have used so far executed the statements within them a finite number of times, i.e, decided by user at runtime are called an odd loop.
Eg. :
while (another = = ’y’)
{
printf (“Hello!”);
printf (“Do you want to another display(y/n):”);
scanf (“%c”, &another);
}
break Statement :-
The keyword break allows us to jump out of a loop instantly, without waiting to get back to the conditional test.
Eg. :
i = 2;
while (i<=num-1)
{
if (num %i = = 0)
{
printf (“Given number is not a prime number”);
break;
}
i++;
}
if (i = = num)
printf (“\nGiven number is a prime number”);
continue Statement :
The keyword continue allows us to take the control to the beginning of the loop, bypassing the statements inside the loop which have not yet been executed.
Eg. : /* To print all combinations of 1,2,3 */
for (i = 1; i<=3; i++)
for (j = 1; j<=3; j++)
for (k=1; k<=3; k++)
{
if(i = = j || j = = k || i = = k)
continue;
printf (“%d %d %d”, i, j, k);
}
d) Case control instruction :-
The control statement which 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.




Syntax :
switch (choice variable)
{
case constant 1 : statements; break;
case constant 2 : statements; break;
……….………………………………
………….……………………………
case constant n : statements; break;
default : statements;
}
Here, Choice variable à integer/character variable
Constants à integer/character constant
Eg. :
switch (ch)
{
case 1 : a = b + c; break;
case 2 : a = b – c; break;
case 3 : a = b * c; break;
case 4 : a = b/c; break;
case 5 : a = b%c; break;
default : printf (“\n invalid choice …!”);
}

Note:-
We can use cases in any order.
We can mix integer and character constants in different cases of a switch.
Some times there may not be any statement in some of the cases in switch, but still they might turn out to be useful.
Even if there are multiple statements to be executed in each case there is no need to enclose these within a pair of braces.
If we have no default case, then the program simply falls through the entire switch and continues with the next instruction that follows the control structure.
The break statement when used in a switch takes the control outside the switch. However, use of continue will not take the control to the beginning of switch as one is likely to believe.
A switch may occur within another switch, which is called nested switch statements.
The switch statement is very useful while writing menu driven programs.
We can have after the case is an int constant or a char constant. Even a float is not allowed.
goto statement :
This is used to jump from any statement to another statement in a C program.
Syntax : goto