Structured Programming
• Structured programming is a problem-solving
strategy and a programming methodology.
Functions and Structured – The construction of a program should embody top-
down design of the overall problem into finite
Programming subtasks.
• Each subtask can be coded directly as a
function.
• These functions can be used in main to
solve the overall problem.
1 2
Functions General syntax:
• Functions are the building blocks of C
and the place where all program activity ret-type function-name (parameter list)
occurs. Function topics include: {
body of the function
return (expression)
– Function types }
– Function variables
– Function arguments • A function may return any type of data except an
– Function scopes array.
– Return values • The parameters receive the values of the
– Function prototypes arguments when the function is called.
– Recursion 3 4
VOID used to indicate: Variables
A. - No Return Value.
B. - No Parameters or Arguments. • A variable is a named location in
memory that is used to hold a value that
* This allows Type compatibility to be can be modified by the program.
handled by the compiler.
• All variables must be declared before
void Fname (void) they can be used.
5 6
1
• Where variables are declared: Local Variable
- Inside functions: void func1(void)
• Declared inside a function.
local variables {
• Can be used only by statements
int x;
- Outside of all functions: that are inside the block in x = 10;
which the variables are declared. }
global variables
• A local variable is created upon void func2(void)
- In the function heading: entry into its block and destroyed {
formal parameters upon exit. int x;
x = -199;
}
7 8
void f(void) #include <stdio.h>
{ int main(void)
int t; {
scanf("%d", &t); int x;
x = 10;
if(t==l) { if(x == 10) {
char s[80]; /* created only upon int x; /* this masks the outer x */
entry into this block */ x = 99;
printf("Inner x: %d\n", x); 99
} }
printf("Outer x: %d\n", x); 10
/* s not known here */ return 0;
} 9 } 10
Global Variables
#include <stdio.h>
void f(void); • They are known throughout the program
int main(void)
Local variables { in which they are defined.
are allocated in the int i;
for(i=0; i<10; i++) f(); A valid call?
Run-time stack. • They are declared outside of any function
return 0;
}
void f(void) • Storage for global variables is in a fixed
{ region (Global Storage Area) and not the
int j = 10;
printf("%d ", j); Prints What? run-time stack.
j++;
} 11 12
2
#include <stdio.h> void func1(void) • Avoid using unnecessary global
{
variables.
int count; /* GLOBAL */ int temp;
temp = count;
void func1(void); func2();
– They take up memory the entire time your
void func2(void); printf("count is %d", count);
} program is executing.
int main(void)
{ void func2(void)
– Using a global variable where a local variable
count = 100; {
int count; /* LOCAL */ will do makes a function less general.
func1();
printf("count is %d", count); for(count=l; count<10; count++)
return 0; putchar('.');
– Using a large number of global variables can
} printf("count is %d", count);
}
lead to program errors.
13 14
Function Parameters
• General form:
The Scope of a Function
fun-name( type varname1, type varname2,…. ) • Each function is a discrete block of code.
• All function parameters must be declared
individually, each including both the type and
• A function's code is private to that
name. function and cannot be accessed by any
void f(int i, int k, int j) /*correct*/ statement in any other function except
void f(int i, k, float j) /* wrong */ through a call to that function.
• Parameters behave like any other local
variable. 15 16
• Variables that are defined within a • The formal parameters to a function also
fall within the function's scope.
Function are local variables. Such
variables are freed from memory when
– A parameter is known throughout the entire
their function completes execution. function.
• Therefore, a local variable cannot hold its – A parameter comes into existence when the
value between function calls. function is called and is destroyed when the
function is exited,( I.e., the Extent of the
variable).
• A global variable has extern storage • A function cannot be defined within a
class. We will see the impact of this later. function (no nested-functions).
17 18
3
Call by Value
Communication with a Function
* When an Argument (variable, constant, or
expression) is passed to a matching parameter
• Two ways that arguments can be passed to (declared in Function Heading), A Copy of the
a function. Argument Value is made and is passed to the
parameter.
Arguments Parameters
– Call by Value. in calling in called
Module. Module.
* Changes made to the parameter have no effect
– Call by Reference. on the argument. i.e., the parameter is
implemented as a local variable which is
19
initialized to the value passed from the 20
Argument.
Call by Reference #include <stdio.h>
int sqr(int x);
• It is often convenient to have functions modify
the values of the variables referred to in the int main(void)
Argument list. {
int t=10;
• The address of an argument is copied into the printf("%d %d", sqr(t) , t);
parameter. return 0;
• Inside the subroutine, the address is used to } What is output?
access the actual argument used in the call.
int sqr(int t)
To effect call-by-reference we must use pointers in {
the Argument list & pass addresses of variables t = t*t;
[see chap 8]. 21 return t; 22
Placement of Functions: #include <stdio.h>
Before the compiler sees a call to a function
it wants to know the Number and Type of void f(int a, int b)
its Parameters and the type of the Return {
Value of the Function. printf(''%d ", a%b); Before Main
}
Two methods of doing so:
int main (void)
1. Place Function Before main function
{
f(10,3);
2. Provide Function Prototype Before the call.
return 0;
23 } 24
4
Function Prototypes
Func Prototype is “Heading” of function.
A Function call can appear Before the
function is Defined (i.e., code of function): FP’s - Can be placed at the top of the File -
typically above any Function Definitions
* The called function can be defined later in But below :
the same file.
#includes
* The called function can be in another file.
#defines
IF the Function Prototype is provided Before This gives the FP’s File Visibility. Know
the call. 25 throughout the file. 26
Parameter Passing /* This function returns the average of 3 exam
Call by Value scores which are passed call-by-value. */
#include <stdio.h>
double average(int, int, int); double average(int exam1, int exam2, int exam3)
{ double testavg;
int main(void) {
int test1, test2, test3;
testavg = (exam1 + exam2 + exam3)/ 3;
double avg;
return testavg;
scanf(“%d%d%d”, &test1, &test2, &test3);
}
avg = average(test1, test2, test3);
printf(“ The average is: %f”’, avg);
}
27 28
Arguments to main( ) #include <stdio.h>
• Information is passed into the main( ) #include <stdlib.h>
function via command line arguments.
int main( int argc, char *argv[] )
• Two special built-in arguments, argc and { a.out John
argv, are used to receive command line Input
arguments. if(argc<2) {
– The argc parameter holds the number of printf(''You forgot to type your name.\n");
arguments on the command line and is an exit(1);
integer. } Hello John
printf("Hello %s", argv[1] );
– The argv parameter is a pointer to an array
of character pointers. return 0;
29 30
}
5
Returning from a Function return expression;
• A function terminates execution and returns to
the caller in two ways.
• It causes an immediate exit from the
1. Occurs when the last statement in the function.
function has executed. – Returns program control to calling
environment.
– Allows Returning of a value.
OR
• The value of expression will become the
2. Occurs when execute the return statement.
return value of the function.
31 32
Return Rules • The } that ends a function also causes the
• You can use as many return statements as function to return. It is the same as a
you like within a function. However, the return without any specified value. If this
function will stop executing as soon as it occurs within a non-void function, then the
encounters the first return. return value of the function is undefined.
/* Return 1 if c is part of string s; 0 otherwise. */
int is_in(char *s, char c) • A function declared as void cannot
{ contain a return statement that specifies
while (*s)
if(*s==c) return 1; a value.
else s++;
return 0;
33 34
{
The exit( ) Function
• A NON-VOID function can be used as an
operand in an expression.
• General form
void exit(int return_code);
• This function causes immediate termination of
x = power(y); the entire program, forcing a return to the
operating system.
if(max(x,y) > 100) printf(''greater");
• The value of return_code is returned to the
for(ch=getchar(); isdigit(ch); ) . . . ;
calling process, which is usually the operating
35
system. 36
6
•Programmers frequently use exit when a
mandatory condition for program Recursion
execution is not satisfied.
• A function calls itself (circular definition).
#include <stdlib.h>
/* non-recursive */ /* recursive */
int fact(int n) { int factr(int n) {
int main(void) int t, answer; int answer;
{
if(!virtual_graphics()) exit(1); answer = 1; if(n==l) return 1;
play(); for(t=1; t<=n; t++) /* recursive call */
... answer=answer*t; answer = factr(n-l)*n;
} return answer; return answer ;
37 } } 38