Sei sulla pagina 1di 65

A Brief History of the C Language

You might be wondering about the origin of the C language and where it got its name. C
was created by Dennis Ritchie at the Bell Telephone Laboratories in 1972. The
language wasn’t created for the fun of it, but for a specific purpose: to design the UNIX
operating system (which is used on many computers).

Because C is such a powerful and flexible language, its use quickly spread beyond Bell
Labs. Programmers everywhere began using it to write all sorts of programs. Soon,
however, different organizations began utilizing their own versions of C. In response to
this problem, the American National Standards Institute (ANSI) formed a committee in
1983 to establish a standard definition of C, which became known as ANSI Standard C.
With few exceptions, every modern C compiler has the ability to adhere to this standard.

Now, what about the name? The C language is so named because its predecessor was
called B. The B language was developed by Ken Thompson of Bell Labs.

General characteristics of C

C is a middle level language. Its characteristics lie between those of problem oriented
language such as FORTRAN, Basic, Pascal and low level Languages. It is a procedural
language. It is reliable, efficient, simple and easy to understand. The approach of
programming in C is bottom-up. The modularity feature of C language, i.e. breaking the
problem into modules called the function makes it easier to organize and maintain.

PREPARING TO PROGRAM

You should take certain steps when you’re solving a problem. First, you must define the
problem. If you don’t know what the problem is, you can’t find a solution! Once you
know what the problem is, you can devise a plan to fix it. Once you have a plan, you can
usually implement it. Once the plan is implemented, you must test the results to see
whether the problem is solved. This same logic can be applied to many other areas,
including programming.

When creating a program in C (or for that matter, a computer program in any language),
you should follow a similar sequence of steps:

1. Determine the objective(s) of the program.


2. Determine the methods you want to use in writing the program.
3. Create the program to solve the problem.
4. Run the program to see the results.
Data types and its information
Integer types—these are whole numbers without any decimal portion. They can be
signed or unsigned. They are also classified as short and long integers depending on their
value.
Floating point types—these are real numbers (with decimal portion) which are stored in
32 bits with 6 digits of precision. There are two types of such numbers in C. These are
float and double. The data type double offers more precision when compared to float data
type.
Character type—A single character is defined as a char data type. They are stored in one
byte of internal storage. They can be signed or unsigned. Signed char can have values
between 0 and 255 while unsigned have –128 to 127 ranges.

User defined data types—Apart from the above, the programmers can define their own
data types using the typedef keyword.

Fundamental Type Derived Types Description Minimum Range


Char Signed char Mininum of 8 bits 0 to 127
Unsigned char -128 to 127
0 to 255
Int Signed Mininum of 16 bits -32,768 to 32,767
Signed int same
(default) same
unsigned same
unsigned int 0 to 65,535
0 to 65,535
Short Signed short Mininum of 16 bits -32,767 to 32,767
Short int same
Signed short int same
Unsigned short same
Unsigned short int 0 to 65,535
0 to 65,535

Long Signed long Mininum of 32 bits -2,147,483,648 to


Long int 2,147,483,647
Signed long int same
Unsigned long same
Unsigned long int same
0 to 4,294,967,295
same
Enum Mininum of 16 bit int -32,768 to 32,767
Float Mininum of 6 decimal
Digit precision -1038 to +10 -38
,0, 1038 to +10 -38

Double long double Minimum of 10 decimal -1038 to +10 -38


Digits precision ,0, 1038 to +10 -38

same
Void Always incomplete No value, no storage
COMPUTER

A Computer is an Electronic Device which takes the given input and gives the required
output. A Computer requires a means of accepting data, somewhere to store the sequence
of operations to require and finally a way of communicating the results. These facilities
are common to any computer regardless of the task.

Compute means to calculate or determine something by mathematical means. The most


commonly used Computer, consists of three parts
• Input Devices (Key-board)
• Central Processing Unit (C.P.U)
• Output Devices (Monitor)
Further a C.P.U is divided into three main parts
1. Arithmetic and Logical Unit (A.L.U)
2. Control Unit (C.U)
3. Memory Unit (M.U)

Memory

Input Output
Device Control Device
C.P.U
Unit

ALU

Figure: Block Diagram of Computer.

Program: Set of instructions given to a computer to get the required output is called a
program. For writing a program we have four steps
1. designing the problem
2. designing an algorithm
3. coding and testing
4. maintenance
Algorithm: Algorithm can be defined as a well-defined computational procedure that
takes single value or a set of values as inputs and produces a single or multiple values as
output. Thus “It is a sequence of steps which transforms an input into an output/ Step
by Step representation of a program is called as “Algorithm”.

A single problem may have multiple algorithms. Also, an algorithm is always a language-
free computational steps. In order to compare algorithms; we must have some criteria to
measure the efficiency of our algorithms. Suppose an algorithm has m input data. The
time and space used by the algorithm are the two main measures for the efficiency of the
algorithm

The Process to Write the Algorithm is given below,


Program to find sum of two numbers
Algorithm:
Step 1: Start
Step 2: Take the input “a,b”
Step 3: Take the operators “+,=”
Step 4: Take the results into “c”
Step 5: Process the problem “c=a+b”
Step 6: Assign the output to “c”
Step 7: Stop

Algorithm to find the roots of quadratic equation for all the cases.

Step 1: Input A, B, C
Step 2: Set D = B * B – 4 * A * C
Step 3: If D > 0 then :
(a)Set X1 = (-B + SQRT(D))/ 2 * A
(b)Set X2 = (-B - SQRT(D))/ 2 * A
(c) Print X1, X2
Else if D = 0 then:
(a)Set X = -B / 2 * A
(b)Print X
Else:
Print “Roots are imaginary”
End If
Step 4: Exit

The fundamental knowledge necessary to solve problems using a computer is the notation
of a Algorithm.
Flow charts: Pictorial/Diagrammatical representation of an algorithm is called Flow
Charts. For easy visual recognition a standard convention is used in drawing flowchart.
In this standard convention
• Parallelogram is used to represent to Input and Output operations.
• Rectangles are used to indicate processing the operation, such as storage and
arithmetic.
• Diamond shaped is used for Decision making (yes/no).
• Oval/rectangle with Rounded ends, are used to indicate beginning (Start) or End
(Stop) points.
• Circle is used to join different parts of a Flowchart; this is called as a connecter.
• Flowlines/Arrows are used to indicate the direction to be followed in a Flowchart.

Parallogra
Start/sto m
p

circl
rectangle e

decisio
n

Flowchart for Sum of two given numbers:


start

Take the variables a,b,c

Read the variables a,b

Compute c=a+b

Print the value of c

stop

The structure of a C program is


Comment lines
Preprocessor directive statements
Global variables
void main ( )
{
Data type declaration with variable;
Statements;
…….
return type;
}

• Each instruction in a C program is written as a separate statement. Therefore a


complete C program would comprise of a series of statements
• Blank spaces may be inserted between two words to improve the readability of
the statement. However, no blank spaces are allowed within a variable, constant,
or keyword.
• All statements are entered in small case letters.
• Every C statement must end with a semi-colon (;). Thus semi-colon acts as a
statement terminator.
• We can include comment lines i.e., either we can use single line or multi line
comments for the user convenient also.
• Pre-processor directive are that which acts as Foundation for the program, there
are number of directives and in that directives we have the Key-word and
statements.
STDIO—Standard Input and Output
In this Directive we have printf, scanf etc.
CONIO—Console Input and Output
In this Directive we have clrscr, getch etc.

• Void means a keyword, and the meaning is it doesn’t return any written
type/value.
• Main() is a collective name given to a set of statements. And this is called as
Function and acts as a starting point of the program. All statements that belong to
main() are enclosed within a pair of braces{ }.
• The printf() statement is a library function that displays information on-screen.
The printf() statement can display a simple text message or a message and the
value of one or more program variables.
• The scanf() statement is another library function. It reads data from the keyboard
and assigns that data to one or more program variables. In other words, it executes
the program statements.
• The return statement is that, it calculates the product of the variables x and y and
returns the result to the program statement that called function. The return
statement returns a value of 0 to the operating system just before the program
ends.
• Input statements: the statements for storing and reading the values
Ex:scanf( )
Output statements: the statements which are used to give required outputs
Ex: printf( )

How to Get into C Compiler:

Assuming that we are using a Turbo C or Turbo C++ compiler, here are the steps that we
need to follow to compile and execute our C program…
1. Start the compiler at C> prompt. The compiler (TC.EXE is usually present in
C:\TC\BIN directory).
2. Select New form the File menu.
3. Type the complete program.
4. Save the program using F2/go the File menu select the Save option, under a
proper name(say add.c).
5. Use the keys ALT+F9 to compile the program (to check if any errors present in
the program).
6. Use the keys CTRL+F9 to run the program(to get the output of the program)
7. Use ALT+F5 also to view the output.

ADDITION.C.
1: /* Program to calculate the Addition of two numbers. */
2: #include <stdio.h>
3: #include <conio.h>
4: void main()
5:{
6: int a,b,c;
7: clrscr();
8: /* Input the first number */
9: printf("Enter a number : ");
10: scanf("%d", &a);
11:
12: /* Input the second number */
13: printf("Enter another number: ");
14: scanf("%d", &b);
15:
16: /* Calculate and display the product */
17: c = a+b;
18: printf ("a=%d b=%d c= %d\n", a, b, c);
19:
20: getch();
21: }

Enter a number: 5
Enter another nunber: 3
a=5 b=3 c= 8

Alphabetic escape sequences representing nongraphic characters in the execution


character set are intended to produce actions on display devices as follows:
Produces an audible or visible alert. The active position shall not be changed.

Execution Meanings
characters
\a (alert) Produces an audible or visible alert. The active position shall not
be changed.
\b (backspace) Moves the active position to the previous position on the current
line. If the active position is at the initial position of a line, the
behavior is unspecified.
\f ( form feed) Moves the active position to the initial position at the start of the
next logical page.
\n (new line) Moves the active position to the initial position of the next line.
\r (carriage return) Moves the active position to the initial position of the current line.

\t (horizontal tab) Moves the active position to the next horizontal tabulation
position on the current line. If the active position is at or past the
last defined horizontal tabulation position, the behavior is
unspecified.
\v (vertical tab) Moves the active position to the initial position of the next
vertical tabulation position. If the active position is at or past the
last defined vertical tabulation position, the behavior is
unspecified.

OPERATORS AND EXPRESSIONS


An operator, in general is a symbol that operates on a certain datatypes.For example, the
operator + is the addition operation. It can operate on integer, character and real (float,
double and long double) numbers.

An expression is a combination of variables, constants and operators written according to


the syntax of the language. In C, every expression evaluates to a value i.e., every
expression results in some value of a creation type that can be assigned to a variable.

For Example: If the variable I and j have been declared by the statement,
int i,j;
then a valid expression involving the assignment operator would be as follows:
int i,j=5;

Types of Operators:

In C, operators can be classified into various categories based on their utility and action.
A list of operator types is given below:
1. Arithmetic operators.
2. Relational operators.
3. Logical operators.
4. Assignment operators.
5. Increment and Decrement operators.
6. Conditional operators.
7. Bitwise operators.
8. Comma operators.
9. Other operators.

Arithmetic Operators:

The Arithmetic Operators perform arithmetic operations and can be classified into Unary
and Binary arithmetic operators. The arithmetic operators can operate on any built in data
type. A list of arithmetic operators and their meaning are given below:

Operators Meaning
+ Addition or unary plus
- Subtraction or unary minus
* Multiplication
/ Division
% Modulo division(remainder after division)

Relational Operators:

While arithmetic operators are used to evaluate arithmetic expressions, relational


operators are used to compare arithmetic, logical and character expressions. We often
compare two similar quantities and depending on their relation, we take some decisions.
These comparisons can be done with the help of relational operators. Each of these
operators compares their left hand side with their right hand side. The whole expression
involving the relational operator then evaluates to an integer. It evaluates to zero if the
condition is false, and one (1) if the condition is true.

Operator Meaning
< Less than
> Greater than
<= Less than or equal to
>= Greater than equal to
== Equal to
!= Not equal to

For Example: if we want to compare to variable, then we use the relational operators.
Eg., if(i= =j)
printf(“hi”);

Logical operators

The Logical Operators is used to compare or evaluate logical and relational expressions.
There are three logical operators in C language. These are the usual And, Or and Not
operators.
Operator Meaning
&& Logical AND
|| Logical OR
! Logical NOT

They are frequently used to combine relational operators,

For Example: x < 20 && x >= 10

In C these logical connectives employ a technique known as lazy evaluation. They


evaluate their left hand operand, and then only evaluate the right hand one if this is
required. Clearly false && anything is always false, true || anything is always true. In
such cases the second test is not evaluated.

Not operates on a single logical value, its effect is to reverse its state. Here is an example
of its use.

if ( ! acceptable )

printf("Not Acceptable !!\n");

Increment/Decrement
The increment operator (++) causes its operand to be increased by one where as the
decrement operator causes its operand to be decreased by one. The operand used with
each of these operators must be a single variable.

E.g. Suppose i is an integer variable that has been assigned a value of 5. The expression +
+i, causes the value of i to be increased by one, whereas the decrement operator causes
the value to be decreased by 1 so, now the new variable of i will be 4

i ++ means i = i + 1
— i means i = i-1

The increment and decrement operators can each be utilized in two different ways,
depending on whether the operator is written before or after the operand. If the operator
precedes the operand (e.g. ++ i) then the operand will be altered in value before it is
utilized for its intended purpose within the program. If however, the operator follows the
operand (e.g i ++) then the value of the operand will be altered after it is utilized

e.g. printf (“ i = %d\n”, i);


printf (“ i = % d\n”, ++i);
printf (“ i = %d\n”, i);

There printf statements will generate following three lines of out put
i=1
i=2
i =2

Now let us take the second case

printf (“ i = %d\n”, i);


printf (“ i = %d\n”, i++);
printf ( i = %d\n”, i );

The statement will generate the following three lines of output


i=1
i=1
i=2

Conditional Operators

Conditional operator is (?:) A expression that makes use of the conditional operator is
called a conditional expression

for e.g. expression 1? expression 2: expression 3


When evaluating a conditional expression, expression 1 is evaluated first. If the
expression 1 is true then expression 2 is evaluated and this becomes the value of
conditional expression However, if expression 1 is false then expression 3 is evaluated
and this becomes the value of the conditional expression
e.g. In the conditional expression shown below suppose f and g are floating point
variables.

The conditional expression is (f < g)? f: g

It takes the value f if f is less than g otherwise the conditional expression takes on the
value of g. In other words conditional expression returns the value of the smaller of the
two variables.

Assignment Operators

The assignment operator is the equal sign (=). Its use in programming is somewhat
different from its use in regular math. If you write

x = y;

in a C program, it doesn’t mean "x is equal to y." Instead, it means "assign the value of y
to x." In a C assignment statement, the right side can be any expression, and the left side
must be a variable name. Thus, the form is as follows:

variable = expression;

When executed, expression is evaluated, and the resulting value is assigned to variable.

Type conversion

You can mix the types of values in your arithmetic expressions. char types will be treated
as int. Otherwise where types of different size are involved, the result will usually be of
the larger size, so a float and a double would produce a double result. Where integer and
real types meet, the result will be a double.

There is usually no trouble in assigning a value to a variable of different type. The value
will be preserved as expected except where;

• The variable is too small to hold the value. In this case it will be corrupted (this is
bad).
• The variable is an integer type and is being assigned a real value. The value is
rounded down. This is often done deliberately by the programmer.

Values passed as function arguments must be of the correct type. The function has no
way of determining the type passed to it, so automatic conversion cannot take place. This
can lead to corrupt results. The solution is to use a method called casting which
temporarily disguises a value as a different type.

eg. The function sqrt finds the square root of a double.


int i = 256;
int root;
root = sqrt( (double) i);

The cast is made by putting the bracketed name of the required type just before the value.
(double) in this example. The result of sqrt( (double) i); is also a double, but this is
automatically converted to an int on assignment to root.

OPERATOR PRECEDENCE AND PARENTHESES


In an expression that contains more than one operator, what is the order in which
operations are performed? The importance of this question is illustrated by the following
assignment statement:

x = 4 + 5 * 3;

Performing the addition first results in the following, and x is assigned the value 27:
x = 9 * 3;

In contrast, if the multiplication is performed first, you have the following, and x is
assigned the value 19:

x = 4 + 15;

Clearly, some rules are needed about the order in which operations are performed. This
order, called operator precedence, is strictly spelled out in C. Each operator has a specific
precedence. When an expression is evaluated, operators with higher precedence are
performed first.
· Unary increment and decrement
· Multiplication, division, and modulus
· Addition and subtraction

If an expression contains more than one operator with the same precedence level, the
operators are performed in left-to-right order as they appear in the expression. For
example, in the following expression, the % and * have the same precedence level, but
the % is the leftmost operator, so it is performed first:

12 % 5 * 2

The expression evaluates to 4 (12 % 5 evaluates to 2; 2 times 2 is 4). Returning to the


previous example, you see that the statement x = 4 + 5 * 3; assigns the value 19 to x
because the multiplication is performed before the addition. What if the order of
precedence doesn’t evaluate your expression as needed? Using the previous example,
what if you wanted to add 4 to 5 and then multiply the sum by 3? C uses parentheses to
modify the evaluation order. A subexpression enclosed in parentheses is evaluated first,
without regard to operator precedence. Thus, you could write

x = (4 + 5) * 3;

The expression 4 + 5 inside parentheses is evaluated first, so the value assigned to x is 27.
You can use multiple and nested parentheses in an expression. When parentheses are
nested, evaluation proceeds from the innermost expression outward.

Look at the following complex expression:


x = 25 - (2 * (10 + (8 / 2)));
The evaluation of this expression proceeds as follows:
1. The innermost expression, 8 / 2, is evaluated first, yielding the value 4:
25 - (2 * (10 + 4))
2. Moving outward, the next expression, 10 + 4, is evaluated, yielding the value 14:
25 - (2 * 14)
3. The last, or outermost, expression, 2 * 14, is evaluated, yielding the value 28:
25 - 28
4. The final expression, 25 - 28, is evaluated, assigning the value -3 to the variable x:
x = -3
You might want to use parentheses in some expressions for the sake of clarity, even when
they aren’t needed for modifying operator precedence. Parentheses must always be in
pairs, or the compiler generates an error message.

As was mentioned in the previous section, if C expressions contain more than one
operator with the same precedence level, they are evaluated left to right. For example, in
the expression

w*x/y*z

w is multiplied by x, the result of the multiplication is then divided by y, and the result of
the division is then multiplied by z. Across precedence levels, however, there is no
guarantee of left-to-right order. Look at this expression:

w*x/y+z/y

Because of precedence, the multiplication and division are performed before the addition.
However, C doesn’t specify whether the subexpression w * x / y is to be evaluated before
or after z / y. It might not be clear to you why this matters. Look at another example:
w * x / ++y + z / y

If the left subexpression is evaluated first, y is incremented when the second expression is
evaluated. If the right expression is evaluated first, y isn’t incremented, and the result is
different. Therefore, you should avoid this sort of indeterminate expression in your
programming. Near the end of this unit, the section "Operator Precedence Revisited"
lists the precedence of all of C’s operators.

The decision control structure in C can be implemented in C using


The if statements
• If-else statement
• Multiple statements
• Nested if statement
• Nested if-else statement

The if Statement
The general form of if statement looks like this:
Syntax: if (this condition is true)
{
execute this statement;
}

Here the keyword if tells the compiler that what follows, is a decision control instruction.
The condition following the keyword if is always enclosed within a pair of parentheses. If
the condition, whatever it is true, then the statement is executed. It the condition is not
true then the statement is not executed instead the program skips past it. The condition in
C is evaluated using C’s relational operators. The relational operators help us to build
expression, which are either true or false. For the if expression there is no semi-colon.

/* FIND WHETHER THE GIVEN NUMBER IS LESS THAN OR EQUAL TO 10 */

main( )
{
int num;
printf(“Enter a number less than 10”);
scanf(“%d”, & num);
if(num < = 10)
{
printf(“The number is less than 10”);
}
}

If – else
Syntax: if (this condition is true)
{
execute this statement;
}
else
{
execute the statements;
}
The if statement by itself will execute a single statement or a group of statements when
the condition following if is true. It does nothing when the condition is false. It the
condition is false then a group of statements can be executed using else statement. The
following program illustrates this

/* CALCULATION OF GROSS SALARY */


main( )
{
float bs, gs, da, hra;
printf(“Enter basic salary”);
scanf(“%f”, & bs);
if(bs <1500)
{ hra = bs * 10/100;
da = bs * 90/100;
}
else
{
hra = 500;
da = bs * 98/100;
}
gs = bs+hra+da;
printf(“gross salary = Rs. %f”, gs);
}

Nested if – else

If we write an entire if - else construct within the body of the if statement or the body of
an else statement. This is called ‘nesting’ of ifs.

Syntax: if(condition)
{
if (condition)
do this;
else
{
do this;
and this;
}
}
else
{
do this;
}

The Loop Control structure


These are three methods by way of which we can repeat a part of a program. They are as
follows,
(a) Using a while statement
(b) Using a do-while statement
(c) Using a for statement

The while Loop


The general from of while is as shown below:
Syntax: initialise loop counter;
while (test loop counter using a condition)
{
statements;
…..;
increment loop counter;
}

The parentheses after the while contains a condition so long as this condition remains true
all statements within the body of the while loop keep getting executed repeatedly

/* CALCULATION OF SIMPLE INTERSET FOR p, n, r */


main( )
{
int p,n, count;
float r, si;
count = 1;

while(count < = 3 )
{
printf(“\n Enter values of p, n and r”);
scanf(“%d %d %f”, & p, & n, & r);
si = p*n*r/100;
printf(“simple interest = Rs. %f”, si);
count = count +1;
}
}

The do-while Loop


The do-while loop takes the following form
Syntax: do
{
statements;
……;
}
while (this condition is true);
There is a minor difference between the working of while and do-while loops. The
difference is the place where the condition is tested. The while tests the condition before
executing any of the statements within the while loop. As against this the do-while tests
the condition after having executed the statements within the loop.

E.g.:
main( )
{
while(5<1)
printf(“Hello \n”);
}

In the above e.q. the printf will not get executed at all since the condition fails at the first
time itself. Now let’s now write the same program using a do-while loop.
main( )
{
do
{
printf (“Hello \n”);
} while (5<1);
}
In the above program the printf( ) would be executed once, since first the body of the
loop is executed and then the condition is tested.

The for Loop


The general form of for statement is as under:
Syntax: for( initialise counter; test counter; increment counter)
{
statements;
……;
}
Now let us write the simple interest problem using the for loop

/* CALCULATION OF SIMPLE INTERST FOR p,n and r */


main( )
{
int p,n, count;
float r, si;
for(count = 1; count <=3; count = count +1)
{
printf(“Enter values of p,n and r”);
scanf(“%d %d %f”, & p, & n, & r);
si = p * n * r / 100;
printf(“Simple interest = Rs %f \n”, si);
}
}
The break Statement
The keyword break allows us to jump out of a loop instantly without waiting to get back
to the conditional test. When the keyword break is encountered inside any C loop, control
automatically passes to the first statement after the loop.

for e.q. The following program is to determine whether a number is prime or not.
Logic:- To test a number is prime or not, divide it successively by all numbers from 2 to
one less than itself. If the remainder of any of the divisions is zero, the number is not a
prime.

following program implements this logic


main( )
{
int num, i;
printf(“Enter a number”);
scanf(“%d”, &num);
i=2
while (i < = num -1)
{
if (num%i= = 0)
{
printf(“Not a prime number”);
break;
}
i++
}
if(i = = num)
printf(“Prime number”);
}

The 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. When the
keyword continue is encountered inside any C loop, control automatically passes to the
beginning of the loop.

e.g.
main( )
{
int i,j;
for(i = 1; i< = 2; i++)
{
for(j=1; j<=2; j++)
{
if (i= =j)
continue;
printf(“\n%d%d\n”, i,j);
}
}
The output of the above program would be....
12
21
when the value of i equal to that of j, the continue statement takes the control to the for
loop (inner) bypassing rest of the statements pending execution in the for loop(inner).

The Case Control structure


switch Statement:-
The switch statement causes a particular group of statements to be chosen from several
available groups. The selection is based upon the current value of an expression that is
included within the switch statement. The form of switch statement is.

Syntax: switch (integer expression)


{
case constant 1:
statements;
break;
case constant 2:
statements;
break;
case constant 3:
statements;
break;
default:
statements;
}

ARRAYS
INTRODUCTION:

An array is a group of related data items that share a common name.


Ex: consider an array name salary which represent a set of salaries of a group of
employees .
salary[10] denotes salary of 10th employee.

Array name subscript(index)

Index : A particular value is indicated by writing a number called Index number of


subscript in brackets after the array name.
While the complete set of values is referred as an array , the individual values are
called elements. Arrays can be of any variable type.

ONE-DIMENSIONAL ARRAYS:

A list of items can be given one variable name using only one subscript and such a
variable is called a single-subscripted variable or a one-dimensional array.
Ex: datatype arrayname[size];
i.e., int number[5];
and the computer reserves five storage locations as shown below:

number[0] number[1] number[2] number[3] number[4]


The values to the array elements can be assigned as follows:

number[0]=35;
number[1]=40;
number[2]=20;
number[3]=57;
number[4]=19;
This would cause the array number to store the values as shown
35 40 20 57 19
number[0] number[1] number[2] number[3] number[4]

The subscript of an array can be integer constants or variables.


Declaration: type variable-name[size];

The type specifies the type of element that will be contained in the array such as float
,int ,char and the size indicates the maximum number of elements that can be stored
inside the array.
Ex: int a[10];
float f[12];
char name[10]; -----this declares name as a character array(string) variable that can
hold a maximum of 10 characters.
Ex:The string ”WELL DONE” is stored as follows

‘W’ ‘E’ ‘L’ ‘L’ ‘‘ ‘D’ ‘O’ ‘N’ ‘E’ ‘\0’


When the compiler sees a character string ,it terminates it with an additional null
character .Thus the element name[9] holds the null character ‘\0’ at the end.When
declaring character arrays we must always allow one extra element space for the null
terminator.

Initializing a character array:

char color[3]=”RED”;
char color[]=”RED”;
The elements of first array are ,
color[0]=’R’ color[1]=’E’ color[2]=’D’
The elements of second array are ,
color[0]=’R’ color[1]=’E’ color[2]=’D’ color[3]=’\0’

Second type of initialization correct.


The array definition could also have been written as
char color[4]=”RED”;

Sorting Techniques:
Selection sort
Bubble sort.
Insertion sort.

Selection sort:
As the name suggests, the first element of the list is selected. It is compared repeatedly
with all the elements. If any element is found to be lesser than the selected element, these
two are swapped. This procedure is repeated till the entire array is sorted. Let us
understand this with a simple example.

Consider the list 74, 39, 35, 32, 97, 84. Following is the table, which gives the status of
the list after each pass is completed.

Pass List after pass


1 32, 39, 35, 74, 97, 84
2 32, 35, 39, 74, 97, 84
3 32, 35, 39, 74, 97, 84
4 32, 35, 39, 74, 97, 84
5 32, 35, 39, 74, 84, 97

Quick sort

This method, invented by Hoare, is considered to be a very faster method to sort the
elements. The method is also called partition exchange sorting. The method is based on
divide-and-conquer technique, i.e., the entire list is divided into various partitions and
sorting is again and again applied on the partitions.

In this method, the list is divided into two based on an element called the pivot element.
Usually, the first element is considered to be the pivot element. Now, move the pivot
element into its correct position in the list. The elements to the left of the pivot are less
than the pivot while the elements to the right of the pivot are greater than the pivot. The
process is reapplied to each of these partitions. This process proceeds till we get the
sorted list of elements. Let us understand this by an example.

Consider the list—74, 39, 35, 32, 97, 84.


(1) We will take 74 as the pivot and move it to position so that the new list becomes – 39,
35, 32, 74, 97, 84. Note that the elements to the left are lesser than 74. Also, these
elements (39, 35 and 32) are yet to be sorted. Similarly, the elements 97 and 84, which
are right to the pivot, are yet to be sorted.

(2) Now take the partitioned list—39, 35, 32. Let us take 39 as the pivot. Moving it to the
correct position gives—35, 32, 39. The partition to the left is 35, 32. There is no right
partition. Reapply the process on the partition, we get 32, 35. Thus, we have 32, 35,39.
(3) Apply the process to the right partition of 74 which is 97, 84. Taking 97 as the pivot
and positioning it, we get 84, 97.
(4) Assembling all the elements from each partition, we get the sorted list.

C program for quick sort


The quick sort is a very good example for recursive programming. Let us assume that an
array named elements[] will hold the array to be sorted and maxsize is the number of
elements to be sorted. We will also assume that the sorting order is ascending in nature.

#include <stdlib.h>
#include <stdio.h>
#define MAXSIZE 500
void quickSort(int elements[], int maxsize);
void sort(int elements[], int left, int right);
int elements[MAXSIZE];
int main()
{
int i, maxsize;
printf(“\nHow many elements you want to sort: “);
scanf(“%d”,&maxsize);
printf(“\nEnter the values one by one: “);
for (i = 0; i < maxsize; i++)
{
printf (“\nEnter element %i :”,i);
scanf(“%d”,&elements[i]);
}
printf(“\nArray before sorting:\n”);
for (i = 0; i < maxsize; i++)
printf(“[%i], “,elements[i]);
printf (“\n”);
quickSort(elements, maxsize);
printf(“\nArray after sorting:\n”);
for (i = 0; i < maxsize; i++)
printf(“[%i], “, elements[i]);
}
void quickSort(int elements[], int maxsize)
{
sort(elements, 0, maxsize - 1);
}
void sort(int elements[], int left, int right)
{
int pivot, l, r;
l = left;
r = right;
pivot = elements[left];
while (left < right)
{
while ((elements[right] >= pivot) && (left < right))
right—;
if (left != right)
{
elements[left] = elements[right];
left++;
}
while ((elements[left] <= pivot) && (left < right))
left++;
if (left != right)
{
elements[right] = elements[left];
right—;
}
}
elements[left] = pivot;
pivot = left;
left = l;
right = r;
if (left < pivot)
sort(elements, left, pivot - 1);
if (right > pivot)
sort(elements, pivot + 1, right);
}

Bubble sort:

The simplest and the oldest sorting technique is the bubble sort. However this is the most
inefficient algorithm. Let us understand this method. The method takes two elements at a
time. It compares these two elements. If the first element is less than the second element,
they are left undisturbed. If the first element is greater than the second element, then they
are swapped. The procedure continues with the next two elements, goes and ends when
all the elements are sorted.
Consider the list 74, 39, 35, 97, 84.
Pass 1: (first element is compared with all other elements)—Note that the first element
may change during the process.
(1) Compare 74 and 39. Since 74 > 39, they are swapped. The array now changes like 39,
74, 35, 97, 84.
(2) Compare 39 and 35. Since 39 > 35, they are swapped. The array now changes like 35,
39, 74, 97, 84.
(3) Compare 35 and 97. Since 35 < 97, they are undisturbed. The array is now 35, 39, 74,
97, 84.
(4) Compare 35 and 84. Since 35 < 84, they are undisturbed. The array is now 35, 39, 74,
97, 84.
At the end of this pass, the first element will be in the correct place. The second pass
begins with the second element and is compared with all other elements. Note that the
number of comparisons will be reduced by one since the first element is not compared
any more.

Pass 2: (second element is compared)


(1) Compare 39 and 74. Since 39 < 74, they are undisturbed. The array is now 35, 39, 74,
97, 84.
(2) Compare 39 and 97. Since 39 < 97, they are undisturbed. The array is now 35, 39, 74,
97, 84.
(3) Compare 39 and 84. Since 39 < 84, they are undisturbed. The array is now 35, 39, 74,
97, 84.
This pass did not bring any change in the array elements. The next pass starts.
Pass 3: (third element is compared)
(1) Compare 74 and 97. Since 74 < 97, they are undisturbed. The array is now 35, 39, 74,
97, 84.
(2) Compare 74 and 84. Since 74 < 84, they are undisturbed. The array is now 35, 39, 74,
97, 84.
This pass also did not bring any change in the array elements. The next pass starts.
Pass 3: (fourth element is compared)
(1) Compare 97 and 84. Since 97 > 84, they are swapped. The array is now 35, 39, 74,
84, 97.
The sorting ends here. Note that the last number is not compared with any more numbers.

At the end of the execution, the array arr[] will be sorted in the ascending order. If you
need to perform a descending order sorting, replace the > symbol with < symbol in the
comparison statement.

Efficiency of bubblesort
Let us now analyze the efficiency of the bubble sort. You can see from the algorithm that
each time (each pass), the number of elements scanned for comparison reduces by 1.

Thus, we have:
Number of comparisons in the first pass = (n – 1)
Number of comparisons in the second pass = (n – 2)
Number of comparisons in the last pass = 1
Thus, the total number of comparisons at the end of the algorithm would have been:
(n – 1) + (n – 2) + … + 2 + 1 = n (n – 1) / 2 = n2 / 2 + O(n) = O(n2)
Hence the order of the bubble sort algorithm is O(n2).

TWO-DIMENSIONAL ARRAY:
A list of items can be given one variable name using two subscripts and such a variable is
called a two-dimensional array.
Ex: datatype arrayname[row_size][column_size];

Two dimensional arrays are stored in memory as shown below:

Column0 column1 column2


Row 0 [0][0] [0][1] [0][2]
310 275 100

Row 1
[1][0] [1][1] [1][2]
200 175 150

Row 2
[2][0] [2][1] [2][2]
30 75 15

Row 3
[3][0] [3][1] [3][2]
250 195 160

As with single dimensional arrays , each dimension of the array is indexed form zero to
its maximum size minus one; the first index selects the row and second index selects the
column within that row.

INITIALIZING TWO-DIMENSIONAL ARRAYS:

int table[2][3]={0,0,0,1,1,1};
The above statement can be equivalently written as
int table[2][3]={{0,0,0},{1,1,1});
or
int table[2][3]={
{0,0,0},
{1,1,1}
};
in all the above statements initializes the elements of the first row to zero and the second
row to one.

When all the elements are to be initialized to zero ,the following short-cut method may be
used.
int m[3][5]={{0},{0},{0}};
Other way of initialization is,
table[0][0]=0;
table[0][1]=0;
table[0][2]=0;
table[1][0]=1;
table[1][1]=1;
table[1][2]=1;

Multidimensional arrays:
Arrays with more than two dimensions also can be defined.these are called Multi
dimensional arrays.
Type arrayname[s1][s2]…[sn];
Ex:
int a[3][3][3]; declares a three dimensional array.
int table[2][2][2][4]; declares four dimensional array.

If a program requires a one-dimensional or multi-dimensional array declaration (because


the array is defined elsewhere in the program) ,the declaration is written in the same
manner as the array definition with the following exceptions.
1. The square brackets may be empty ,since the array size will have been
specified as a part of the array definition .Array declarations are
customarily written in this form.
2. Initial values cannot be included in the declarations.
These rules apply to formal argument declarations within functions as well as
external variable declarations.

String handling functions


For string handling C provides a standard set of library functions. Though there exists
many such functions four of them will be discussed here.

The strcmp( ) Function


This function is used to check whether two strings are same or not. If both the strings are
same it return a 0 or else it returns the numeric difference between the ASCII values of
nonmatching characters.

e.q.
main( )
{
char string1 [ ] = “orange”;
char string2 [ ] = “banana”;
printf(“%d\n”, strcmp(string1, string2));
printf(“%d\n”, strcmp(string2, “banana”);
printf(“%d”, strcmp(string1, “Orange”));
getch( );
}
output
13
0
32
In the first printf statement we use the strcmp( ) function with string1 and string2 as it
arguments. As both are not equal (same) the function strcmp( ) returned 13, which is the
numeric difference between “orange” and “banana” ie, between string2 and b. In the
second printf statement the arguments to strcmp() are string2 and “banana”. As string2
represents “banana”, it will obviously return a 0. In the third printf statement strcmp( )
has its arguments “orange” and “Orange” because string1 represents “Orange”. Again a
non-zero value is returned as “orange” and “Orange” are not equal.

strcpy( ) Function
The function copies one string to another for e.g. the following program

main( )
{
char source [ ] = “orange”;
char target [20];
strcpy(target, source);
clrscr( );
printf(“source: %s\n”, source);
printf(“target:%s”, target);
getch( );
}
output will be
source : orange
target : orange
strcat( )
This function concatenates the source string at the end of the target string for e.g,
“Bombay” and “Nagpur” on concatenation would result in to a string “Bombay Nagpur”.
Here is an example of strcat( ) at work.

main( )
{
char source [ ] = “Folks”;
char target [30] = “Hello”;
strcat(target, source);
printf(“\n source string = %s”, source);
printf(“\n target string = %s”, target);
}
And here is the output
source string = folks
target string = Hello folks

strlen( )
This function counts the number of characters present in a string. Its usage is illustrated in
the following program.
main( )
{
char arr[ ] = “Bamboozled”
int len1, len 2;
len1 = strlen(arr);
len2 = strlen(“Hunpty Dumpty”);
printf(“\n string = %s length = %d”, arr, len1);
printf(“\n string = %s length = %d”, “Humpty Dumpty”, len2);
}
The output would be
string = Bamboozled length=10
string = Humpty Dumpty length = 13
while calculating the length of the string it does not count ‘\0’.

(string.h)
There are two groups of string functions defined in the header <string.h> .The first have
names beginning with str and the second have names beginning with mem except for
memmove function. The behavior is undefined if copying takes place between overlapping
objects.
In the following table
 s& t are of type char *
 cs and ct are of type const char *.
 n is of type size_t
 c is an int converted to char.
char *strcpy(s,ct) __________ copy string ct to string s including ‘\0’ ;return s.
char *strncpy(s,ct,n)_________ copy at most n characters of string ct to s ;return s.
pad with ‘\0’ s if t has fewer than n characters.
char *strcat(s,ct)____________ concatenate string ct to end of string s; return s.
char *strncat(s,ct,n)__________ concatenates at most n characters of string ct to s
terminate s with ‘\0’ ;return s.
int strcmp(cs,ct)_____________ compare string cs to string ct ;return <0 if cs <ct
0 if cs=ct or >0 if cs >ct.
int strncmp(cs,ct,n)__________compare atmost n characters of cs to string ct;return <0 if
cs<ct ,0 if cs=ct or >0 if cs>ct.
char *strchr(cs,c)____________ return pointer to first occurrence of c in cs or NULL if
not present .
char *strrchr(cs,c)___________ return pointer to last occurrence of c in cs or NULL if
not present.
size_t strspn(cs,ct) __________ return length of prefix of cs consisting of characters in ct;
size_t strcspn(cs,ct) __________return length of prefix of cs consisting of characters not
in ct;
char *strpbrk(cs,ct) __________ return pointer to first occurrence in cs of any character
of string ct, or NULL if none are present.
size_t strlen(cs) ___________ return length of string cs.
char *strerror(n)___________ return pointer to implementation defined string
corresponding to error end.
Char *strtok(s,ct) __________ strtok searches s for tokens delimited by characters from
ct;
A sequence of calls strtok(s,ct) splits s into tokens, each delimited by a character from
ct.The first call in a sequence has a non NULL s. It finds the first token in s consisting of
characters not in ct. it terminates that by overwriting the next character of s with ‘\0’ and
returns a pointer to the token, each subsequent call, indicated by a NULL value of s,
returns the next such token, searching from just past the end of the previous one. Strtok
returns NULL when no further token is found. The string ct may be different on each
call.

The mem…. Functions meant for manipulating objects as character arrays, the
intent is an interface to efficient routines. In the following table,
s and t are of type void *
cs and ct are of type const void *.
n is of type size_t.
c is an int converted to an unsigned char.
void *memcpy(s,ct,n) ___________copy n characters from ct to s and return s.
void * memmove(s,ct,n)___________ same as memcpy except that is works even if the
objects overlap.
int memcmp(cs,ct,n)_______________compare the first n characters of cs with ct; return as
with strcmp.
void * memchr(cs,c,n) _____________ return pointer to first occurrence of character c in cs,
or NULL if not present among the first n characters.
void *memset(s,c,n) _______________place character c into first n characters of s; return s.

FUNCTIONS
A Function is a “self-contained block of statements that perform a coherent/specific task
of same kind”. Every C program can be thought of as a collection of these functions. Let
us see the general form of the function which is given below.

Uses of the function:


1. Writing functions avoids rewriting the same code over and over.
2. Using functions it becomes easier to write programs and keep track of what they
are doing.
Syntax:
void main( )
{
statements;
…….;
function name( );
statements;
getch( );
}
function name( )
{
statements;
………….;
}

Some Important Points to remember when doing the Function Concepts:

 Any C program contains atleast one function, and it is nothing but the main( ),and
the execution starts from the main part or we call the starting point of the
program.
 There is no limit on the number of function that might be present in a C program,
it is left for the user to keep how many functions he/she want to keep can keep in
the program.
 After each function has done its executions the controller will return back to the
main( ),and the program ends.
 A function gets called when the function name is followed by a semicolon. And
any function can be called from any other function. Even main( ) can be called
from other function.
For example,
main( )
{
A( ); //Here “A” is a function and end with semicolon here.
}
A( )
{
statements;
…………..;
main( );
}
 Any function can be called any number of times. A function can call itself; such a
process is called “Recursion”.
For example,
main( )
{
A( );
A( );
}
A( )
{
statements;
.…………;
}
 The order in which the function are defined in a program and the order in which
they get called not necessarily are same, but if we give the order the function is
very easy and readable to the user.
For example,
main( )
{
A1( ); //Here A1 & A2 are two functions
A2( );
}
A2( ) //Here A2 will execute the statements after the A1 function
{
statements;
}
A1( ) //Here A1 will execute first because in the main function A1
function is called first and then go to the A2 function.
{
statements;
}
 A function can be called from other function, but a function cannot be defined in
another function.
For example,
main( )
{
statements;
………….;
A( ); //Here A( ) function is defined inside another
function, main( ),so it is wrong function to call.
{
statements( );
}
}
 There are basically two types of functions:
• Library functions Ex. printf( ),scanf( ),etc.
• User-defined functions Ex. A( ),A1( ),A2( ),……

Here name itself is telling that Library functions means it is already defined in the
C programming. And the User-defined functions means which are defined by the
Users/programmers.

A function is a self-contained program segment that carries out some specific, well-
defined task.

A function will carry out its intended action whenever it is accessed (i.e., whenever the
function is “called”) from some other portion of the program. The same function can be
accessed from several different places within a program. Once the function has carried
out its intended action, control will be returned to the point from which the function was
accessed.

Generally a function will process information that is passed to it from the calling portion
of the program and return a single value. Information is passed via special identifiers
called arguments or parameters and return via the return statement. Some functions
however accept information but do not return anything.

The strengths of C language is that C functions are easy to define and use.C functions can
classified into 2 categories namely, library functions and user-defined functions. Main is
an example of user-defined functions. printf ,scanf functions belong to category of library
functions.

The main distinction between these two is library functions are not required to be written
by us. Where as a user-defined function has to be developed by the user at the time of
writing a program. However a user-defined function can later become a part of the C
program library.

A program may become too large and complex and as a result the task of debugging,
testing and maintaining becomes difficult. If a program is divided into functional parts,
then each part may be independently coded and later combined into a single unit. These
subprograms called functions are much easier to understand, debug and test. This sub
sectioning approach clearly results in a number of advantages.

1. It facilitates top-down modular programming as shown


Main program

Function1 Function2 Function3 Function4 Function5


In this programming style, the high level logic of the overall problem is solved first while
the details of each lower level function are addressed later.

2. The length of a source program can be reduced by using functions at appropriate


places.
This factor is particularly critical with micro computers where memory space is limited.

3. It is easy to locate and isolate a faulty function for further investigations.

4. A function may be used by many other programs this means that a C programmer can
build on what others have already done, instead of starting over, from scratch..

Definition:

A function definition has two principal components the first line (including the arguments
declarations), and body of the function.

The first line of a function definition contains the type specification of the value returned
by the function, followed by the function name, and (optionally) a set of arguments,
separated by commas and enclosed in parentheses. Each argument is preceded by its
associated type declaration .An empty pair of parentheses must follow the function name
if the function definition does not include any arguments.

In general terms, the first line can be written as,

data-type name(type1 arg1,type2 arg2,type3 arg3 ……typen argn)

{
//function body;
}

where data-type represents the data type of the item that is returned by the function,
name represents the function name and type1,type2,type3….typen represents the data
types of the arguments arg1,arg2,arg3,…argn .The data types are assumed to be of int
if they are not shown explicitly. However the omission of the data types in this
considered poor programming practice, even if the data types are integers.

Arguments

The arguments are called formal arguments because they represent the names of the data
items that are transferred into the function from the calling portion of the program. They
are also known as formal parameters .The corresponding arguments in the function
reference are called actual arguments since they define the data items that are actually
transferred.

The Form of C Functions:


All functions have the form
function-name(argument list)
Argument declarations;
{
local variable declarations;
executable statement1;
executable statement2;
__________________
__________________
return (expression);
}

Scope of the arguments

The identifiers used as formal arguments are local in the sense that they are not
recognized outside of the function .Hence the names of the formal arguments need not be
the same as the names of the actual arguments in the calling portion of the program. Each
formal argument must of the same datatype; however as the data item it receives from the
calling portion of the program.

Ex: Consider the function which converts a lower case letter to upper case.
char lower_upper(char c)
{
//function body
char c1;
c1=(c>=’a’ && c<=’z’)?(‘A’+c-‘a’):c;
return c1;
}

Any function can call any other function. A function can be called more than once, infact
this is one of the main features of using functions.
The following example illustrates the flow of control in a multifunction program.

main()
{
________________________
________________________
function1();//calling function1
________________________
________________________
function2();//calling function2
________________________
________________________
function1();//calling function1
________________________

}
function1()
{
_______________________
_______________________
}
function2()
{
______________________
______________________
function3();
_______________________
}
function3()
{
_____________________
_____________________
}

Ex: calling a function lower_upper in the main function.


main()
{
char c;
__________
c=lower_upper(‘d’);
_______________
}

Category of functions

A function, depending on whether arguments are present or not and whether a value is
returned or not, may belong to one of the following categories.
Category 1: functions with no arguments and no return values
Category 2: functions with arguments and no return values
Category 3: function with arguments and return values
Category 4: function with no arguments and return values
Category 1:

When a function has no arguments, it does not receive any data from calling function.
Similarly when no return value calling function will not receive any data from called
function. In effect there is no data transfer between calling and called functions.

function1() No input function2()


{ {
-------- No output ------------
-------- ------------
function2(); ------------
} }

Category 2:

When a function has arguments but no return values it receives data from calling function
but calling function does not receive any value from called function.

function1() Values of args function2(f)


{ {
---------- ----------
---------- No return Value ----------
function2(e); ----------
} }

Category 3:

When a function has arguments with return values it receives data from calling function
and calling function receives a value from called function.

function1() Values of arguments function2(f)


{ {
---------- ----------
---------- Function result ----------
function2(e); return a;
} }
Category 4:

When a function has no arguments but return values it does not receive any data from
calling function but calling function receives a value from called function.

function1() No arguments function2()


{ {
---------- ----------
---------- return Value ----------
function2(); return a;
} }

In the above , function1 is calling function and function2 is called function.

Note: The actual and formal arguments should match in number, type and order.
The values of actual arguments are assigned to the formal arguments on a one to one
basis,

Starting with the first argument as shown.

actual arguments
main()
{
-------------
function call function1(a1,a2,a3…,am);
-----------
}
called function function1(f1,f2,f3,….,fm);
{
---------------
--------------
} formal arguments

WHY USE FUNCTIONS


Two reasons:

(i) Writing functions avoids rewriting the same code over and over. Suppose that there is
a section of code in a program that calculates area of a triangle. If, later in the program
we want to calculate the area of a different triangle we won’t like to write the same
instructions all over again. Instead we would prefer to jump to a ‘section of code’ that
calculates area and then jump back to the place from where you left off. This section of
code is nothing but a function.
(ii) Using functions it becomes easier to write programs and keep track of what they are
doing. If the operation of a program can be divided in to separate activities, and each
activity placed in a different function, then each could be written and checked more or
less independently. Separating the code in to modular functions also makes the program
easier to design and understand.

(a) Functions declaration and prototypes


Any function by default returns an int value. If we desire that a function should return a
value other than an int, then it is necessary to explicitly mention so in the calling
functions as well as in the called function.
e.g:
main ( )
{
float a,b,
printf (“\n Enter any number”);
scanf (“\% f”, &a );
b = square (a);
printf (“\n square of % f is % f”, a,b);
}
square (Float x)
{
float y;
y = x * x;
return (y);
}

Enter any number 2.5


square of 2.5 is 6.000000

Here 6 is not a square of 2.5 this happened because any C function, by default, always
returns an integer value. The following program segment illustrates how to make square (
) capable of returning a float value.

main ( )
{
float square ( );
float a, b;
printf (“\n Enter any number “);
scanf (“%f” &a);
b = square (a);
printf (“\n square of % f is % f, “ a, b);
}
float square (float x)
{
float y;
y= x *x;
return ( y);
}

Enter any number 2.5


square of 2.5 is 6.2500000

CALL BY VALUE
In the preceding examples we have seen that whenever we called a function we have
always passed the values of variables to the called function. Such function calls are called
‘calls by value’ by this what it meant is that on calling a function we are passing values of
variables to it.

The example of call by value are shown below ;


sum = calsum (a, b, c);
f = factr (a);

In this method the value of each of the actual arguments in the calling function is copied
into corresponding formal arguments of the called function. With this method the
changes made to the formal arguments in the called function have no effect on the values
of actual argument in the calling function. the following program illustrates this

main ( )
{
int a = 10, b=20;
swapy (a,b);
printf (“\na = % d b = % d”, a,b);
}
swapy (int x, int y)
{
int t;
t = x;
x = y;
y = t;
printf ( “\n x = % d y = % d” , x, y);
}
The output of the above program would be;
x = 20 y = 10
a =10 b =20
CALL BY REFERENCE
In the second method the addresses of actual arguments in the calling function are copied
in to formal arguments of the called function. This means that using these addresses we
would have an access to the actual arguments and hence we would be able to manipulate
them the following program illustrates this.
main ( )
{
int a = 10, b =20,
swapr (&a, &b);
printf (“\n a = %d b= %d”, a, b);
}
swapr (int *x, int * y)
{
int t;
t = *x
*x = *y;
*y = t;
}
The output of the above program would be
a = 20 b =10

Actual and formal arguments

Actual argument—these are the arguments, which are specified in the function call.
For example, consider, a = gcd (x, y). Here x and y are called the actual arguments

Formal arguments—these are the arguments used in the unction declaration. For
example, consider int gcd (int m, int n). Here m and n are called the formal arguments

Global and local variables

Global variable—the variables, which are declared outside all the functions (including
the main) is, called as global variable. They are available to all the functions.

Local variable—the variables, which are declared within a function, are called local
variables. They can be used only within the function in which it is declared.

Automatic and static variables


Automatic variable—they are created when the function block is entered and removed
when the function is terminated. By default, all the variables are automatic variables.

Static variables—they are variables, which are declared local to a function. However
they are available even outside the function in which they are declared.
Recursion

A function can access other functions .In fact it can even access itself. This process of
calling itself is known as recursion.

Ex: The evaluation of factorials of a given number. The factorial of a number n is


expressed as a series of repetitive multiplications
Factorial of n=n(n-1)(n-2)……1.

For example,
Factorial of 4=4*3*2*1=24
A function to evaluate factorial of n is
factorial(n)
int n;
{
int fact;
if(n==1)
return 1;
else
fact=n*factorial(n-1);
return fact;
}

let us see how to work the recursion function:


Assume n=3, Since the value of n is not 1 the statement
fact=n*factorial(n-1);
will be executed with n=3. That is,
fact=3*factorial(2);
will be evaluated. The expression on the right-hand side includes a call to factorial with
n=2. this call will return the following value;
2*factorial(1)
Once again. factorial is called with n=1. This time, the function returns 1. The sequence
of operations can be summarized as follows:
Fact=3*factorial(2)
=3*2*factorial(1)
=3*2*1
=6
Recursive functions can be effectively used to solve problems where the solution is
expressed in terms of successively applying the same solution to subsets of the problem.
When we write recursive functions, we must have an if statement somewhere to force the
function to return without the recursive call being executed. Otherwise, the function will
never return.
Functions with arrays

Like the values of simple variables, it is also possible to pass the values of an array to a
function. To pass an array to a called function, it is sufficient to list the name of the array,
without any subscripts, and the size of the array as arguments.

For example, the call


largest(a,n);

Arguments –Call by Value

In C, all function arguments are passed “by value” .This means that the called function is
given the values of its arguments in temporary variables rather than originals. The called
function cannot directly alter a variable in the calling function. It can only alter its
private, temporary copy.
Ex:
main()
{
int a=10, b=20;
swapv(a,b);
printf(“\n a=%d b=%d”,a,b);

}
swapv(int x,int y)
{
int t;
t=x;
x=y;
y=t;
}

The parameter n is used as a temporary variable, and is count down ( a for loop that runs
backwards) until it becomes zero; there is no longer a need for the variable i. whatever is
done to n inside power has no effect on the argument that power was originally called
with.

In the second method call by reference the addresses of actual arguments in the calling
function are copied into formal arguments of the called function. This means that using
these addresses we would have an access to the arguments and hence we would be able to
manipulate them.
Ex:
main()
{
int a=10, b=20;
swapr(&a,&b);
printf(“\n a=%d b=%d”,a,b);
}
swapr(int *x, int *y)
{
int t;

t=*x;
*x=*y;
*y=t;
}

Note that this program manages to exchange the values of a and b using their addresses
stored in x and y.

Usually in C programming we make a call by value. This means in general you cannot
alter the actual arguments. But if desired, it can always be achieved through a call by
reference.
STORAGE CLASSES

Variables in C can have not only datatype but also storage class that provides information
about their location and visibility. The storage class decides the portion of the program
with in which the variables are recognized.
A variable in C can have any one of the four storage classes:
1. Automatic variables
2. External variables
3. Static variables
4. Register variables

Scope & Lifetime of variables:

The scope of each variable determines over what part(s) of the program a variable is
actually available for use. Longevity refers to the period during which a variables retains
a given value during execution of a program. So, longevity has a direct effect on the
utility of a given variable.

The variables can be categorized into internal or local and external or global. Internal
variables are those which are declared with in a particular function. While external
variables are declared outside of any function.

Ex: int number; it is a global variable


main()
{
……………
}
function1()
{
int n1; it is a local variable to the function1
……………
}

in the above example n1 can not be used in main function. It can be used only in
function1 because it is local variable to that. But, number can be used in both main and
function1 being a global variable.

It is very important to understand the concept of storage classes and their utility in order
to develop efficient multifunction programs.

Automatic variables:

Automatic variables are declared inside a function in which they are to be utilized. They
are created when the function is called and destroyed automatically when the function is
exited. So, they are private (or local) to the function in which they are declared. Hence,
automatic variables are also referred to as local or internal variables.
A variable declared inside a function without storage class specification is, by default, an
automatic variable.

main()
{
auto int number;
…………………
…………………
}
The storage class of the variable number in the above example is automatic.
Storage : Memory
Default value :garbage value.
Scope :Local
Life :Till the control remains within the block in which the
variable is defined.

Register Storage class

Instead of keeping in main memory where normal variables are stored we can tell the
compiler to store a variable in CPU registers. This makes fast access to variables.
This is preferred for frequently accessed a variable which leads to faster execution of
programs.

Ex: register int count;

ANSI standards does not restrict its application to any particular data type, most
compilers Allow only int or char variables to be places in the register. Since there is a
limit on no of variables that can be stored in the register, when the limit is reached C will
automatically convert register variables into non register variables.

External Storage class:


An external variable is global variable. It is declared outside the all functions. Yet is
available to all functions that care to use them.

Ex:
int i;
Main()
{
extern int i;

printf(“\n i=%d”,i)
}
Consider,
Main()
{
---------
---------
---------
y=5;
}
int y;

In the above main can not access y as it has been declared after the main function.
To know the use of external variable let us consider following example.

main()
{
extern int y;//external declaration
---------------
}
function1()
{
extern int y;//external declaration
--------------
}
int y;//definition

In this main and function1 y can be accessed as it has been declared after both the
functions. The external declaration of y inside the functions informs the compiler that y is
an integer type defined somewhere else in the program.
Note:
The extern declaration does not allocate storage space for variables.

Multifile programs

In real-life programming environment we may use more than one source files which may
be compiled separately and linked later to form an executable object code. This approach
is useful because any change in one file does not affect other files thus eliminating the
need for recompilation of the entire program.

Multiple source files can share a variable provided it is declared as an external.


Variables that are shared by two or more files are global variables and therefore we must
declare them accordingly in one file and then explicitly define them with extern in other
files.
file1.c file2.c
main() int m;/* global variable */
{ function2()
extern int m; {
int i; int i;
---------- -------------
----------- -------------
} }
function1() function3()
{ {
int j; int count;
--------- ----------
--------- ----------
} }

The function main in file1 can reference the variable m that is declared as global in file2.
function1 cannot access the variable m. If , however the extern int m; statement is placed
before main, then both the functions could refer to m.This can also achieved by using
extern int m; statement inside each function in file1.

The extern specifier tells the compiler that the following variable types and names have
already been declared elsewhere and no need to create storage space for them. It is the
responsibility of the linker to resolve the reference problem. It is important to note that a
multi-file global variable should be declared without extern in one (and only one) of the
files. The extern declaration is done in places where secondary references are made. If we
declare a variable as global in two different files used by a single program, then the linker
will have a conflict as to which variable to use and, therefore, issues a warning.

When a function is defined in one file and accessed in another, the later file must include
a function declaration. The declaration identifies the function as an external function
whose definition appears elsewhere we usually place such declarations at the beginning
of the file, before all functions. Although all functions are assumed to be external, it
would be a good practice to explicitly declare such functions with the storage class
extern.
Static variables

These variables persist until the end of the program. A variable can be declared static
using the keyword static like.

file1.c file2.c
main() extern int m;
{ function2()
int i; {
----------- int i;
----------- ----------
-----------
} }
function1() function3()
{ {
int j; int count;
---------
---------
} }

static int x;
static float y;

A static variable can be either internal type or external type; depending on the place of
declaration. Internal static variables are those which are declared inside a function. The
scope of internal static variables extends upto the end of the function in which they are
defined. Therefore these are similar to auto variables except that they remain in existence
or alive throughout the remainder of the program. Therefore these are used to retain
values between function calls.

Ex: it can be used count the number of calls made to a function.


POINTERS

Pointer variables can be used in expressions in place of ordinary variables. For this
purpose, we need to prefix the pointer variable with an asterisk. For example, consider
the following.
int i = 100;
int *p = &i;

Now we can use *p wherever we would use i. For example, suppose that we want to
multiply the value of i by 2 to compute the value of another variable j. Then, the
following two expressions are the same.

int j = i * 2;
int j = *p * 2;

Note that we have simply substituted i with *p. Similarly, we can have the following
equivalent if conditions.

if (i > 100)
printf ("Hello");
if (*p > 100)
printf ("Hello");

‘C’ program to illustrate the use of pointers in arithmetic operations.


Pointer variables can be used in arithmetic operations in place of ordinary variables. For
this purpose, we need to prefix the pointer variable with an asterisk. For example,
consider the following:

int i = 100;
int *p = &i;

Now we can use *p wherever we would use i. For example, suppose that we want to find
out if i is an even or odd number. Then the following two arithmetic operations are
equivalent.

int j = i / 2;
if (j == 0)
printf ("Even");
else
printf ("Odd");
int j = *p / 2;
if (j == 0)
printf ("Even");
else
printf ("Odd");
STRUCTURES:

Structures help to organize complex data in a more meaningful manner. It creates a


format, which may be used to declare many other variables in that format. For example,
we want a single collection to hold an integer and a character variable. This is possible
only through a structure. It is declared as below. We will define a structure, which will
define details of a book—title of the book, author of the book, price of the book and the
number of pages it has.

Look at the declaration given as follows:

struct book
{
char title[20];
char author[15];
int pages;
float price;
};
It can be initialized as below:
static struct book mybook = {“Data Structure”, “tenenbaum”, 500, 200.0};

Define the structure to represent a date. Use your structure that accept two different
dates in the format mmdd of the year and do the following: Write a C program to
display the month names of both dates.

struct mydate
{
int yyyy;
int mmdd;
};
main()
{
struct mydate date1, date2;
int month1, month2;
char *months[] = {“”,”Jan”,”Feb”,”Mar”,”Apr”,”May”,”Jun”,”Jul”,
“Aug”,”Sep”,”Oct”,”Nov”,”Dec”};
printf(“\nEnter first date (mmdd) “);
scanf(“%4d”,&date1.mmdd);
printf(“\nEnter second date (mmdd) “);
scanf(“%4d”,&date2.mmdd);
month1 = date1.mmdd / 100; // take month alone
month2 = date2.mmdd / 100; // take month alone
printf(“\nFirst month is %s”,months[month1]);
printf(“\nSecond month is %s”,months[month2]);
}
Structure within structure

A Structure within a structure means nesting of structures. This means one structure is
defined within another structure. The example is given below:

struct employee;
{
char name[20];
int empno;
struct salary
{
int basic;
int DA;
};
};

C program to illustrate the concept of structure within structure.

struct date
{
int day;
int month;
int year;
};
struct employee
{
int empno;
char name[20];
float basic;
struct date joindate;
};
main()
{
struct employee emp1 = {100,”Muthu”,5000.00,10,12,2002};
printf(“\nEno : %d, Name : %s, Basic : %5.2f”,emp1.empno,emp1.name,
emp1.basic);
printf(“\nJoindate %2d.%2d.”,emp1.joindate.day,emp1.joindate.month);
printf(“%4d”,emp1.joindate.year);
}
Array of structures

Consider a simple example. While analyzing the marks obtained by a class of students,
we may use a template to describe student name and marks obtained in various subjects
and then declare all the students as structure variables. In such cases, we may declare an
array of structures, each element of the array representing a structure variable.
struct marks
{
int marks1;
int marks2;
int marks3;
};

main()
{
static struct marks IIIMCA[2] =
{{78, 76, 87}, {67, 87, 76}};
}

C program to calculate student-wise total for three students using an array of


structure.

struct marks
{
int sub1;
int sub2;
int sub3;
int total;
};
main()
{
int i;
static struct marks student[3] = { {56, 45, 65},
{59, 55, 75},
{45, 65, 75}};
static struct marks total;
for (i = 0; i <= 2; i++)
{
student[i].total = student[i].sub1 + student[i].sub2 +
student[i].sub3;
total.sub1 = total.sub1 + student[i].sub1;
total.sub2 = total.sub2 + student[i].sub2;
total.sub3 = total.sub3 + student[i].sub3;
total.total = total.total + student[i].total;
}
printf(“\nSTUDENT TOTAL\n\n”);
for (i = 0; i <= 2; i++)
printf(“\nStudent[%d] %d”, i + 1, student[i].total);
printf(“\nSUBJECT TOTAL\n\n”);
printf(“%s %d\n%s %d\n%s %d\n”,
“Subject 1“, total.sub1,
“Subject 2“, total.sub2,
“Subject 3“, total.sub3);
printf(\nGrand Total = %d”,total.total);
}

C program to illustrate the use of structure pointer.

struct currency
{
int rupees;
int paise;
};
main()
{
struct currency mycurr = {123,25};
showit(&mycurr);
}
showit(struct currency *myptr)
{ printf(“\nRupees %d.%d”,myptr->rupees,myptr->paise);
}
FILES

If we want to store data in a file in the secondary memory, we must specify certain things
about the file, to the operating system. They include:
1. Filename.
2. Data structure.
3. Purpose.

Filename is a string of characters that make up a valid filename for the operating system.
It may contain two parts, a primary name and an optional period with the extension.
Examples:
Input.data
store
PROG.C
Student c
Text.out

Data structure of a file is defined as FILE in the library of standard I/O function
definitions. Therefore, all files should be declared as type FILE before they are used.
FILE is a defined data type. When we open a file, we must specify what we want to do
with the file. For example, we may write data to the file or read the already existing data.

Following is the general format for declaring and opening a file:

FILE *fp;
fp = fopen(“ filename”, “ mode”);
The first statement declares the variable fp as a “pointer to the data type FILE”. As
stated earlier. FILE is a structure that is defined in the I/O library. The second statement
opens the file named filename and assigns an identifier to the FILE type pointer fp. This
pointer which contains all the information about the file is subsequently used as a
communication link between the system and the program. The second statement also
specifies the purpose of opening this file. The mode does this job.
Mode can be one of the following:
r open the file for reading only.
w open the file for writing only.
a open the file for appending (or adding) data to it.
Note that both the filename and mode are specified as strings. They should be enclosed in
double quotation marks.
When trying to open a file, one of the following things may happen:
1. When the mode is ‘writing’ a file with the specified name is created if the file does not
exist. The contents are deleted, if the file already exists.
2. When the purpose is ‘appending’, the file is opened with the current contents safe. A
file
with the specified name is created if the file does not exist.
3. If the purpose is ‘reading’, and if it exists, then the file is opened with the current
contents
safe; otherwise an error occurs.
Consider the following statements:
FILE *p1, *p2;
p1 = fopen(“data”, “r”);
p2 = fopen(“results”, “w”);
The file data is opened for reading and results is opened for writing. In case, the results
file
already exists, its contents are deleted and the file is opened as a new file. If data file
does not
exist, an error will occur.
Many recent compilers include additional modes of operation. They include:

r+ The existing file is opened to the beginning for both reading and writing.
w+ Same as w except both for reading and writing.
a+ Same as a except both for reading and writing.
We can open and use a number of files at a time. This number however depends on the
system we use.
OPERATING SYSTEM

Operating System (O.S) can be defined as system software which acts as the Interface
between user and the system and manages the resources in efficient way. The primary
goal of an operating system is thus to make the computer system convenient to use.
Secondary goal is hardware resource management. They are different O.S, they are,

1. DOS (Disk Operating System): This Operating System for IBM range of
microcomputers was developed by a team of Microsoft’s programmers.Therefore,
the Operating System also called as MS-DOS, this is an Operating System
basically developed for 16 bit microcomputers. It is a collection of programs on a
floppy disk designed to help run the programs, create and manage files and
facilitate the use of peripheral devices such as disks, printers etc.
2. Windows: This Operating System is mainly used for the Graphical User Interface
(GUI).It acts according to the user requirement.
3. Unix
4. Linux, etc

The most important program that runs on a computer is Operating System. Every general
purpose computer must have an Operating System to run other programs. Operating
Systems perform basic tasks, such as recognizing input from the keyboard, sending
output to the display screen, keeping track of files and directories on the disk, and
controlling peripheral devices such as disk drives and printers. The Operating System is
also responsible for security, ensuring that unauthorized users do not access the system.

Operating System can be classified as follows:


• Multi-User: Allows two or more users to run programs at the same time. Some
Operating System permits hundreds or even thousands of concurrent users.
• Multi-Processing: Supports running a program on more than one CPU.
• Multi-Tasking: Allows more than one program to run concurrently.
• Multi-Threading: Allows different parts of a single program to run concurrently.
• Real-Time: Responds to input instantly. General purpose Operating Systems, such
as DOS and UNIX, are not real-time.

Operating Systems provide a software platform on top of which other programs, called
application programs, can run. The application programs must written to run on top of a
particular Operating System.

BUSES

A Bus is a set of Lines(wires) designed to transfer all bits of a word from a specified
source to a specified destination on the same or a different I.C(Integrated Circuit),the
source and destination are typically registers. A Bus can be unidirectional, that is, capable
of transmitting data in one direction only, or it can be bidirectional. If these Buses are
long, the cost of the wires or cables used must also be taken into account. They are
different types of Buses,
1. System Bus: The System Bus is a communication path between the
microprocessor and peripherals. It is nothing but a group of wires to carry bits.

2. Address Bus: The Address Bus consists of 16,20,24,32 parallel signal lines. On
theses lines the CPU sends out the address of the memory location that is to be
written to or read from. The number of memory locations that the CPU can
address is determined by the number of address lines. If the CPU has N address
lines, then it can directly address 2 Power of N memory locations.Simply, we can
say that Address Bus is used to carry the address.

3. Data Bus: The Data Bus consists of 8, 16, or 32 parallel signal lines. The data bus
lines are bidirectional. This means that the CPU can read data in from memory or
from a port on these lines, or it can send data out to memory or to a port on these
lines. Simply we can say that bus is used to carry the data.

MODEM

A Modem is a device or program that enables a computer to transmit data over, for
example, telephone or cable lines. Computer information is stored digitally, whereas
information transmitted over telephone lines is transmitted in the form of Analog waves.
A modem converts between these two forms (Analog to Digital waves and vice-
versa).Fortunately; there is one standard interface for connecting External Modems to
computers called RS-232. Consequently any External Modem can be attached to any
computer that has an RS-232 port, which almost all personal computers have. There are
also Modems that come as Expansion boards that you can insert into a vacant expansion
slot.These are sometimes called onboard or Internal Modems.

While the Modems interfaces are standardized, a number of different protocols for
formatting data to be transmitted over telephone lines exist. Aside from the transmission
protocols that they support, the following characteristics distinguish one modem from
another:
• Bps (bits per seconds).
• Voice/data.
• Auto-answer.
• Data compression.
• Flash memory.
• Fax capability.

BROWSER

A Browser is a computer program that resides in your computer enabling you to use the
computer to view WWW documents and access the Internet taking advantage of text
formatting, hypertext links, images, sounds, motion, and other features.Firefox and
Internet Explorer are currently the leading “graphically browsers” in the world (meaning
they facilitate the viewing of graphics such as images and video and more). There are
other browsers (e.g., Mozilla, Safari and Opera) .Most offers many of the same features
and can be successfully used to retrieve documents and activate many kinds of programs.

The main way in which browsers differ is in the convenience features they offer for
navigating and managing the Web and all the URLs you may want to keep track of.
Netscape and Internet Explorer both offer the ability to e-mail documents, download
them to diskette, print them, and keep track of where you’ve been and site you want to
“bookmark” or “Add to Favorites”.

INTERNET

The Internet is a network of network, linking computers sharing the TCP/IP protocols.
Each runs software to provide or “serve” information and/or to access and view
information. The Internet is the transport vehicle for the information stored in files or
documents on another computer. It can be compared to an International communications
utility servicing computers. It is sometimes compared to a giant International plumbing
system. The Internet itself does not contain information. It is a slight misstatement to say
a” document was found on the Internet”. It would be more correct to say it was found
through or using the Internet.

Computers on the Internet may use one or the entire following Internet Services.,
• Electronic mail (e-mail).
• Telnet or remote login
• FTP or File Transfer Protocols.
• Gopher
• The WWW (World Wide Web or “the Web”).

WORLD WIDE WEB

The World Wide Web or WWW or The Web is the largest, fastest growing activity on
the Internet’s readers, interpreting XML in a way analogous to how browsers interpret
HTML.The WWW incorporates all of the Internet services. You can retrieve documents,
view images, animations and videos, listen to sound files, speck and hear voice, and view
programs that run on practically any software in the world, providing your computer has
the hardware and software to do these things.

When you log onto the Internet using a Web Browser(e.g., Internet Explorer, Fire
Fox,Mozilla,Netscape,Opera,Safari), you are viewing documents in the World Wide
Web. The basic foundation on which the WWW functions is the programming language
called HTML. It is HTML and other programming embedded within HTML that makes
possible Hypertext. Hypertext is the ability to have Web pages containing links, which
are areas in a page or buttons or graphics on which you can click your mouse button to
retrieve another document into your computer. This “click ability” using Hypertext links
is the feature which is unique and revolutionary about the Web.
COMPUTER NETWORKS

In large and wide spread organizations, better efficiency can be achieved by linking its
various computerized departments for that we are using the Computer Networks.” A
Computer Network consists of two or more computers that are linked in order to share
resources exchange files, or allow electronic communication”.

Network is that “a group of computers connected each other is called Network”. With the
Computer Network we have so many uses,
1. The data consisting of text, graphics, sound, motion pictures etc can be
communicated at extremely fast rate through networks.
2. The data becomes available on online. For instance; a user can get the Exam
results and any type of reservations through Internet.
3. The user gets better services such as email, e-commerce, Internet shopping
through the Networks.

Types of Networks

A group of computers connected each other is called as Network. Based on the


requirements the Computer Networks are classified as follows:

• LAN(Local Area Networks)


• WAN(Wide Area Networks)

LAN (Local Area Networks): A LAN is a network of closely located computers connected
by transmission media and adaptors in such a manner that the system allows its users to
communicate and share computing resources. Plug and Play network adaptors are used in
LAN instructions. Such adaptors are generally 16 bit, supporting Full-duplex mode of
transmission of data. The transmission rate is in the tune of 10 to 20 Mbps.The LAN is
generally contained in an office, factory or an organization housed in a building. It is
confined to a small sized geographical area and depends upon transmission media of
moderate to high data rate. The design of a LAN involves the selection of a Topology and
an architecture that guides the interconnection of components.

Network Topology: The term topology means the “structure consisting of paths and devices
that provide” the necessary communication interconnection among the components of the
network.

There are four choices of arranging the components. We can link everything together on
a line; we can join the ends of this line to form a ring; we can radiate all our links out
from a central hub; or we connect all the components on point to point basis.
Respectively, these topologies are;

1. Linear Bus Topology


2. Ring Topology
3. Star Topology
WAN (Wide Area Networks): A wide area network is a computer network that spreads a
region, country or whole of the world.WAN interconnect LAN’s located in any part of
the world. The LAN’s are connected with the help of WAN back bones. Generally
WAN’s use satellites as the primary transmission on media and, therefore, the
transmission is comparatively costly. Where LAN market has grown at the rate of 175%,
the WAN growth has been relatively slow at 40%.The popular, WAN protocols are;

1. X-25 Protocol.
2. Frame Relay.
3. ATM.

Potrebbero piacerti anche