Httpssoul - Su.edu - Phpluginfile.php1522235mod Resourcecontent3Functions20and20Structured20Programming PDF
Httpssoul - Su.edu - Phpluginfile.php1522235mod Resourcecontent3Functions20and20Structured20Programming PDF
Function
- a group of program statements that performs a specific task:
▪ a function that handles all inputs
▪ a function that displays a menu
▪ a function that computes some values
- mostly used to break up a large program into simpler and manageable parts (modules)
2 types of functions:
a) Standard functions
- predefined or built-in functions of the C system compiler
- we could easily identify them since they are the C statements with an open and close parentheses ( )
- examples are main( ), printf( ), scanf( ), getch( ), etc.
b) Programmer-defined functions
Syntax of a Function:
Each function has a name which is used to refer to that function. Each function name must be unique. A function name
may be any valid identifier. The statements enclosed by curly braces comprise the body of the function.
Function Invocation
A program is made up of one or more functions, one of them is main(). Program execution always begins with main().
To execute a function, a function call is made somewhere in the program. A function call causes the execution of the
statements in the body of a function. To make a function call, simply write down the function name followed by
parentheses ( ) and a semicolon.
Example 1
#include<stdio.h>
void fxn2(void) /* void data type means no value will be returned by function fxn2 */
{
printf(“\nSecond function”);
}
return 0;
}
Output:
Problem #1:
Write a function-oriented program that performs a printing task for a long line above and below the words “OFFICIAL
RECEIPT.” Call or invoke this function from the main program two times.
Example 2
#include<stdio.h>
int num1, num2; /* num1 and num2 are examples of globally declared variables */
sum = num1+num2;
printf(“The sum of %d and %d is %d”, num1, num2, sum);
}
int main(void)
{
input();
compute_sum();
return 0;
}
Write a function-oriented program that computes for the diameter, circumference and area of a circle. The program
must have a separate function to:
Note: Only variables radius and pi must be declared globally. Other variables must be declared locally.
Function Prototype
Example 3
#include<stdio.h>
int main(void)
{
int a=5;
float b=7..67;
char sample =’H’;
void fxn2(void)
{
printf(“\nText inside function fxn2”);
}
void fxn1(void)
{
printf(“\nText inside function fxn1”);
}
Output
The program above shows a function heading written above the main() function or main program. This function
heading tells the C compiler that there are subprograms called fxn1() and fxn2() below the main program.
The given codes were examples of programs with function calls that do not pass any value into the parameter list,
thus, void is explicitly written inside the function’s parentheses. The explicit declaration of void is a good programming
practice since it tells the C compiler in advance that no value is to be passed into the parameter list.
Parameter Passing
Functions can be written to accept values (through parameters) and to return a value. This is useful for computational
tasks. The function computes a value using the parameters and returns the value computed.
To define such a function in C, we need to specify the data types and variable names of the parameters and also the
data type of the value to be returned by the function.
Function Format:
Examples: float fxn1(int x, float y, char a) /* there are 3 parameters accepted by fxn1 */
float fxn2(int b) /* there is a single parameter accepted by fxn2 */
When called/invoked in the calling function, the basic format is: function_name(actual parameter)
Formal Parameter
Actual Parameter
When passing parameters, the number of actual parameters should coincide with the number of formal parameters.
They should also be declared in sequence.
/* This is an example of a program that passes a value to a called function without returning any value
to the calling environment
*/
#include<stdio.h>
int main(void)
{
int x =2;
char y=’b’;
fxn1(x); /* calls function fxn1 and passes the value of x to the first parameter which is m */
fxn2(y, 3);
fxn2(‘k’,x);
return 0;
}
z = ‘k’ w=2
void fxn2(char z, int w) /* function fxn2 consists of 2 formal parameters, namely, z and w */
{
printf(“\n%d %c”,w, z);
}
void fxn1(int m) // m =2
{
printf(“%d “,m);
}
Output
2
3b
2k
2k
Problem 3:
Write a function-oriented program that computes the area of a rectangle. Inputs must be done inside function main()
and must be passed to a function that computes and displays the area.
When a return statement is encountered, execution of the function is passed back to the calling environment as well.
Moreover, this value will be converted, if necessary to the type of the function as specified in the function definition.
Example 5
/* This is an example of a program that passes a value to a called function by returning a value
to the calling function
*/
#include<stdio.h>
int main(void)
{
int age, b;
return (0);
}
int fxn1(int num) /* a function that accepts an integer and returns an integer value to the calling function
*/
{
int x;
#include<stdio.h>
int fxn1(int B)
{
int m = 7;
B = ++m *B;
return B;
}
void fxn2(int x, y)
{
int h = 3;
x+= h + y++;
++h;
printf(“\n%d %d %d”,x, y, h);
return; /* datatype_returned by your function is specified as void since it returns nothing*/
}
int main(void)
{
int x, y = 5;
return 0;
}
Output
Problem 4:
Edit your program in problem 2. This time, do not use global variables. Meaning, all variables must be declared locally
inside a function. Use parameter passing by value. See to it that each function that you create performs a specific task.
Problem 5:
Write a function-oriented program that computes the factorial value of an input n! then display the computed factorial
value on screen. (Example: The factorial value of 5 is 5*4*3*2*1 which is equal to 120).
Problem 6:
Write a function-oriented program that calculates the sum of the squares from 1 to n. Thus, if the input is 4, the output
should be 30 because 12 + 22 + 32 + 42= 30.
Problem 8
Write a function-oriented program that calculates the power value of the input based number and exponent number.
Then display the power value.
Sample input/output:
Problem 9
Write a function-oriented program that will display all odd and even numbers given from n to 1. Use a separate
function to display all even and another separate function to display all odd numbers.
Sample input/output:
Enter a number: 9
Even numbers: 8 6 4 2
Odd numbers: 9 7 5 3 1
Pointers
- variables that store memory addresses (memory locations) of another variable
- when a program is run, each of the variables declared in the program is assigned a unique memory location
which stores the value of that variable
- a function call such as scanf(“%d”, &x) causes an appropriate value to be stored at a particular address in
memory where x is a variable and &x is the address or location in memory of its stored value
Example:
int i, *p; /* declares i to be of type int and p to be of type “pointer” to int */
int *p, a, b;
?
Variable p a b
Value ? ? ?
Address 0000 0001 0002
Figure 1
Explanation: This causes the compiler to allocate space in memory for two integers and a pointer to int. At this point, the contents
of the variables are garbage, because no values have been assigned. Question marks are placed inside the diagram because we
do not know what values are stored in the three variables.
a = b = 7;
p = &a;
Variable p a b
Value 0001 7 7
Address 0000 0001 0002
Figure 2
Explanation: The first statement stores 7 to variables a and b. The second statement stores the address of a (which is 0001) to p.
In this case, p is now said to “point” to a.
The indirection operator (*) is used to access the value of the variable pointed to by a pointer. Consider the statement
printf(“%d”, *p); /* since p points to a, and a has a value 7, the dereferenced value of p is 7 and that is
what gets printed*/
The statements
*p = 3;
printf(“%d”, a);
prints out 3. The object pointed to by p is assigned the value 3. Since p points to a, the stored value of a in memory is
overwritten with the value 3. Thus, when we print out the value of a, 3 gets printed.
Variable p a b
Value 0001 73 7
Address 0000 0001 0002
Figure 3
p = &b;
causes p to point at b
Variable p a b
Value 0002 3 7
Address 0000 0001 0002
Figure 4
*p = 2 * *p – a;
printf(“%d”, b);
Explanation: The first statement is read as: “The object pointed to by p is assigned the value 2 times what p is pointing to minus a.
Note that the expression p on the right side of the assignment is evaluated first. This is because the dereference operator (*)
has higher precedence than the binary arithmetic operators.
In a certain sense, the dereference or indirection operator (*) is the inverse of the address operator (&). Consider the
following code:
float x, y, *p;
p = &x;
y = *p;
First, p is assigned the address of x. Then y is assigned the value of the object pointed to by p. The two statements is
equivalent to:
y = x;
When an expression is passed as an argument to a function, a copy of the value of the expression is made, and it is
this copy that is passed to the function. This mechanism is known as call-by-value. Suppose that x is a variable and
f() is a function. A function call such as f(x) cannot change the value of a variable x in the calling environment because
only a copy of the value of variable x is passed to f( ). In other programming languages, however, such a function call
can change the value of a variable x in the calling environment. The mechanism that accomplishes this is known as
call-by reference. To get the effect of call-by-reference in C, one must use pointers in the parameter list in the
function definition and pass addresses of variables as arguments in the function call.
The following programs demonstrate how the values of the argument variables that are passed as memory address
have been changed or affected by the operation of the function call by reference:
Example 1
#include<stdio.h>
int main(void)
{ int a = 3, b = 7;
tmp = *p;
*p = *q;
*q = temp;
}
#include<stdio.h>
int swap(int *, int *, int); /* function prototype */
int main(void)
{
int x, y, t;
system(“cls”);
x =10;
y = 20;
t = 30;
Output:
x+1=21
y+1=11
t+1=31
Exercises
Functions and Structured Programming
Prepared by: Kim L. Faburada 13
1) Determine the output of the following codes:
int a = 9;
int *ptr = &a; /* assuming & is 3000 */
*ptr = 11;