You are on page 1of 52

Designing Structured Programs in C

Structured Programming
• It makes use of the control structures :
– sequence, selection and repetition
• Structured programming does not use GO TO
commands.
• Structured Design
– program should be designed from the top-down or
bottom-up as a hierarchical series of modules.
• A logical way of partitioning or subdividing a program
so that each module performs one or a small number of
related tasks.
Top-Down Design
• The process of breaking the overall procedure into
modules and then subdivide each component module
until the lowest level of detail has been reached.
• The payroll system of a company can contain the
following modules or tasks:
– Master file
– Earnings
– Deductions
– Taxing
– Net earning
– Print reports
Stepwise Refinement
• Top-down design strategy.
• The program is developed by successively refining
levels of procedural detail.
• This successive refinement of specifications terminates
when all instructions are expressed in terms of any
underlying computer or programming language.
• Every refinement step implies some design decisions.
It is important that the programmer is aware of the
underlying criteria.
Type Conversions in C
Type Conversion

• When variables and constants of different types are


combined in an expression then they are converted
to same data type.
• The process of converting one predefined type
into another is called type conversion.
• Implicit Type Conversion
• Explicit Type Conversion
• When the type conversion is performed automatically by the compiler without
programmers intervention, such type of conversion is known as implicit type
conversion or type promotion.
• If either of the operand is of type long double, then others will be converted to
long double and result will be long double.
• Else, if either of the operand is double, then others are converted to double.
• Else, if either of the operand is float, then others are converted to float.
• Else, if either of the operand is unsigned long int, then others will be
converted to unsigned long int.
• Else, if one of the operand is long int, and the other is unsigned int, then
– if a long int can represent all values of an unsigned int, the unsigned int is
converted to long int.
– otherwise, both operands are converted to unsigned long int.
• Else, if either operand is long int then other will be converted to long int.
• Else, if either operand is unsigned int then others will be converted to
unsigned int.
• The type conversion performed by the programmer by
posing the data type of the expression of specific type is
known as explicit type conversion.
• The explicit type conversion is also known as type
casting.
• Type casting in c is done in the following form:
(data_type)expression;
• where, data_type is any valid c data type, and expression
may be constant, variable or expression.
For example,
x=(int)a+b*d;
• The following rules have to be followed while
converting the expression from one type to another to
avoid the loss of information:
• All integer types to be converted to float.
• All float types to be converted to double.
• All character types to be converted to integer.
Functions in C
SUB-PROGRAMS

• In top down design, the problem is broken down into


sub-problems.
• Solutions to the sub-problems are provided by
subprograms, known as procedures, functions, or
subroutine depending on the programming language.
• A subprogram performs or executes the computer
instructions required to solve a given subproblem.
• A Sub Program is a part of a program that performs
one or more related tasks, has its own name, is
written as a separate part of the program, and is
accessed via a call statement.
• Disadvantage -- Procedure calls consume execution
time and memory.
• Advantage -- Procedures make the program easier to
write, test, debug and maintain.
Introduction

• C language supports two types of functions: -


– Library Functions: pre-defined set of functions .
– User Defined Functions/Subprograms: functions defined by
the user according to his/her requirement.
– These are the programs, which have the global as well as local
declaration statement, executable statement and function calling
statement like main program.
Function

• “A self-contained block or a sub-program of one


or more statements that performs a special task
when called”.
or
• “A set of independent statements, which can be
utilized, whenever it required”.
Types of Function

Function

Library Function User-Defined Function


or or
Standard in-built Function Self-Contained Program
or or
Compiler Function Call-by-value &
Call-by-reference Function
(sqrt(), pow(), tan() etc.) (add(), raj(), factorial() etc.)
Why Use Functions?

• If we want to perform a task repetitively then it is


not necessary to rewrite the particular block of the
program again & again.
• The function defined can be used for any number of
times to perform the task.
• Using functions large programs can be reduced to
smaller ones. It is easy to debug & find out the
errors in it.
How Function Works?

• Once a function is defined & called, it takes some


data from the calling function & returns a value to
the called function.
• Whenever a func. is called, control passes to the
called func. & working of the calling func. is
stopped.
• When the execution of the called func. is
completed, control returns back to the calling func.
& executes the next statement.
Cont’d

• The values of actual argu. passed by the calling


func. are received by the formal argu. of the called
function.
• If formal argu. > actual argu. -> Garbage value
• The func. operates on formal argu. & sends back the
result to the calling func. The return () statement
performs this task.
Declaration of Function
int abc ( int i, int j, int k ); //Function Declaration
main()
{
---------
---------
abc (x, y, z); //Function Call
Actual Argument
---------
---------
}
abc (i, j, k) //Function Definition
{ Formal Argument
---------
Example
int add (int a, int b); //Function Declaration
main()
{
int x = 1, y = 2, z;
z = add (x, y); //Function Call
printf (“z = %d”, z);
getch();
}
add (a, b) //Function Definition
{
Function Prototype/Declaration
• A prototype statement helps the compiler to check the
return type & argument type of the function.
• A function prototype declaration consists of the
function’s return type, name & arguments list.
• When the programmer defines the function, the
definition of the function must be same like its
prototype declaration.
– A) float sum (float, int);
– B) float sum (float x, int y);
Function Prototype

– A) float sum (float, int); // the prototype of function sum


() is declared. Its return value is float & arguments are
float & integer type resp.
– B) float sum (float x, int y); // with argument type,
argument names are also declared. It is optional & also
not compulsory to use the same variable name in the
program.
Scope/Rules of Functions
• Function makes the lengthy & complex programs
easy & in short forms.
• The length of source program can be reduced.
• Memory space can be properly utilized.
• It can be used by many programs.
• It increases the execution speed of the program &
makes the programming simple.
• Portability of the program is very easy.
• It removes the redundancy.
• Debugging becomes very easier & fast.
Scope/Rules of Functions
• They are more flexible than library functions.
• Testing (V & V) is very easy.
• Reliability is high in the function programming.
• Function has the modular approach.
• Function always works efficiently.
• User can build a customized library of different
function used in daily routine having specific goal &
link with the main program similar to the library
functions.
Style (Creating functions)
• A function without parameter and no return value
• A function with parameter and no return value
• A function with parameter and return value
• A function without parameter and return value
A function with no parameter and no return value
void main()
{
clrscr();
void print(); /*func declaration
print(); /*func calling
Printf(“no parameter and no return value”);
print();
getch();
}
void print() /*func defination
{ int i;
for(i=1;i<=30;i++)
{ printf(“*”);
}
printf (“\n”);
}
A function with no parameter and no return value

• There is no data transfer between calling and called


function
• The function is only executed and nothing is
obtained
• Such functions may be used to print some
messages, draw stars etc
A function with parameter and no return value
void main()
{
int a=10,b=20;
void mul(int, int);
mul(a,b); /*actual arguments
getch();
}
void mul(int x, int y) /*formal arguments
{
int s;
s=x*y;
printf(“mul is %d” ,s);
}
A function with parameter and return
value
#include<conio.h>
void main()
{
int a=10,b=20,c;
int max(int,int);
c=max(a,b);
printf(“greatest no is %d”,c);
getch();
}
int max(int x, int y)
{
if(x>y)
return(x);
else
A function without parameter and return value

#include<conio.h>
void main()
{
int a=10,b=20;
int sum();
int c=sum(); /*actual arguments
printf(“sum is %d”,c);
getch();
}
int sum() /*formal arguments
{
int x=10,y=30;
return(x+y); /*return value
}
Argument passing techniques

• Call By Value
• Call By Reference
Call By Value
• It is a default mechanism for argument passing.
• When an argument is passed by value then the copy of
argument is made know as formal arguments which is
stored at separate memory location
• Any changes made in the formal argument are not
reflected back to actual argument, rather they remain
local to the block which are lost once the control is
returned back to calling program
Example

void main()
{
int a=10,b=20;
void swap(int,int);
printf(“before function calling %d %d”,a,b);
swap(a,b);
printf(“ after function calling %d %d”,a,b);
getch();
}
void swap(int x, int y)
{
int z;
z=x;
x=y;
y=z;
printf(“value is %d, %d”, x,y);
}
Output:
before function calling a=10 b=20
value of x=20 and y= 10
after function calling a=10 b=20
Call By Reference

• In this instead of passing value, address are passed.


• Here formal arguments are pointers to the actual
arguments
• Hence change made in the argument are
permanent.
Example

Void main()
{
int a=10 ,b=25;
void swap(int *,int *);
printf(“before function calling %d %d”,a,b);
swap(&a,&b);
printf(“after function calling %d %d”,a,b); getch();
}
void swap(int *x,int *y)
{
int z;
z=*x;
*x=*y;
*y=z;
Printf(“value is %d %d”,*x,*y);
}
Output:

before function calling a= 10 b= 25


value of x=25 and y=10
after function calling a=25 b= 10
Basic Library Functions (math.h)
• Mathematics is relatively straightforward library to use again.
• You must #include <math.h> and must remember to link in the
math library at compilation:
– cc mathprog.c -o mathprog -lm
• A common source of error is in forgetting to include the
<math.h> file (and yes experienced programmers make this
error also). Unfortunately the C compiler does not help much.
Consider:
• double x; x = sqrt(63.9); Having not seen the prototype for sqrt
the compiler (by default) assumes that the function returns an
int and converts the value to a double with meaningless results.
Recursion

42
Recursion
• Recursion is a technique that solves a problem by
solving a smaller problem of the same type.
• A recursive function is a function invoking itself, either
directly or indirectly.
• Recursion can be used as an alternative to iteration.
• Recursion is an important and powerful tool in problem
solving And programming.
• Recursion is a programming technique that naturally
implementthe divide-and-conquer problem solving
methodology.
43
The Nature of Recursion
1. One or more simple cases of the problem (called the
stopping cases or base case) have a simple non-recursive
solution.
2. The other cases of the problem can be reduced (using
recursion) to problems that are closer to stopping cases.
3. Eventually the problem can be reduced to stopping cases
only, which are relatively easy to solve.
In general:
if (stopping case)
solve it
else
44
reduce the problem using recursion
Four Criteria of A Recursive Solution
1. A recursive function calls itself.
– This action is what makes the solution recursive.

2. Each recursive call solves an identical, but smaller, problem.


– A recursive function solves a problem by solving another problem that is identical in
nature but smaller in size.

3. A test for the base case enables the recursive calls to stop.
– There must be a case of the problem (known as base case or stopping case) that is
handled differently from the other cases (without recursively calling itself.)
– In the base case, the recursive calls stop and the problem is solved directly.

4. Eventually, one of the smaller problems must be the base case.


– The manner in which the size of the problem diminishes ensures that the base case
is eventually is reached. 45
Efficiency of Recursion

• The other reason that recursive programs may turn out to


be inefficient is the simple fact that, when we use recursion
to solve problems we are interested exclusively with
correctness, and not at all with efficiency.
• Consequently, our simple, elegant recursive algorithms
may be inherently inefficient.
• Therefore, it is essential, after we have solved the
problem, to critically examine our solution and attempt to
improve on it; both by removing sources of inefficiency
and by refining its elegance.
Recursion

• Process where a function is called itself but stack


frame will be out of limit because function call will be
infinite times.
– So a termination condition is mandatory to a recursion.
– In C/C++, Recursion can be divided into two types:
(a) Run- Time Recursion: Normal as in C
(b) Compile- Time Recursion: By using Template
• Each of these can be also divided into following
types:

1. Linear Recursion
2. Binary Recursion
3. Tail Recursion
4. Mutual Recursion
5. Nested Recursion
MCQs
1. What error would the following function give on compilation ?
f(int a, int b)
{
int a;
a = 20;
return a;
}
1. Missing parentheses in return statement
2. Function should be defined as int f(int a, int b)
3. Re-declaration of ‘a’
4. No error

2. It is necessary to declare the type of a function in the calling program if the


function
1. Returns an integer
2. Returns a non-integer value
3. Is not defined in the same file
4. None of these
MCQs

1. Which one of the passing parameters technique?

1. Call by value
2. Call by function
3. Both of these
4. None of these

2. Which is the function depends upon math.h library function?


1. mod()
2. floor()
3. sqrt()
4. All of above
Thank You!!!

You might also like