0% found this document useful (0 votes)
3 views64 pages

Arrays, Functions (Mamun Sir 22)

Arrays in C are indexed variables that store multiple data items of the same type, allowing for efficient memory usage and access. They must be declared with a specific syntax, and all elements must be of the same type, with memory allocated contiguously. Additionally, arrays can be multidimensional and initialized in various ways, with specific rules governing their declaration and access.

Uploaded by

tasfiatasnim1084
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views64 pages

Arrays, Functions (Mamun Sir 22)

Arrays in C are indexed variables that store multiple data items of the same type, allowing for efficient memory usage and access. They must be declared with a specific syntax, and all elements must be of the same type, with memory allocated contiguously. Additionally, arrays can be multidimensional and initialized in various ways, with specific rules governing their declaration and access.

Uploaded by

tasfiatasnim1084
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 64

1

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:

 int array2 [12]; // An array of 12 integers (12 integer variables)


 char array1 [10]; // An array of 10 characters
 An integer constant must be used inside the square
bracket during array declaration. A variable name/expression
cannot be used inside the square brackets to declare the
arraysize.
 However constant (variable) name can be used inside the
square brackets but only through Macro definition like shown
below:
#define ARRAY_SIZE 10 // Macro declaration
int array_name[ARRAY_SIZE]; // Array declaration
 All elements (variables) must be of the same type, i.e.,
arrays using mixed data (variable) types are NOT possible
3

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]

st_id[0] st_id[1] st_id[2] st_id[3] st_id[4]

0 0 0 0 0
[100] [102] [104] [106] [108]

 st_id = &st_id[0]; //Not necessary (automatically done)


5

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];

 Multidimensional arrays are declared by increasing the


pair of square brackets following the array name.
 If there is only one set of brackets, the array is one
dimensional, two sets of brackets indicate a two-
dimensional array, and so on.
 Multidimensional arrays are stored in a linear fashion in the
computer’s memory – elements are grouped from
rightmost index inward
11

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

row 1 a[0][0] a[0][1] a[0][2] a[0][3] a[0][4]

row 2 a[1][0] a[1][1] a[1][2] a[1][3] a[1][4]

row 3 a[2][0] a[2][1] a[2][2] a[2][3] a[2][4]

row 4 a[3][0] A[3][1] A[3][2] a[3][3] a[3][4]

a Actual Memory Mapping for declaration: int a[4][5];


100
[065] a[0][0] a[0][1] a[0][2] a[0][3] a[0][4] a[1][0] a[1][1] a[1][2] a[1][3] a[1][4]
0 0 0 0 0 0 0 0 0 0
[100] [102] [104] [106] [108] [110] [112] [114] [116] [118]
a[2][0] a[2][1] a[2][2] a[2][3] a[2][4] a[3][0] A[3][1] A[3][2] a[3][3] a[3][4]
0 0 0 0 0 0 0 0 0 0
[120] [122] [124] [126] [128] [130] [132] [134] [136] [138]
13

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.

 A function is a collection of statements that executes sequentially.

 All executions in C programming are done inside functions.

 The program takes a modular appearance when functions are used.

 Functions are of two types:

(i) Built-in standard C library functions such as ‘printf( )’ and

‘scanf( )’

(ii) User-defined functions such as ‘main( )’


17

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( )’

 The name of a user-defined function can be anything from a


single letter to a long word. Similar rules as that for identifiers
must be followed.

 Every C program starts execution at the first statement inside the


function ‘main( )’ and ends execution at the last statement inside
the function ‘main( )’
18

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.

 All the declarations and statements contained within {……….}


block is called function body.

 Note that a function must be written containing both prototype


declaration part and its entire body part in the program for its
execution.

 Only function body part cannot be used anywhere in the program.


20
Functions
 However, the prototype declaration part can be used at the global
declaration section at the beginning of a program as for function
declaration as follows:

return_type function_name(list of types of arguments)

int add(int, int); //function prototype declaration

float sort(int*, float*) //function prototype declaration

 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).

 Functions without arguments are possible (arguments are optional).


21
Functions
 In ANSI C, void must be used to state explicitly the absence of
function arguments, e.g. void print(void); This fact, however, is
ignored by the modern compilers.

 Function arguments can be mixed – that is, of any of the standard


data types, i.e., int, float, char, long, double, etc.

 If user-defined functions are placed following the ‘main( )’ function,


then function prototype declarations must be done at the
global/prototype declaration section of the program preceding the
‘main( )’ function.

 However, if all the user-defined functions are placed before the


‘main( )’ function, then prototype declarations are not required.
22
Functions
 A function can call another function (built-in library function or user-
defined one) within a C program.

 A function can be called from other functions as well.

 A function should not call the function ‘main( )’.

 If a function is called from another function, the latter is called the


‘calling’ function and the former ‘called’ function.

 A function is called by using its ‘function_name’ in the calling function


followed by the correct number and correct type of arguments within a
pair of parenthesis.

 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.

 Then the values of the constants, variables or expressions of the


calling function are copied to the variables of the ‘called’ functions
sequentially. This method of function call is termed as “Function
call by value”.

 In such case of “Function call by value”, the variables of the calling


function have no relationship with the variables of the called
function. They are totally different since they have separate
addresses in memory even if they have similar names.
24
Functions
 A function does not recognize any of the auto/local variables of
other functions.

 When a function is called from anther function at some point (statement)


inside its body, the CPU stops execution of the subsequent statements
of the current ‘calling’ function and starts execution of the first statement
of the ‘called’ function. It continues execution until the last statement of
the ‘called’ function unless a ‘return’ or ‘exit(0)’ is used to terminate it.

 Upon completion of execution, a ‘called’ function should return a value


(and control) to the ‘calling’ function exactly at the same point
(statement) of the calling program (except ‘void’ type function which has
no return value). The CPU then continues execution of the subsequent
statements of the calling function following the ‘function-call’ statement.
25
Functions
 When a function returns a value, the value needs to be assigned to some
variable in the ‘calling’ function – if there is no assignment specified, then
the return value is simply discarded.

 A function usually terminates when the last statement in the function is


executed and, conceptually, the function’s ending ‘}’ is encountered. A
function also exits whenever it encounters a ‘return’ or ‘exit(0)’ statement
within its function body.

 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

 Since this user-defined function has no arguments, it can be


called simply by using its name, including the parentheses
following the name, i.e., line( );
29

Functions
The following program demonstrates the use of functions
#include <stdio.h>
void print (void); //function prototype
int main ( )
{
print( );
return 0;
}

void print (void)


{
long j;
for (j=0; j<1000000; j++); //delay loop
printf(“\n\n\t\t Hello World! \n\n");
}
30
Functions
 The variable j used in ’print( )’ function is known only to ’print( )’ .
it is not accessible from ’main( )’ function. This type of variable
defined in a function and unknown outside that function is called a
local variable. J is created when ’print( )’ is called from ’main( )’
and destroyed when ’print( )’ function exits and return controls to
the calling function ’main( )’.

 A variable used in this way in a function is known in C as an


automatic variable, because it is automatically created when a
function is called and destroyed when the function returns – the
length of time the variable lasts is called its scope or lifetime.
31

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 function is called subtractor

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);
}

Function type float


#include <stdio.h>
float area (float);
void main (void)
{
49

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.

int func_array ( int array [ ] ); // prototype

int func_array ( int *array_pointer ); // prototype

 When a function has an array type of argument, then it is called from


the ‘calling’ function by using its function_name followed by simply the
array_name (without the square bracket [ ]) as its argument within the
parenthesis, e. g. func_array(array_name); //function call
53

Functions

 Since an array_name is actually a pointer to its first element, the


address of the array’s first element is actually passed to the
‘called’ function instead of the values of the array elements. This
method of calling a function is called “function call by reference” .

 Therefore, instead of copying the values of the array elements


from the calling function to the called function, the entire actual
array is passed to the ‘called’ function. The ‘called’ function thus
perform operations on the actual array elements of the ‘calling’
function.
54
Functions
 By default, arrays are always passed by reference.

 ‘Function call by reference’ can also be done with other variables.

 In order to do this, a function has to be declared with pointer arguments in


its prototype declaration.
int func_ptr ( int *ptr1, int *ptr2 ); // prototype

 This function then can be called by passing the addresses of the


variables as arguments during function calls.

func_ptr ( &x, &y); // function call by reference

//ptr1 = &x; ptr2 = &y;

 In this method of calling by reference, ‘called’ function can perform direct


data operations on the actual variables of the ‘calling’ function.
55
Functions

/*USING FUNCTIONS AND ARRAY TO FIND BIGGEST NUMBER*/


#include <stdio.h>
#define SIZE 5
int find_biggest (int array [ ], int size); //prototype
int main ( ) {
int numbers [SIZE] = {2, 5, 1, 9, 7};
int i, is_big;
printf (“Here is the initial set of numbers  “);
for (i = 0; i < SIZE; i++)
printf (“%d “, numbers [i]);
is_big = find_biggest (numbers, SIZE); //function call
printf (“\nThe biggest number is %d: \n”, is_big);
return 0;
}
56
Functions
int find_biggest (int array [ ], int size)
{
int k, so_far_biggest = 0;
for (k = 0; k < size; k++)
if (array [k] > so_far_biggest)
so_far_biggest = array [k];
return 0;
}
Functions 57

/*USING FUNCTION CALL BY REFERENCE TO SWAP THE VALUES OF TWO VARIABLES*/


#include <stdio.h>
void swap (int *x, int *y) //function with pointer arguments
{
int temp;
temp = *x;
*x = *y;
*y = temp;
}

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

printf("\n\tThe numbers entered are as follows:\n");


for(j=0;j<SIZE;j++)
{
printf("\n\t%f", gpa[j]); //confirms input data
}
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",' ');
Functions 60

compare: // a label followed by a colon to use with goto statement


for(i=k; i<SIZE; i++)
{ // ‘k’ is a fixed position compared with the next ‘i’ positions
if (gpa[k] < gpa[i+1]) { temp = gpa[k];
gpa[k]= gpa[i+1];
gpa[i+1]= temp;
}
}

k++;
if(k<SIZE)goto compare; // goto statement followed by a label with semi-colon

printf("\n\n\tThe numbers arranged from highest to lowest are as follows:\n");


for(j=0;j<SIZE;j++)
{
printf("\n\t%f", gpa[j]); //prints sorted data
}
printf("\n\n\tThank you for using this program...\n\n\n\n"); return 0;
}
61
Functions
/*USING MULTIPLE FUNCTIONS TO SORT AN ARRAY*/
#include <stdio.h>
#include <windows.h>
#define SIZE 5 // changing the digits changes the number of array
element
void print_input(float*);
void print_msg(void);
void sort_input(float*);
void swap(float*, float*);
void print_output(float*);

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");
}

You might also like