Arrays, Functions (Mamun Sir 22)
Arrays, Functions (Mamun Sir 22)
Arrays
Arrays are indexed variables that contain many data items
(variables) of the same type. They are used to declare many
variables with a single declaration. This saves coding time
and space.
Further, once declared, the compiler reserves the required
amount of memory addresses for the variables in contiguous
regions of the memory. This makes the access to all the
variables easy if any single address is known.
In C, one can have an array of anything: characters,
integers, floats, doubles, arrays, pointers, structures, and so
on.
In essence, an array is not a new variable type, rather this is
a method of declaring a number of variables of the same
type in groups.
2
Arrays
The syntax for array declaration is:
array_type array_name [array_size]
Examples are:
Arrays
An array has four basic properties:
The individual data items (variables) in the array are called
elements
All elements (variables) must be of the same data type
All elements are stored contiguously in the computer’s memory,
and the subscript (or index) of the first element is always zero
(that means the last element in the array has index of [array_size-1] )
The array_name is a pointer that holds the address of the first
element in the array
(All the subsequent elements can be accessed by using the
pointer arithmetic)
4
Arrays
Example:
int st_id[5]; // creates 5 elements (variables) st_id[0],
// st_id[1], st_id[2], st_id[3] and st_id[4]
st_id
// creates a pointer with the arrayname
100
// the pointer points to the first element (variable)
[040]
0 0 0 0 0
[100] [102] [104] [106] [108]
Arrays
So the value of the first element can be accessed as:
st_id[0] or as *st_id
The subsequent elements can be accessed as:
array_name[index] or as *(array_name + index)
where, index = [element_number – 1].
In the previous example, the last element (5th element) can be
accessed as:
st_id[4] or as *(st_id+4)
In case of pointer notation, the index is automatically multiplied
by the sizeof(pointer_type) to access a specific element in the
memory. For example, in case of integer type pointer, the index
is multiplied by 2 (byte), character type pointer, the index is
multiplied by 1 (byte) and float type pointer, the index is
multiplied by 4 (byte) to access the element.
6
Arrays
There are three methods for initializing arrays:
By default when they are created – only applies to global
and static automatic arrays
Only constant data can be used to initialize an array thus
created
Explicitly when they are created by supplying constant
initializing data
During program execution by assigning or copying data
into the array
The arrays will always be initialized (default) to binary
zero if no other initialization data is supplied
The following program shows such arrays:
7
Arrays
#include <stdio.h>
#define ARRAY_ONE_SIZE 5
#define ARRAY_TWO_SIZE 5
int array_one [ARRAY_ONE_SIZE]; // Global array
main ()
{
static int array_two [ARRAY_TWO_SIZE];
printf (“array_one [0]: %d\n”, array_one [0]);
printf (“array_two [0]: %d\n”, array_two [0]);
return (0);
}
Unlike programs in other languages, the first subscript for
all arrays in C is zero
8
Arrays
The arrays can be initialized and ANSI C standard lets
supply initialization values for any array, global or
otherwise, defined anywhere in a program
The following code segment illustrates this –
int numbers [3] = {1, 2, 3};
static float cost [5] = {5.45, 6.78, 3.88, 9.12, 0.0};
static int more_numbers [3] = {1, 2, 3, 4, 5, 6, 7};
char vowels [] = {‘a’, ‘e’, ‘i’, ‘o’, ‘u’};
The first statement declares the numbers array to be 3
integers and provides the initial values of the elements
In the second example, initialization happens when the
entire program loads
9
Arrays
In the third example, there are 7 values for a 3-element
array
This will result in an error message indicating too many
initializers; in contrast, if there are more spaces than the
initializers, the values go into the beginning of the array
and the extra elements become zeroes
If the count is empty, as in the fourth example, the number
of values determines the size of the array
That is, the program dimensions the array automatically
with unsized arrays
Whenever C encounters an array initialization statement
and the array size is not specified, the compiler
automatically creates an array large enough to hold all of
the specified data
10
Arrays
It is possible to have arrays within arrays – that is,
multidimensional arrays such as shown below:
int multi_array [2] [3];
Arrays
Multidimensional arrays can be initialized in the same way
as one-dimensional array, for example:
float a [2] [3] = {3.1, 1.2, 0.5, 9.3, 2.4, 5.3};
Note that rightmost dimension always increases the fastest
a
100
[078] a[0][0] a[0][1] a[0][2] a[1][0] a[1][1] a[1][2]
3.1 1.2 0.5 9.3 2.4 5.3
[100] [104] [108] [112] [116] [120]
The usual terminology for the two indices is that the first
gives the row number in the grid and that the second gives
the column number in the grid
If we declare an array as: int a[4][5];
then we can think of the array elements arranged as:
12
Arrays
col 1 col 2 col 3 col 4 col 5
Arrays
If we declare an array as: int a[5][4];
col 1 col 2 col 3 col 4
row 1 a[0][0] a[0][1] a[0][2] a[0][3]
row 2 a[1][0] a[1][1] a[1][2] a[1][3]
row 3 a[2][0] a[2][1] a[2][2] a[2][3]
row 4 a[3][0] A[3][1] A[3][2] a[3][3]
row 5 A[4][0] A[4][1] A[4][2] A[4][3]
a
Actual Memory Mapping for declaration: int a[5][4];
100
[065] a[0][0] a[0][1] a[0][2] a[0][3] a[1][0] a[1][1] a[1][2] a[1][3] A[2][0] a[2][1]
0 0 0 0 0 0 0 0 0 0
[100] [102] [104] [106] [108] [110] [112] [114] [116] [118]
a[2][2] a[2][3] a[3][0] A[3][1] A[3][2] a[3][3] A[4][0] A[4][1] a[4][2] A[4][3]
0 0 0 0 0 0 0 0 0 0
[120] [122] [124] [126] [128] [130] [132] [134] [136] [138]
14
Arrays
Unsized array initializations are not restricted to one-
dimensional arrays
For multidimensional arrays, one must specify all but
the leftmost dimension for C to index the array properly
With this approach, one can build tables of varying length
and the compiler will automatically allocate enough storage
For example:
int array1 [ ] [2] [3] [5]; // valid declaration
int array2 [ ] [ ] [3] [5]; // invalid declaration
15
Arrays
To access a particular element (variable) of an array, one
must specify an index = [element_number – 1], for example,
if an array is declared as: int books_in_stock[10]; then
books_in_stock [2] indicates the third variable of the array
During the declaration of an array, the square brackets
must contain a valid integer constant (or constant variable
defined by a macro)
On the other hand, when accessing a specific array
element in anywhere in the program, the index inside the
square bracket may be an integer constant, variable or
expression.
However, The Integer expressions/variables can be used
within the square brackets to access an element only if
they evaluate to a valid integer index
16
Functions
In C, statements are grouped into units called ‘functions’. In some
programming languages, functions are also called ‘methods’,
‘procedures’, ‘sub-routines’, ‘sub-functions’, ‘subs’ and so on.
‘scanf( )’
Functions
Every C program must have at least one user-defined function
called ‘main( )’
One C program must not contain more than one function called
‘main( )’
Functions
The C code that describes what a function does is called
the function definition i.e., a complete function.
The function definition or a complete function consists
of two parts: function prototype declaration and function body
Syntax of a function definition:
return_type function_name (type1 arg1, type2 arg2, …...)
{
declarations……..
statements………
return variable/expression/constant;
}
19
Functions
Here the first line describing return_type, function_name and
(type1 arg1, type2 arg2, ......) constitute the function prototype
which is used in the declaration of the function.
Note that a function prototype_only declaration does not require the list of
variables. Only number and type of arguments are sufficient. But when
writing the function, the list of variables are mandatory, if variable type
existed in the argument list in the prototype declaration (i.e., not void).
The arguments supplied to a ‘called’ function from the ‘calling’ one may
be constant values, variables or expressions.
23
Functions
Upon calling, all the (auto/local) variables of the called function are
created in memory.
Upon return or exit, all the variables created for the ‘called’ function are
destroyed, i.e., the data in those variables are lost.
26
Functions
This way, during the execution (runtime) of a program, every time a function is
called from another function, the variables for that ‘called’ function are created.
Then the values from the ‘calling’ function are copied to its arguments
(variables). After completion of execution, when the ‘called’ function exits
(returns to the ‘calling’ function), all its variables are lost, i.e., the data inside
those variables can no longer be used in the next call.
A function can be called multiple times from other functions during a program
execution.
A function can also call other functions multiple times during a program
execution.
For example, if func1, func2, and func3 constitute a program, func1 can call
both func2 and func3. On the other hand, both func2 and func3 can call func1.
27
Functions
This way, during the execution (runtime) of a program, every time a function is
called from another function, the variables for that ‘called’ function are created.
Then the values from the ‘calling’ function are copied to its arguments
(variables). After completion of execution, when the ‘called’ function exits
(returns to the ‘calling’ function), all its variables are lost, i.e., the data inside
those variables can no longer be used in the next call.
A function can be called multiple times from other functions during a program
execution.
A function can also call other functions multiple times during a program
execution.
For example, if func1, func2, and func3 constitute a program, func1 can call
both func2 and func3. On the other hand, both func2 and func3 can call func1.
28
Functions
Function example:
void line (void)
{
.........
}
Here line is the name of the function, the first void means that
’line()’ does not return anything, and the second void means
that it takes no arguments
Functions
The following program demonstrates the use of functions
#include <stdio.h>
void print (void); //function prototype
int main ( )
{
print( );
return 0;
}
Functions
Let’s consider another example:
#include <stdio.h>
int subtractor (int, int); // Function prototype
int main ()
{
int a = 5, b = 93, c;
c = subtractor (a, b);
printf (“The difference is: %d\n”, c);
return 0;
}
32
Functions
int subtractor (int x, int y) // Function declaration
{
int z;
z = x – y;
return z; // Function return type
}
The prototype states that the function will accept two integer
arguments and return an integer type
33
Functions
A function can also call itself using a calling statement inside its
body. This is known as recursion . Although calling ‘main( )’
function recursively is also possible, it is highly discouraged since
in most situations, this leads to peculiar program behavior.
The factorial of a number can be generated with recursion, for example:
#include <stdio.h>
double factorial (double);
int main( )
{
double number = 20.0, fact;
fact = factorial (number);
printf (“The factorial is: %15.0lf \n”, fact);
return 0;
}
34
Functions
double factorial (double answer)
{
if (answer <= 1.0)
return (1.0);
else
return (answer * factorial (answer – 1.0));
}
Recursive functions are useful in making clearer and simpler
implementations of algorithms. However, recursive functions run
slower than their iterative equivalents due to the overhead of
repeated function calls since each call to a recursive function
makes a new copy of the arguments and local variables.
35
Functions
The following program has a simple function named printer
that receives no arguments and does not return a value
The main function calls the function printer – control is
returned to the main function when printer has completed
its task
#include <stdio.h>
#include <math.h>
void printer (void);
int main( )
{
printf (“This program extract a square root.\n\n”);
printer( );
return 0;
}
36
Functions
void printer(void)
{
double z = 5678.0, x;
x = sqrt (z);
printf (“The square root of %lf is %lf \n”, z, x);
}
37
Functions
#include <stdio.h>
const float PI = 3.14159;
void radius (int r);
int main ( )
{
int myradius;
printf (“Enter the radius, as an integer, \n”);
printf (“from the keyboard. \n”);
scanf (“%d”, &myradius);
radius (myradius);
return 0;
}
38
Functions
void radius (int r)
{
float area, volume, sarea;
area = PI * (float) (r * r);
volume = PI * 4.0/3.0 * (float) (r * r *r);
sarea = PI * 4.0 * (float) (r * r);
printf (“The radius is %d \n\n”, r);
printf (“The circle has an area of %f \n”, area);
printf (“The sphere has a volume of %f \n”, volume);
printf (“The surface area of the sphere %f \n”, sarea);
}
39
Functions
Floats are as easy to transfer as arguments as are integers
– the following program is an example:
#include <stdio.h>
#include <math.h>
void hypotenuse (float, float);
int main ( )
{
float ylength, xlength;
printf (“Enter the height of a right triangle. \n”);
scanf (“%f”, &ylength);
printf (“Enter the base of a right triangle. \n”);
scanf (“%f”, &xlength);
40
Functions
hypotenuse (ylength, xlength);
return (0);
}
void hypotenuse (float x, float y)
{
double myhyp;
myhyp = hypot ((double) x, (double) y);
printf (“The hypotenuse of the triangle is “);
printf (“%g \n”, myhyp);
}
The hypot function has been used from math.h
41
Functions
It should be noted that all math.h functions accept and
return double types – the double type is a very precise
float value
The following program raises a number to a power
#include <stdio.h>
#include <math.h>
void power (double x, double y);
main ()
{
double xnum, ynum;
printf (“Enter the number to be raised to a power.\n”);
42
Functions
scanf (“lf”, &xnum);
printf (“Enter the power. \n”);
scanf (“lf”, &ynum);
power (xnum, ynum);
return 0;
}
void power (double x, double y)
{
double result;
result = pow (x, y);
printf (“The result is %lf \n”, result);
}
43
Functions
The functions so far discussed have not returned any
values to the calling function and thus were of type void
The following example is of a function that returns a
character value to the calling program using a function
named toupper (prototyped in ctype.h) – other functions
in ctype.h are tolower and toascii
#include <stdio.h>
#include <ctype.h>
char uppercase (char letter);
int main ()
{
44
Functions
char lowchar, hichar;
printf (“Enter a lowercase character. \n”);
lowchar = getchar ();
hichar = uppercase (lowchar);
printf (“%c\n”, hichar);
return 0;
}
char uppercase (char letter)
{
return (toupper (letter));
}
45
Functions
Similar to the previous example, a function can return other
types of values as shown in the following examples
// Function type integer
#include <stdio.h>
int cubenumber (int);
int main ()
{
int i, cube;
for (i = 0; i < 20; i +=2) {
cube = cubenumber (i);
printf (“The cube of %d is %d \n”, i, cube);
46
Functions
}
return 0;
}
int cubenumber (int number)
{
return (number * number * number);
}
Function type long
// Accepts an int value and returns a long
#include <stdio.h>
long twopower (int);
int main ()
47
Functions
{
int i;
long weight;
for (i = 0; i < 31; i++)
{
weight = twopower (i);
printf (“2 raised to the &d power is &ld\n”, i, weight);
}
return 0;
}
long twopower (int number)
{
48
Functions
int t;
long value = 1;
for (t = 0; t < number; t++)
value *= 2;
return (value);
}
Functions
float answer;
printf (“Enter radius of a sphere: “);
answer = area (sarea);
printf (“Area of the sphere is: %.2f”, answer);
}
float area (float sarea)
{
float radius;
scanf (“%f”, &radius);
sarea = 4.0 * 3.14159 * radius * radius;
return (sarea);
}
50
Functions
Return type double
#include <stdio.h>
#include <math.h>
const double PI = 3.14159265359;
double trigsine (double);
int main ()
{
int i;
double sine;
for (i = 0; i < 91; i++)
{
sine = trigsine ((double) i);
51
Functions
printf (“Sine of %d degrees is %20.18lf \n”, i, sine);
}
return 0;
}
double trigsine (double angle)
{
double temp;
temp = sin ((PI/180.0) * angle);
return (temp);
}
52
Functions
In order to create a function with an array as an argument, the argument
can be declared either (i) as a pointer or (ii) as an array in its prototype
declaration. If the function is to step through the array elements with an
index, the declaration must be an array with square brackets [ ], the size
can be empty.
Functions
int main( )
{
int a = 10, b = 20;
printf("\n\n\tThe value of a = %d and b = %d before swap.\n\n", a, b);
swap(&a, &b); /* function call by reference, which passes as x = &a, y = &b */
printf("\n\n\tThe value of a = %d and b = %d after swap.\n\n", a, b);
return 0;
}
58
Functions
/*USING A SINGLE FUNCTION TO SORT AN ARRAY*/
#include <stdio.h>
#include <windows.h>
#define SIZE 5 // changing the digits changes the
//number of array elements
int main()
{
float gpa[SIZE], temp;
int i=0,j=0,k=0;
int n;
printf("\tEnter %d numbers by pressing enter after each number:\n", SIZE);
for(i=0;i<SIZE;i++)
{
scanf("%f", &gpa[i]); //number input
printf("\tnumber%d = %f\n",i+1, gpa[i]); //echo input
}
Functions 59
k++;
if(k<SIZE)goto compare; // goto statement followed by a label with semi-colon
int main() {
float gpa[SIZE];
print_input(gpa);
print_msg( );
sort_input(gpa);
print_output(gpa); return 0;}
62
Functions
void print_input(float *gpi) //gpi = &gpa[0]; so, (n+1)th element, gpa[n] == *(gpi+n)
{
int i, j;
printf("\tEnter %d numbers by pressing enter after each number:\n", SIZE);
for(i=0;i<SIZE;i++)
{
scanf("%f", (gpi+i)); //number input using pointer notation for array
printf("\tnumber%d = %f\n",i+1,*(gpi+i)); //echo input
}
printf("\n\tThe numbers entered are as follows:\n");
for(j=0;j<SIZE;j++)
{
printf("\n\t%f", *(gpi+j)); //confirms input data using pointer notation for array
}
}
63
Functions
void print_msg(void) {
int n;
printf("\n\n\tPlease Wait....");
for (n=5;n>=0;n--){
Sleep(1000); //delay introduced by ‘Sleep(miliseconds)’ from <windows.h>
printf("\b%d", n);}
printf("\b%c",' ');
}
void sort_input(float *gps) { //gps = &gpa[0]; so, (n+1)th element, gpa[n] == *(gps+n)
int i, k=0;
while(k<SIZE){ //‘k’ is a fixed position compared with the next ‘i’ positions
for(i=k+1; i<SIZE; i++){ // sorting data using pointer notation for array
if (*(gps+k) < *(gps+i))swap((gps+k), (gps+i));
}
k++;
}
}
64
Functions
void swap (float *x, float *y){ // a function with pointers for swapping values
float temp;
temp = *x;
*x = *y;
*y = temp;
}
void print_output(float *gpo){ //gpo = &gpa[0]; so, (n+1)th element, gpa[n] == *(gpo+n)
int j;
printf("\n\n\tThe numbers arranged from highest to lowest are as
follows:\n");
for(j=0;j<SIZE;j++)
{
printf("\n\t%f", *(gpo+j)); //prints sorted data using pointer notation for array
}
printf("\n\n\tThank you for using this program...\n\n\n\n");
}