C Internals
Basics of C Programming
Sunday, 5 June 2016
Saturday, 5 October 2013
Example of a Function in C - How to create a function in C
Some examples of modular programming in C:
Example:
Design a modular program to add two numbers
#include<stdio.h>
/*
prototype */
int add (int x, int y);
int main()
{ int a, b, c;
a = 10; b = 20,;
c = add (a, b); /* function call */
printf(“\n The sum is : %d”, c);
return 0;
}
/*
function to add two integers
Input
: two integer x and y
Output :
sum of x and y
*/
int add (int x, int y)
{ z = x + y;
return (z);
}
NOTE
i.
Prototype means
the behavior of the function, i.e.
o
the return type,
o
the name
and,
o
the number and
type of input parameter
There is no need of
identifiers in the prototype. So, the following is also sufficient
int add (int,
int );
The prototype is also called “declaration” or
“header” .
ii.
The body of a
function that contains actual code for the function is called “definition”.
iii.
The definition of
a function can also be given before main() function. In this case there is no need of prototype.
iv.
The function main
is the “calling function”, and add() is
“called function”.
v.
In the calling
function, there is function call statement. The list inside parentheses is
called “argument list”.
vi.
In the header of
the called function, the list inside the parentheses is called the “parameter
list”.
vii.
The type and
number of arguments must exactly match with those parameter.
viii.
The value of
arguments is assigned to corresponding parameters.
int add ( int x, int y ) /* header of definition */
Effectively, it is an assignment operation: x = a; y = b;
The identifiers a,
b and c are called local identifier s of function main(). The identifiers x, y and z are called local identifier of add()
function. A local identifier can be used
within the function in which it is declared. So a, b and c are accessible
within main() only. Similarly x, y and z are accessible within add() function
only.
ix.
A function can
contain more than one return physically. But, logically only one will be
executed out of them. As soon as a return in the called function encounters,
execution control is transferred to the calling function at the point where a
function call was made.
c = add (a, b);
c = add (a, b);
Effectively, the returned value is assigned to the
lvalue of the assignment statement of the function call. So, the equivalent
effect is:
c = z
x.
The data type of
a following three must exactly match:
· The data type of return expression in called function.
· The return type of the function.
· The data type of variable, in which the returned value is being stored.
· The data type of return expression in called function.
· The return type of the function.
· The data type of variable, in which the returned value is being stored.
xi.
The returned
value can be discarded, if not required.
xii.
If the function
does not return anything, its return type is void. A void function may or may
have not return statement. If there is no return statement, it is implicitly
inserted at the end of function.
xiii.
Guideline:
Normally, a function should not contain input/output statement, because it
looses the generality of function. the input to the function should be supplied
as parameter. The result is normally returned from the function. but this
scheme has limitation, that we can return only single value from the function
multiple returned values can be done with the help of:
·
Structures
·
call by reference
parameter.
Example
/*
program to find factorial of a number */
#include<stdio.h>
long factorial(int); /* prototype */
int main()
{ int n;
long fact;
printf(“\nEnter a number : “);
scanf(“%d”, &n);
fact = factorial(n);
printf(“\n The factorial is : %ld”, fact);
return 0;
}
/*
function to find factorial
Input
: a number n
Output
: factorial of n
*/
long factorial (int num)
{ long fact = 1;
/* loop
to calculate factorial */
for (int I = 2; i<= num; ++i)
fact *= I;
return fact;
}
Formation of Stack:
The operating system
maintains a user stack to keep track of functions called. When a function is
called, a new entry on the top of stack is inserted, this entry contain the
local identifiers of the called function. When the function ends, this entry is
popped (removed). The behavior of function matches with property of STACK. The
function that is called at last will be completed first.
Example: Design a
function that takes and integer as parameter and returns its factorial.
Note: Local variables in two different functions may be of
same name, they are treated as independent variables. For example the variable
”fact” is local variable in the function main() and factorial() both. Both are
entirely different. So, the values will not conflict. It is simply because
separate space is allocated for “fact” of main() and “fact” of factorial().
Disadvantages of Modular Programming in C
Use of function increases the execution time. This
increases is proportionally substantial when the function is very small. During
execution when function is called, there is transfer of control from one area
of memory to other area of memory. It requires a lot of accounting activities;
hence some extra memory and more CPU time is needed.
When the function is sufficiently large, this increase
in time is proportionally less.
Advantages of Modular Programming in C
A large program is divided into small modules. The basic idea
is – “to develop a small set of statements is comparatively simpler”. The C
provides the facilities of functions to support modular programming.
Modularization is a design time activity. To take full
advantage of modularization, modules should be independent of one another. One
module should perform one atomic task. One module should not be given to many
responsibilities.
Advantages of Modular Programming- Following are the advantage of modular programming.
(i) Simplicity
in development – It is easier to
develop a small set of statements as compared to a large one. It is also easier
to concentrate on a small code.
(ii) Faster
development – A big task is divided
into logically separate many small task. The development of these small modular
task can be done simultaneously. In this way, development can be done in less
time.
(iii) Reusability – If a module is developed in such a way that it is
logically independent from other modules, then it can be used again and again.
it saves time and efforts, so software code reduced.
(iv) Abstraction – Abstraction means hiding of details. Hiding of
details. Hiding of detail provides simplicity. Functions once developed can be
called at many places. Each time when it is called, there is no need to
concentrate on its implementation details. It reduces complexity and enhances
clarity. Abstraction provides more opportunity to concentrate on the higher
level logic of a program/task.
(v) Reduced code
size – When a set of statements used
at many places, it is better to design a function for this code and call it at
multiple place. It drastically reduces the code size.
Simplicity in testing and modification – Modular programming gives the opportunity to concentrate on a confined area. It provides easiness in testing. Moreover, modification in a module is simpler as compared to modification in the complete program.
Looping statements in C - for loop - while loop - do while loop
2.1
LOOPING
STATEMENTS
When
one or more statement are to be executed repeatedly either a specified number
of times or until a particular condition is being satisfied, loop is used.
There are three types of loops in C.
·
for
·
while
·
do … while
Ø
Looping is also called repetition or
iteration.
Ø Looping
can also be implemented with the help of goto statement but the goto statement
is avoided in structured programming because it destroys the concept of
“locality of references.” Locality of references increases the efficiency of
memory access.
1.
for – loop:
The for loop consist of two parts.
·
Header
·
body – C statements that are to be executed
repeatedly.
The header contains the three section:
(a)
Initialization
(b)
Condition
(c)
Statement
·
It takes the following form:
·
generally we use the initialization in place
of s1 and increment/decrement in place of s2, c is the test condition.
·
If body have more than one statement then
braces are necessary.
·
The initialization statement s1 is not
executed repeatedly; it is executed only once, just before entering the loop.
·
The statements to be executed repeatedly are
s3 and s2, till the condition c remains true.
·
The statements inside the header is executed
in such a way as if it is the last statement of body of the for loop
·
Any section of the header of for loop can be
left blank. If condition is left blank, it is considered as true for ever. So
it will be an infinite loop, which is the loop that never terminate.
The statement s1 and s2 will be
repeated forever.
·
The for loop must be documented specifying its
purpose.
Error
in Loop – The errors in loops are caused due to
incorrect conditions. There may be three types of logical error in loops:
(a) Infinite looping: it results when
the loop condition never become false.
(b) Boundary case problem: The
condition is such that it repeats the loop either one time more or one time
less than required.
(c) The condition may be such that it
is never true. In this case the loop statements will not be executed even for a
single time.
Nesting
of Loop – The
statements in the body of for loop can be any valid C statement. So it can be
another for loop. It is called nesting of for loop. In case of nesting, one
loop must be completely inside the other loop. The overlapping of two loops is
not possible.
/* start of outer loop */
/* start of inner loop */
…..
/* end of inner loop */
……
/* end of outer loop */
Break statement – Break is used at two places:
● inside switch --- case statement
● inside the loop
As soon as break statement is
encountered, the execution comes out of the structure immediately. If break is
inside the loop, the loop is terminated.
● The break statement inside the loop
is only meaningful when it is provided with if statement.
Continue statement – It is used in loops. As soon as it is executed the statement physically appearing after continue statement are skipped and loop continues. It is meaningful to take continue inside if statement.
2. while – Loop: If
we want to do something a fixed number of times, we use while loop statement
which takes following form:
initialize loop counter;
while (condition)
{
Statements;
}
·
The while is an entry controlled loop
statement.
·
The test – condition is evaluated and if the
condition is true the body of loop is executed. After execution of the body the
test condition in once checked if it is
true the body of while loop is evaluated otherwise execution exit from the
loop. If at the entry time if test condition is false then body of loop would
not executed at all.
·
The body of while loop may have one or more
statements. The braces are needed only if the body contain two or more
statements.
3. The do…while Loop – There is minor difference between
while and do-while.
This difference is the place where the
condition is tested. Do-while is the exit-controlled loop that is why the body
of the loop is always executed at least once whether the test condition is true
of false. It takes the following form:
do
{
do_work();
}
while (condition);
is equivalent to
do_work();
while
(condition)
{
do_work();
}
that (as long as the continue statement is not
used) is technically equivalent to the following (though these examples are not
typical or modern style):
while
(true)
{
do_work();
if (!condition) break;
}
or
LOOPSTART:
do_work();
if (condition)
goto LOOPSTART;
·
The while is an entry controlled loop
statement. The test – condition is evaluated and if the condition is true the
body of loop is executed. After execution of the body the test condition in
once checked if it is true the body of while loop is evaluated otherwise
execution exit from the loop. If at the entry time if test condition is false
then body of loop would not executed at all.
·
The body of while loop may have one or more
statements. The braces are needed only if the body contains two or more statements.
Examples:
int counter = 5;
int factorial = 1;
do {
factorial *= counter--; /* Multiply, then decrement. */
} while (counter > 0);
printf("factorial of 5 is %d\n", factorial);
Try following
example to understand do...while loop. You can put the following code
into a test.c file and then compile it and then run it.
#include
<stdio.h>
main()
{
int i = 10;
do{
printf("Hello %d\n", i );
i = i -1;
}while ( i > 0 );
}
|
This will produce
following output:
Hello 10
Hello 9
Hello 8
Hello 7
Hello 6
Hello 5
Hello 4
Hello 3
Hello 2
Hello 1
|
You can make use
of break to come out of do...while loop at any time.
#include
<stdio.h>
main()
{
int i = 10;
do{
printf("Hello %d\n", i );
i = i -1;
if( i == 6 )
{
break;
}
}while ( i > 0 );
}
|
This will produce
following output:
Hello 10
Hello 9
Hello 8
Hello 7
Hello 6
|
Subscribe to:
Posts (Atom)