You are on page 1of 8

LESSON 1 FUNCTION

Lesson Objectives:

1. learn the advantages of using Function;


2. differentiate the storage classes; and
3. differentiate the call by value and call by reference.

STORAGE CLASSES

2 different ways to characterized variables:

1. By data type – refers to the type of information represented by a variable.


2. By storage class – refers to the permanence of a variable and its scope within the
program that is the portion of the program over which the variable is recognized.

4 specifications of storage-class in C:

1. Automatic variables or Auto


2. External variables or Extern
3. Static variables
4. Registers

AUTOMATIC VARIABLES

Always declared within a function and are local to the function in which they are declared.
Even if they have the same name, the variables are independent to one another.
Any variable declared within a function is considered as Automatic variables unless a different
storage class specification is included within the declaration.
The keyword AUTO is NOT required during variable declaration.
Does not retain its value once the control is transferred out of its defining function.

EXTERNAL VARIABLES

Variables that are NOT confined to a single functions therefore, they are recognized in the entire
program.
Usually span two or more functions, and often an entire program.
They retain their assigned values within this scope.

STATIC VARIABLES

2 important and distinct uses:

1. To allow local variable to retain its previous value when the block is re-entered.
2. Use in connection with external declarations.

Can be utilized within the function but cannot be accessed outside of their defining function.

REGISTER VARIABLES

Tells the compiler that the associated variables should be stored in high-speed memory
registers, provided it is physically and semantically possible.
Defaults to automatic whenever the compiler cannot allocated an appropriate physical registers.
The use of Storage class registers is an attempt to improve execution speed.
SAMPLE PROGRAM WITH EXTERN AND AUTO:

#include<stdio.h>
#include<conio.h>

int a=3;

int funct1(int count)


{
for(count=1; count<=5; ++count)
{ a=a+count;
printf("%d ", a);
}

return 0;
}

void main()
{
clrscr();
int count;

funct1(count);
OUTPUT:
getche();
} 4 6 9 13 18

SWAPPING

(Page 18) An important technique in solving programming problems where the principle is
assigning the value of variable A to the value of variable B and vice-versa.
3 complex process stage in Swapping:

1. Put the value of variable A into variable Temp.


2. Put the value of variable B into variable A.
3. Put the value of variable Temp into variable b.

SAMPLE PROGRAM FOR SWAPPING

#include<stdio.h> OUTPUT:
#include<conio.h>
Before
void swap(int *x, int *y); a is 3 and b is 5.

void main() After


{ clrscr(); a is 5 and b is 3.
int a=3, b=5;

puts("Before");
printf("a is %d and b is %d.", a, b);

swap(&a, &b);

puts("/nAfter");
printf("a is %d and b is %d.", a, b);

getch();
return;
}
void swap(int *x, int *y)
{ int z;
z=*x;
*x=*y;
*y=z;
}

FUNCTIONS
 An effective way to solve a problem is by decomposition. Decomposition is the way of breaking problems
into small pieces, manageable pieces is critical to writing large programs.
 A function is a section of a program which performs a specific task. The task is assigned to a function is
performed whenever C encounters the function name.
 A function is a subprogram that is a function performs a task within a program and is written in a form
similar to C main program.
 Advantages of using a function:

1. Helps streamline the design of a program and prevents small details from obscuring the
program logic.
2. Functions can often be used more than once in a program and in several different programs,
therefore sharing programming time.
3. Provides natural methods for dividing a programming task among a team of programmers.
4. Can be tested individually making program debugging simpler and organized.

Function Declaration

A function declaration should contain the following: Function name, type of value to be returned if there
is any and the number and types of the arguments that must be supplied during function calling. A function may
contain argument names.

Format: type function_name (parameter list)


Example: void pbdit();
float pbdit (float a, float b);
int pbdit(int x, int y);

Function Definition

Function Definition is the code that describes what a function does. There is a distinct difference
between Function Definition and Function Declaration. A function is defined using a function header and
function body as shown below:

General Form: Type function_name(parameter list)

{ declaration -> Local variables

statements;
}

Function header

 Written exactly the same as the function prototype, except ";"


 Declares the type of return value, name of the function, type of each parameter, and
name of each formal parameter
Function body

 Follows the function header and completes the function definition


 Consists of declarations and executable statements -- similar to the body of the MAIN
part of the program

The type of function starts a function definition. Next is the name of the function followed by an open
parenthesis. Inside the parenthesis is the parameter declaration. After the parameter declarations is the close
parenthesis. A parameter serves as placeholders for values that will be passed when the function is called.
Sometimes, to emphasize their role as placeholders these parameters are called Formal Parameter. Lastly is the
function body which is a block, or compound statements and it too may contain declarations.

Example: int pbdit(int x)


{
return( 3 * x);
}

Local Variables to a Function

Any variable declared inside the function body is called a Local variable or Automatic variable or simply
auto and any variable declared outside the function body is a Global variable.

Remember this:

 Local variables can be referenced only by statements that are inside the block where the
variable is declared.
 Local variable are not known outside their own code.
 Local variables ONLY exist on the block code where they are declared. This means that the
variable is created upon entry and deleted upon exit.

 A global variable are known in the entire program and holds their values during the entire
program execution.
 Global Variables can be accessed by any expression regardless of what function that expression
is in.
 Global Variables are helpful when the same amount of data is used in many functions in your
program.
 Avoid using unnecessary global variables.

Return Statement

The Return Statement terminates the execution of a function and returns control to the calling function.
Execution resumes in the calling function at the point immediately following the call. Return statement may or
may not include an expression.

Syntax: return;
return(expression);

Function Prototypes

A function must be declared before they are used. Function declaration syntax is called Function
Prototype in ANSI C (American National Standards Institute for the C programming language). Function
prototype tells the compiler the number and the type of arguments that are to be passed to the function and
the type of the value that is to be returned by the function.

Syntax: type function_name(parameter type list)

Example: double sqrt (double num); = double sqrt(double);


A Function prototype:

 Describes how the function is called.


 Tells everything you need to know to make a function call.

double sqrt (double num);


result function parameter formal
type name list parameter

 Formal parameter is a place holder to stand for the actual parameter.


 Function prototype terminates with semi-colon.

Naming Parameter/Parameter List

A function header identifies the parameters that will be passed to the function. When the function is
called, the Formal parameter will be replaced by the Actual parameter. Always remember that Formal
parameter is not program variables. You can assign Formal parameter to program variables which will
eventually replace them.

Function Invocation and Call by Value


Aside from the Main Function, a program is made up of one or more function definitions. A program
execution always begin with the main(). When a function is called on the main() function, the program control
goes to the function and performs its task. After the task is done by the function called, the program control
goes back to the main() function and executes the next statements.

Functions are called by writing their names and an appropriate list of arguments within a parenthesis.
Usually, these arguments match in number and type of parameter in the parameter list in the function
definition. The compiler enforces type compatibility when function prototypes are used. All arguments are
passed “call by value” which means that each argument is evaluated and its value is used locally in place of the
corresponding formal parameter.

A function call may come from the main program or within a function. The place where the function is
called is referred to as the calling function or calling environment.

Call by Value and Call by Reference

A function which is invoked using Call by value means that when the function is called a copy of the
value of the actual parameter used in the call is passed across to the memory space of the function. Anything
that happens inside the function to this copy of the value of the parameter cannot affect the original actual
parameter.

A function which is invoked using Call be reference means the address is passed by using symbol
ampersand (&) and the value is accessed by using the asterisk (*) symbol.
LESSON 2 ARRAYS

(page 27)

Lesson Objectives:

1. learn the details of the basic concepts of Arrays;


2. to be familiar with the different uses of Arrays; and
3. to apply the use of arrays in some complicated applications.

ARRAY

To process large amounts of data, we need a powerful data structure such as ARRAY.
Characteristics of Array:

1. Is a fixed size, sequenced collection of elements of the same data type.


2. Is a sequence of data items that are of the same type, indexible, and that are stored
contiguously.
3. Data type that is used to represent a large number of homogeneous values.

We refer to the elements of the arrays as first element, second element and so forth.
We designate the first element as Number0, the second element as Number1 and so on.
Loops are programming constructs that makes array processing easy.

1. Loops can read and write elements in an array.


2. Loops can be used to add, subtract, multiply and divide the elements.
3. Loops can also be used for more complex processing such as calculating averages.

Use the square brackets to index the elements of an array.

USING ARRAY IN C

An Array must be declared and defined before it can be used.


Declaration and Definition tell the compiler the:
1. name of the array;
2. the type of each element; and
3. the size or the number of elements in the array.

The size of the array is a constant and must have a value at compilation time.
Array is defined in the same manner as ordinary variable except each array must be
accompanied by a size specification.
General form of a One dimensional arrays is:

storage class data-type array [expression];

int IT[5]; int IT[5] = { 1, 2, 3, 4};

float CS[7]; float CS[7]= {1, 2, 3, 4,};

double ECE[35];

Storage class is optional.

One dimensional array string data type a character in a string can be accessed either as an
element in an array by making use of a pointer to character.
Strings are handled differently by an Array.

char college[6] = “CCMIT”; should be: char college[ ] = “CCMIT”;

means that:

college[0] = ‘C’;
college[1] = ‘C’;
college[2] = ‘M’;
college[3] = ‘I’;
college[4] = ‘T’;
college[5] = ‘\0’;

ACCESSING ELEMENTS IN ARRAYS

C uses index to access individual elements in an array.


Index must be an integral value or an expression that evaluates to an integral value.
Array’s name is a symbolic reference for the address to the first byte of the array.
When the array name is used, it is actually referring to the first byte of the array.
The index represents an offset from the beginning of the array to the element being referred to.
C calculates the address of an element in the array using the formula:

element address = array address + (sizeof(element) * index)

STORING VALUES IN ARRAY

Declaration and definition only reserve space for the elements in the array. No values will be
stored.
To store values in an array it must:
1. initialized the elements,
 General form is storage class data type arrayname[expression] = {value1,
value2, … value n};
 Done at the time of declaration and definition.
 For each element in the array we provide a value.
 Values must be enclosed in braces and separated by comma if there are more
than one value.
 Initial values must appear on the order in which they will be assigned to the
individual array elements.

2. read values from the keyboard or a file


 Can be done using loop.
 The most appropriate looping statement in an array is the For loop because the
number of elements are fixed and unknown.
 Individual elements can be assigned values using the assignment operator.
 You cannot assign one array to another array even if they match full in type and
in size.

3. assign values to each individual element.


SAMPLE PROGRAM FOR ARRAY

#include<stdio.h>
#include<conio.h>

// Sorts the 3 values of num

void main()
{ clrscr();
int num[3] = {5, 3, 10 };
int h, i, temp;

for(h=0; h<=3;++h)
for(i=0; i<h; ++i)
{ if(num[i] > num[i+1])
{ temp = num[i];
num[i] = num[i+1];
num[i+1] = temp;
}
}

for(i=0; i<3; i++)


printf("%d\n", num[i]);

getch();
}

#include<conio.h>
#include<stdio.h>

#define p printf

void main()
{
int bsit[8];
int count, high;

clrscr();

p("\nEnter your 8 choosen numbers:\n");

for(count=0; count<8; count++)


scanf("%d", &bsit[count]);

{
high=0;
for(count=0; count<8; count++)
{ if(high<bsit[count])
high=bsit[count]; }

p("The highest number is: %d", high);


p("\n");

p("Their difference from the highest are \n\n");

for(count=0; count<8; count++)


{ p("\n %d difference: %d", bsit[count], high-bsit[count]);
}}

getche();
}

You might also like