C PROGRAMMING MODULE SMK PERMAS JAYA, PG, JHR.
Sentinel-controlled while Statement If value of num is
nonzero, the loop
#include<stdio.h> control expression is
main () considered True.
{
int num;
printf("Enter an integer or zero:");
scanf("%d",&num);
while(num)
{
printf(“The number is: %d\n",num);
printf("Enter an integer or zero:");
scanf("%d",&num);
}/* end_while */
}
Repetition: do … while Statement
Syntax:
NO semicolon
do Semicolon is
LoopBody-statement; compulsory
while (LoopControlExpression);
/* end_do_while */
the LoopBody-statement inside it will be executed once no matter what.
Then only the condition will be checked to decide whether the loop should be
executed again or just continue with the rest of the program.
Counter-controlled do … while Statement : Example
#include<stdio.h> #include<stdio.h>
main ()
main ( ) {
{ int num = 1;
printf(“Hello World\n”);
printf(“Hello World\n”); do
printf(“Hello World\n”); {
printf(“Hello World\n”);
printf(“Hello World\n”); printf("Hello World\n");
num++;
} }
while(num <=5); /*end_do_while */
}
51
C PROGRAMMING MODULE SMK PERMAS JAYA, PG, JHR.
#include<stdio.h> OUTPUT? #include<stdio.h>
main () main ()
{ {
int j = 10;
int j = 10;
while(j < 10)
{ do
printf(“J = %d\n“, j); {
j++; printf(“J = %d\n“, j);
} j++;
/*end_while */ }
} while(j < 10); /*end_do_while */
}
Sentinel-controlled do…while Statement : Example
#include<stdio.h> Sentinel value 999 will
main () terminate the loop.
{
int num;
printf("Enter an integer or 999:");
scanf("%d",&num);
do
{
printf("Number is: %d\n",num);
printf("Enter an integer or 999:");
scanf("%d",&num);
} while (num != 999);
/* end_do_while */
}
Repetition: for Statement Semicolons are compulsory
The syntax:
for (InitializationExp; LoopControlExp; UpdateExp) NO semicolon
LoopBody-statement;
/*end_for */
InitializationExp = assign initial value to a loop control variable
UpdateExp = change value of the loop control variable at the end of each loop
LoopControlExp = the loop condition - to compute to True (1) or false (0)
52
C PROGRAMMING MODULE SMK PERMAS JAYA, PG, JHR.
Counter-controlled for Statement : Example
#include<stdio.h> #include<stdio.h>
main () main ()
{ {
int num;
int num = 1;
for (num=1;num<=5;num++)
{ while(num <=5)
printf("Hello World\n"); {
} /*end_for */
} printf("Hello World\n");
num++;
Example } /*end_while */
}
#include<stdio.h>
main () Omit the InitializationExpression. Initial
{ value of the variable num depends on
int num=1; what?
for (;num<=5;num++)
{
printf("Hello World\n");
} /*end_for */
}
Sentinel-controlled for Statement
#include<stdio.h>
main ()
{
char ans;
printf(“Do you want to continue? (y/n):”);
for (scanf(%c”,&ans); ans != ‘y’ && ans != ‘Y’ && ans != ‘n’ && ans != ‘N’;
scanf(%c”,&ans))
{
// Display the following Display this as long
printf(“Please type y or n:"); as the user does not
key-in y or n.
} /*end_for */
}
53
C PROGRAMMING MODULE SMK PERMAS JAYA, PG, JHR.
Nested for Statement : Example Output:
12345
#include<stdio.h> 2345
void main( ) 345
{ 45
5
int i, j;
for(i=0; i<6; i++){
printf("\n");
for(j=i+1; j<6; j++)
printf("%d", j);
}
}
The continue and break Statements
Both of these statements are used to modify the program flow when a
selection structure or a repetition structure is used.
The break Statement
Used to forced exit of selection or terminate repetition structure.
#include<stdio.h> When the value of num is equal to
main () 2, the program will break out of the
{ for loop.
int num;
Output:
for (num=1;num<=5;num++) Hello World
{ Hello World
if (num==2)
break;
/* end_if */
printf("Hello World\n");
} /*end_for */
}
54
C PROGRAMMING MODULE SMK PERMAS JAYA, PG, JHR.
The continue Statement
Used to skip the rest of the loop body statements and continue with
the next repetition of the loop.
#include<stdio.h> When the value of num is equal to 2, the
main () program will skip the printf statement and
{ continue with the for loop.
int num;
Output:
for (num=1;num<=5;num++) Number 1
{ Number 3
if (num==2) Number 4
Number 5
continue;
/* end_if */
printf(“Number %d\n“,num);
} /*end_for */
}
Example :
55
C PROGRAMMING MODULE SMK PERMAS JAYA, PG, JHR.
10. Functions
Introduction to Functions
A function is a block of code which is used to perform a specific task.
It can be written in one program and used by another program without
having to rewrite that piece of code.
Functions can be put in a library. If another program would like to use them, it will
just need to include the appropriate header file at the beginning of the program
and link to the correct library while compiling.
A function is used by calling the name of the function.
Categories of Functions
Predefined functions (standard functions)
Built-in functions provided by C that are used by programmers without
having to write any code for them. Pre-defined at the standard C libraries.
Example: printf(), scanf(), main() etc
User-Defined functions
Functions that are written by the programmers themselves to carry out
various individual tasks.
Examples: CalculateAverage(), Sum() etc
56
C PROGRAMMING MODULE SMK PERMAS JAYA, PG, JHR.
Pre-defined Functions
<assert.h> Contains macros and information for adding diagnostics that
<ctype.h> aid program debugging.
<errno.h> Contains function prototypes for functions that test
characters for certain properties, convert lowercase letters to
uppercase and vice versa.
Defines macros that are useful for reporting error condition.
<float.h> Contains the floating point size limits of the system.
<limits.h> Contains the integral size limits of the system.
<math.h> Contains function prototypes for math library functions.
<setjump.h> Contains function prototypes for function that allow
bypassing of the usual function call and return sequence.
Pre-defined Functions
<signal.h> Contains function prototypes and macros to handle various
<stdarg.h> conditions that may arise during program execution.
<stddef.h>
<stdio.h> Defines macros for dealing with a list of arguments to a
<stdlib.h> function whose number and types are unknown.
<string.h> Contains common definitions of types used by C for
<time.h> performing certain calculations.
Contains function prototypes for the standard input/output
library functions and information used by them.
Contains function prototypes for conversions of numbers to
text and text to numbers, memory allocation, random
numbers, and other utility functions
Contains function prototypes for string processing functions.
Contains functions prototypes and types for manipulating
time and date.
User-defined Functions
A programmer can create his/her own function(s).
It is easier to plan and write our program if we divide it into several functions
instead of writing a long piece of code inside the main function.
A function is reusable and therefore prevents programmers from having to
unnecessarily rewrite what we have written before.
57
C PROGRAMMING MODULE SMK PERMAS JAYA, PG, JHR.
The Concept
vs.
Without Function With Function
#include <stdio.h> #include <stdio.h>
main() void print_menu(void);
{… main()
{…
printf(“This program draws a rectangle”);
… print_menu();
} …
} /* end main */
User-defined Functions void print_menu(void)
In order to write and use our own
{
printf(“This program draws a rectangle”);
} /* end function */
function, we need to do these:
1. Function declarations
Also called function prototype. Used to declare a function.
2. Function calls
Call the function whenever it needs to be used.
3. Function definitions
Also called function implementation, which define the function somewhere
in the program.
Example Function declaration
Function call.
#include <stdio.h>
void print_menu(void); Function definition
58
main()
{
print_menu();
print menu();
}
void print_menu(void)
{
printf(“This program draws a rectangle”);
} /* end function */
C PROGRAMMING MODULE SMK PERMAS JAYA, PG, JHR.
Function Declarations/Prototype
Consist of:
A function type.
A function name.
An optional list of parameter type enclosed in ().
Use commas to separate more than one parameter types. Use (void) or () if
there is no parameter.
A terminating semicolon.
59
C PROGRAMMING MODULE SMK PERMAS JAYA, PG, JHR.
Example:
void print_menu(void);
int GetScore(void);
void CalculateTotal(int);
char Testing(char, char);
Function Calls
A function is called by the declared function name.
Requires:
1. Name of the function.
2. A list of parameters, if any, enclosed in ()
3. A terminating semicolon.
Example:
print_menu();
print_menu(3);
print_menu(3, answer);
Two Types of Function Calls
Call by value
In this method, copy of actual parameter’s value is passed to the function. Any
modification to the passed value inside the function will not affect the actual
value.
In all the examples that we have seen so far, this is the method that has been
used.
Call by reference
In this method, the reference (memory address) of the variable is passed to the
function. Any modification passed done to the variable inside the function will
affect the actual value.
To do this, we need to have knowledge about pointers and arrays, which will be
discussed in the next chapter.
Function Definitions
A function definition is where the actual code for the function is written. This
code will determine what the function will do when it is called.
Consists of :
A function type (return value data type).
A function name.
An optional list of formal parameters enclosed in parentheses (function
arguments)
A compound statement ( function body)
60
C PROGRAMMING MODULE SMK PERMAS JAYA, PG, JHR.
A Function may…
1. Receive no input parameter and return nothing,
2. Receive no input parameter but return a value,
3. Receive input parameter( one or more) and return nothing, OR
4. Receive input parameter( one or more) and return a value
1.Receive no input parameter and return nothing: Example
#include <stdio.h> Function declaration.
void print_menu(void); Function call.
main() Function definition
{
print_menu();
}
void print_menu(void)
{
printf(“This program draws a rectangle”);
} /* end function */
2. Receive no input parameter and return a value: Example
#include <stdio.h> Function declaration.
int print_menu(void); Function call.
main()
{ Function definition
int value;
value = print_menu();
printf(“The return value is: %d”, value);
}
int print_menu(void)
{
printf(“This program draws a rectangle”);
return 1;
} /* end function */
3. Receive input parameter ( one or more) and return nothing: Example
#include <stdio.h> Function declaration.
void print_menu(int); Function call.
main()
{ Function definition
61
print_menu(3);
}
void print_menu(int x)
{
printf(“This program draws %d rectangles”, x);
} /* end function */
C PROGRAMMING MODULE SMK PERMAS JAYA, PG, JHR.
4. Receive input parameter ( one or more) and return a value: Example
#include <stdio.h> Function declaration.
int print_menu(int); Function call.
main()
{ Function definition
printf(“The value: %d\n”, print_menu(3));
}
int print_menu(int x)
{
printf(“This program draws %d rectangles\n\n”, x);
return x;
} /* end function */
Function with parameter/argument
When a function calls another function to perform a task, the calling function
may also send data to the called function. After completing its task, the called
function may pass data it has generated back to the calling function.
Two terms used:
Formal parameter
Variables declared in the formal list of the function header (written in function
prototype & function definition)
Actual parameter
Constants, variables, or expression in a function call that correspond to its
formal parameter
Example
#include <stdio.h> Formal parameter/argument
void print_menu(int); Actual parameter/argument
main()
{
print_menu(3);
}
void print_menu(int x)
{
printf(“This program draws %d rectangles”, x);
} /* end function */
62
C PROGRAMMING MODULE SMK PERMAS JAYA, PG, JHR.
Formal parameter/argument
#include <stdio.h> Actual parameter/argument
int print_menu(int);
main()
{
printf(“The value: %d\n”, print_menu(3));
}
int print_menu(int x)
{
printf(“This program draws %d rectangles\n\n”, x);
return x;
} /* end function */
Three important points concerning functions with parameters are:
The number of actual parameters in a function call must be the same as
the number of formal parameters in the function definition.
A one-to-one correspondence must occur among the actual and formal
parameters. The first actual parameter must correspond to the first formal
parameter and the second to the second formal parameter, an so on.
The type of each actual parameter must be either the same as that of the
corresponding formal parameter.
Example: More than one Parameters
Example : One Parameter
#include <stdio.h> Function declaration.
void print_menu(int); Function call.
main()
{ Function definition
print_menu(3);
}
void print_menu(int x)
{
printf(“This program draws %d rectangles”, x);
} /* end function */
63
C PROGRAMMING MODULE SMK PERMAS JAYA, PG, JHR.
Example: More than one Parameters
#include <stdio.h>
void print_menu(int, char);
main()
{
char answer = ‘y’;
print_menu(3, answer);
}
void print_menu(int x, char ans)
{
if (ans == ‘y’ || ans == ‘Y’)
printf(“This program draws %d rectangles”, x);
} /* end function */
64
C PROGRAMMING MODULE SMK PERMAS JAYA, PG, JHR.
11. Data Structures
11.1 ARRAY
4.11 Data Structure Statements
4.11.1 Arrays
4.11.2 Structure statements
Explanatory notes
Candidates should be able to
(a) declare an array;
(b) perform operations on arrays up to two dimension;
(c) give initial values to array elements;
(d) use the declaration, operation, calling, sending, and returning of arrays in
functions;
(e) describe the concept of structure in C language;
(j) use struct.
Introduction to Array
In C, a group of items of the same type can be set up using Array
An array is a group of consecutive memory locations related by the fact that they
all have the same name and the same type.
The compiler must reserve storage (space) for each element/item of a declared
array.
The size of an array is static (fixed) throughout program execution.
To refer to a particular location or element in the array, we specify the name of
the array (index or subscript) and the position number of the particular element in
the array.
65
C PROGRAMMING MODULE SMK PERMAS JAYA, PG, JHR.
Let say we have an array called a.
Notice that the position
starts from 0.
Name of the array a[0] -10
The position number within a[1] 99
the square brackets is formally a[2] -8
called a subscript. A subscript a[3] 100
can be an integer or an integer a[4] 27
expression. For example if a[5] 10
x = 1 and y = 2, then a[x+y]
is equal to a[3].
a[6] 1976
a[7] -2020
a[8] 1
Array Declaration
Array declaration is made by specifying the data type, it’s name and the number
of space (size) so that the computer may reserve the appropriate amount of
memory.
General syntax:
data_type array_name[size];
Examples:
int my_array[100];
char name[20];
double bigval[5*200];
int a[27], b[10], c[76];
Array Initialization
There are 2 ways to initialize an array: during compilation and during execution.
During compilation:
int arr[ ] = {1, 2, 3, 4, 5}; unsized array
We can define how many elements that we want since the array
size is not given.
66
C PROGRAMMING MODULE SMK PERMAS JAYA, PG, JHR.
int arr[3] = {90, 21, 22};
We can define only 3 elements since the array size is already
given.
int arr[5] = {2,4}
Initialize the first two elements to the value of 2 and 4 respectively,
while the other elements are initialized to zero.
int arr[5] = {0}
Initialize all array elements to zero.
During execution:
Using loop to initialize all elements to zero int arr[3], index;
for (index = 0; index < 3; index++)
arr[index] = 0;
Using loop and asking the user to specify the value for each element.
int arr[3], index;
for (index = 0; index < 3; index++)
{
printf (“arr[%d]:”,index);
scanf(“%d”,&arr[index]);
}
Assigning value to array element
We can assign a value to a specific array element by using its index number.
Example: let’s say we have an array that represent the number of inhabitant in 5
unit apartments.
int apartment[5]={3,2,6,4,5};
The above initialization indicates that there are 3 people living in apartment 0, 2
people living in apartment 1 and so on.
Let say that we have a new born in apartment 3, so we need to change the
number of inhabitant living in apartment three.
apartment[3] = apartment[3] + 1;
Now, we have the following values in our array:
3,2,6,5,5
Reading values from array elements
We can read a value from a specific array element by referring to the index.
For example, let’s say we want to know how many people leaving in apartment 3,
we could simple do this:
int apartment[5] = {3,2,6,4,5};
int no_of_people;
no_of_people = apartment[3];
printf(“Apartment 3 has %d people”, no_of_people);
The above C code will produce the following output:
Apartment 3 has 4 people.
Hint!!! Remember that array index starts at 0
67
C PROGRAMMING MODULE SMK PERMAS JAYA, PG, JHR.
Sorting using array:
Example 1: finding total inhabitants There are total of 20 inhabitants
Output:
#include <stdio.h>
#define size 5
void main(void)
{
int apartment[size] = {3,2,6,4,5};
int index, total = 0;
for (index = 0; index < size; index++)
{
total = total + apartment[index];
}
printf("There are total of %d inhabitants",total);
}
68
C PROGRAMMING MODULE SMK PERMAS JAYA, PG, JHR.
Example 2: list down number of inhabitants in each apartment
#include <stdio.h>
void main(void)
{
int apartment[5] = {3,2,6,4,5};
int index, total = 0;
printf("%-7s %-15s\n","Apt No", "No of people");
for (index = 0; index < 5; index++)
{
printf("%4d %10d\n",index, apartment[index]);
}
}
Example 2 output 3
2
Apt NoNo of people 6
0 4
1 5
2
3
4
Passing Array to a Function
When we pass an array to a function, we are actually passing the pointer to the
first element in the array to the function. Therefore, any changes to the array
inside the function will also change the actual array inside the calling function.
When we want to pass an array to a function, we need to know these 3 things.
How to write the function prototype?
How to do function call?
How does the function header would look like?
Assume that we have the following array declaration.
flaot marks[10] = {0.0};
Say for example we want to write a function, called get_marks, which will read
marks from the user and store the marks inside the array.
69
C PROGRAMMING MODULE SMK PERMAS JAYA, PG, JHR.
Passing Array to a Function
Function prototype:
/* data type with square bracket */
void get_marks(float [ ]);
void get_marks(float *); /*treating array as pointer */
Function call:
get_marks(marks); /* just pass the array name */
Function header:
void get_marks(float marks[ ])
void get_marks(float *marks) /*treating array as pointers */
Example 1: parameter received as an array
#include <stdio.h>
#define size 10
void get_marks(float [ ]);
float calc_average(float [ ]);
void main(void) Example 1:
{
float marks[size] = {0.0}; /*initializing the array
get_marks(marks); /* function call */
printf(“Average for marks given is %f”, calc_average(marks));
}
parameter received as an array
void get_marks(float marks[ ]) float calc_average(float marks[ ])
{ {
int i; float total = 0.0;
int i;
for (i = 0; i < size; i++)
{ for (i = 0; i < size; i++)
{
printf("Marks student %d:",i + 1);
scanf("%f",&marks[i]); total = total + marks[i];
} }
} return (total / size);
}
70
C PROGRAMMING MODULE SMK PERMAS JAYA, PG, JHR.
2-Dimensional Array
It is possible to create an array which has more than one dimension.
For example:
2D array: int array[4][2];
3D array: int array[4][2][10];
Graphical representation of a 2D array:
int myarray[4][2] = {1, 2, 3, 4, 5, 6, 7, 8};
12 This array has 4 rows and 2
columns.
Four 3 4
rows 5 6
78
Col 1 Col2
Variable initialization can also be done this way:
int myarray[4][2] = {{1, 2}, {3, 4}, {5, 6}, {7, 8}};
This method is less confusing since we can see the rows and columns division
more clearly.
To initialize a 2D array during execution, we need to use a nested for loop:
for (row = 0; row < 4; row++)
{
for (column = 0; column < 2; column++)
myarray[row][column] = 0;
}
Although it is possible to create a multi-dimensional array, arrays above 2-
dimensions are rarely used.
Passing a 2D array to a function
When a 2D (or higher dimensional) array is passed to a function, the size of the
second (or subsequent) subscript needs to be specified.
For example, if we have:
int twoD[4][5];
Then the function header which would take twoD as an argument should
be declared like this:
void Process2D(int twoD[ ][5])
An array is stored consecutively in memory regardless of the number of
dimensions. Therefore, specifying the subscripts in the function parameter will
help the compiler to know the boundary of the different dimensions.
71
C PROGRAMMING MODULE SMK PERMAS JAYA, PG, JHR.
11.2 STRUCTURE PROGRAMMING (STRUCT)
In this chapter you will learn about,
Introduction
Declaring Structure Type & Structure Variables
Referring and initializing structure elements
Passing structures to a function
Using typedef
Example using structure
Introduction
So far we have only used data types which have been defined by C such as int,
double and char.
It is also possible to create our own data types.
A user defined data type is called a structure.
A structure can contain both built-in data types and another structure.
The concept of structure is pretty much the same as arrays except that in an
array, all the data is of the same types but in a structure, the data can be of
different types.
Definition
A structure is a derived data type that represents a collection of a related data
items called components (or members) that are not necessarily of the same data
type.
Declaring Structure Type
General syntax: component
struct structure_name {
data_type element1; 72
data_type element2;
...
};
Example:
struct student {
char name[20];
int studentID;
char major[50];
};
C PROGRAMMING MODULE SMK PERMAS JAYA, PG, JHR.
Declaring Structure Variables
After declaring a structure type, we may declare variables that are of that type. A
structure variable declaration requires:
The keyword struct
The structure type name
A list of members (variable names) separated by commas
A concluding semicolon
Then, assume that variable of structure type student is my_student. So the
declaration should be written as;
struct student my_student;
Based on example: struct student
By including this declaration in our program, we are informing the compiler about
a new data type which is a user defined data type.
The declaration just makes the compiler aware the existent of new data type but
does not take an action yet.
Based on the declaration of
struct student my_student;
causes the compiler to reserve memory space for variable my_student and the
components of its structure.
Based on example: struct student Values
Structure variable Components Simon
0078
my_student name CS
studentID
major
Conceptual memory structure variable my_student of type student (assuming that the
components of variable my_student have already been assigned values)
73
C PROGRAMMING MODULE SMK PERMAS JAYA, PG, JHR.
Based on example: struct student
It is possible to combine the declarations of a structure type and a structure
variable by including the name of the variable at the end of the structure type
declaration.
struct student { = struct student {
char name[20]; char name[20];
int studentID; int studentID;
char major[50]; char major[50];
}; } my_student;
struct student my_student;
Declaring Nested Structure
Members of a structure declaration can be of any type, including another
structure variable.
Suppose we have the following structure declaration, which is a member of struct
type student:
struct address {
int no;
char street[20];
int zipcode;
};
Declaring Nested Structure
We can rewrite the structure student declaration as follow:
struct student {
char name[20];
int studentID;
char major[50];
struct address addr;
};
This structure type student can be written as;
struct student {
char name[20];
int studentID;
char major[50];
struct address{
int no;
char street[20];
int zipcode;
};
};
74
C PROGRAMMING MODULE SMK PERMAS JAYA, PG, JHR.
Referring and Initializing Structure Elements
A structure contains many elements. Each elements of a structure can be
referred to / accessed by using the component selection operator “.” (dot).
Let us use the structure student which we have seen before as an example:
struct student {
char name[20];
int studentID;
char major[50];
};
struct student my_student;
Therefore to refer to the element of a structure, we may write as follow;
my_student.name;
my_student.studentID;
my_student.major;
Referring and Initializing Structure Elements
Therefore, we can initialize each elements of a structure individually such as:
struct student my_student;
my_student.studentID = 10179;
Or we can initialize the structure while we are creating an instance of the
structure:
struct student my_student = {“Ahmad”, 10179, “IT”}
Notice that it is possible to use the ‘=’ operator on a struct variable. When the ‘=’
sign is used, each elements of the structure at the right hand side is copied into
the structure at the left hand side.
Example: Structure Initialization
struct birthdate {
int month;
int day;
int year;
};
struct birthdate Picasso = {10, 25, 1881};
printf(“Picasso was born : %d/%d/%d\n”, Picasso.day,
Picasso.month, Picasso.year);
Output :
Picasso was born : 25/10/1881
75
C PROGRAMMING MODULE SMK PERMAS JAYA, PG, JHR.
Passing Structures to a Function
Call by Value:
We can pass the student structure that we have created before to a function
called display( ) as follows:
void display (struct student); /* function prototype */
display (student1); /* function call */
void display (struct student s1); /* function header */
where student1 is a variable of type struct student.
In the above function, a copy of the student structure will be created locally for
the use of the function. Any changes to the structure inside the function will not
affect the actual structure.
Example Using Structure: Call by value
#include <stdio.h>
#include <string.h>
struct student{
char name[20];
int id;
};
void display(struct student); /* function prototype */
void main(void)
{
struct student student1;
strcpy(student1.name, "Ahmad"); /*initialising variable */
student1.id = 12345; /*initialising variable */
display(student1);
}
void display(struct student s1) /* make a local copy of the structure */
{
printf("Name: %s\n", s1.name);
printf("ID: %d\n", s1.id);
}
76
C PROGRAMMING MODULE SMK PERMAS JAYA, PG, JHR.
Example Using Structure: A Function that return a structure
#include <stdio.h>
#include <string.h>
struct student{
char name[20];
int id;
};
struct student read(void); /* function prototype */
void main(void)
{
struct student student1;
student1 = read(); /*function call */
printf("Name: %s", student1.name);
printf("\nID: %d\n", student1.id);
}
struct student read(void)
{
struct student s1;
printf("Enter name:");
scanf("%s",s1.name); /* alternative: gets(s1.name); */
printf("Enter ID:");
scanf("%d",&s1.id);
return s1;
}
Call by reference
It is also possible to use pointers and pass the reference of the structure to the
function. This way, any changes inside the function will change the actual
structure as well.
To pass a structure variable as a reference, the Read( ) function can be written
this way:
void Read(struct student *); /* function prototype */
Read(&student1); /* function call */
void Read(struct student *s1); /* function header */
where student1 is a variable of type struct student.
77
C PROGRAMMING MODULE SMK PERMAS JAYA, PG, JHR.
Call by reference
Take note that when a structure is declared as a pointer, the elements in the
structure cannot be referred to using the ‘.’ operator anymore. Instead, they need
to be accessed using the ‘->’ operator (indirect component selection
operator).
For example:
void Read(struct student *s1)
{
s1->studentID = 10179;
scanf(“%s”, s1->name);
}
Example Using Structure: Call by reference
#include <stdio.h>
#include <string.h>
struct student{
char name[20];
int id;
};
void Read (struct student *); /* function prototype*/
void main(void)
{
struct student student1;
Read(&student1); /* function call: passing reference */
printf("Name: %s", student1.name);
printf("\nID: %d\n", student1.id);
}
void Read (struct student *s1) /* function header, receive structure as a pointer
variable */
{
printf("Enter name:");
scanf("%s",s1->name); /* you can also use: gets(s1->name) */
printf("Enter ID:");
scanf("%d",&s1->id);
}
78
C PROGRAMMING MODULE SMK PERMAS JAYA, PG, JHR.
Using typedef in Structure Declarations
The keyword typedef provides a mechanism for creating synonyms (aliases) for
previously defined data types.
Here is an example on how to use typedef when declaring a structure:
struct student {
char name[20];
int studentID;
char major[50];
struct address addr;
};
Using typedef in Structure Declarations
By using typedef:
typedef struct student StudentData;
we are now aliasing the structure with a name to be used throughout the
program. So instead of writing the word “struct” before declaring a struct variable
like the following
struct student my_student;
we can now write:
StudentData my_student;
We could use the alias name when passing the structure to a function:
void display(StudentData s1);
Example : using typedef
#include <stdio.h> void display(StudentData s1)
#include <string.h> {
struct student{ printf("Name: %s\n", s1.name);
char name[20]; printf("ID: %d\n", s1.id);
int id;
}
};
typedef struct student StudentData;
void display(StudentData); /* function prototype */
void main(void)
{
StudentData student1;
strcpy(student1.name, "Ahmad");
student1.id = 12345;
display(student1);
}
79
C PROGRAMMING MODULE SMK PERMAS JAYA, PG, JHR.
Example: Array of structure
#include <stdio.h>
#define NUM_STUDENTS 10
struct student {
int studentID;
char name[20];
int score;
char grade;
};
typedef struct student StudentData;
void Read (StudentData student[]);
void CountGrade (StudentData student[]);
void main ( )
{
StudentData student[NUM_STUDENTS];
Read(student);
CountGrade(student);
}
void Read (StudentData student[])
{
int i;
for (i = 0; i < NUM_STUDENTS; i++) {
printf("Enter the studentID: ");
scanf("%d", &student[i].studentID);
printf("Enter the name: ");
scanf("%s", student[i].name);
printf("Enter the score: ");
scanf("%d", &student[i].score);
printf("\n");
}
}
80
C PROGRAMMING MODULE SMK PERMAS JAYA, PG, JHR.
void CountGrade (StudentData student[])
{
int i;
for (i = 0; i < NUM_STUDENTS; i++) {
if (student[i].score > 90)
student[i].grade = 'A';
else if (student[i].score > 80)
student[i].grade = 'B';
else if (student[i].score > 65)
student[i].grade = 'C';
else if (student[i].score > 50)
student[i].grade = 'D';
else
student[i].grade = 'F';
printf("The grade for %s is %c\n", student[i].name, student[i].grade);
printf("\n");
}
}
Sample Output
/* Sample Output
Enter the studentID: 789654
Enter the name: Salman
Enter the score: 96
Enter the studentID: 741258
Enter the name: Jack
Enter the score: 79
:
:
:
The grade for Salman is A
The grade for Jack is C
:
:
Press any key to continue
*/
81
C PROGRAMMING MODULE SMK PERMAS JAYA, PG, JHR.
82