Professional Documents
Culture Documents
CDCP2202
C Programming II
Kalaivani K. Radakrishnan
Topic 2 Repetition 17
2.1 while Statement 17
2.2 do-while Statement 21
2.3 for Statement 24
2.3.1 The Relationship between for and
while Statements 27
2.4 Controlling Loops 28
2.4.1 Endless Loop 29
2.4.2 while Loop Controlled by Condition 30
2.4.3 while Loop Controlled by Sentry 31
2.5 continue Statement 32
2.6 break Statement 33
Summary 34
Key Terms 35
Topic 3 Functions 36
3.1 What are Functions? 37
3.2 Function Definition 38
3.3 Function Prototype 40
3.4 Function Calls 43
3.4.1 Functions without Returned Data Type
and without Parameters 43
3.4.2 Functions without Returned Data Type
but with Parameters 45
3.4.3 Functions with Returned Data Type
and with Parameters 47
3.5 Library Functions of C 48
Summary 51
Key Terms 51
Topic 4 Files 52
4.1 File Support in C Programs 52
4.1.1 Binary File 53
4.1.2 Text File 53
4.2 File Operations 53
4.2.1 fopen() 53
4.2.2 fclose() 55
4.2.3 fprintf() 56
4.2.4 fscanf() 57
Summary 61
Key Terms 62
Appendix 63
INTRODUCTION
CDCP2202 C Programming II is an advanced course and a continuation of
CDCP2101 C Programming I, which is offered by the Faculty of Information
Technology and Multimedia Communication at Open University Malaysia
(OUM). This course is worth 2 credit hours and should be covered within 8 to 15
weeks.
COURSE AUDIENCE
This course is offered to all learners taking the Diploma in Information
Technology. Learners are required to attend this course and master the subject.
This course is crucial for them to apply knowledge and skills from previous
modules by implementing programming commands, syntax and techniques.
As an open and distance learner, you should be able to learn independently and
optimise the learning modes and environment available to you. Before you begin
this course, please confirm the course material, the course requirements and how
the course is conducted.
STUDY SCHEDULE
It is a standard OUM practice that learners accumulate 40 study hours for every
credit hour. As such, for a two-credit hour course, you are expected to spend 80
study hours. Table 1 gives an estimation of how the 80 study hours could be
accumulated.
Study
Study Activities
Hours
Understanding course content and initial discussions 5
Read four topics and complete exercises given at a rate of 10 hours per 40
topic
Attend four tutorial sessions at a rate of 2 hours per session 8
Access to Websites 7
Complete one assignment at a rate of 10 hours per assignment 10
Revision 10
TOTAL STUDY HOURS 80
COURSE OUTCOMES
By the end of this course, you should be able to:
1. Apply computer programming concepts and problem solving methods
using common programming techniques; and
2. Write, compile and run computer programming using C language.
COURSE SYNOPSIS
This course is divided into four topics. The synopsis for each topic is presented as
follows:
Topic 1 describes the control feature in programming where learners can make
selection programs based on certain conditions.
Topic 2 explains the control feature in programming where learners can make
repetition programs based on certain conditions.
Learning Outcomes: This section refers to what you should achieve after you
have completely covered a topic. As you go through each topic, you should
frequently refer to these learning outcomes. By doing this, you can continuously
gauge your understanding of the topic.
Summary: You will find this component at the end of each topic. This component
helps you to recap the whole topic. By going through the summary, you should
be able to gauge your knowledge retention level. Should you find points in the
summary that you do not fully understand, it would be a good idea for you to
revisit the details in the module.
Key Terms: This component can be found at the end of each topic. You should go
through this component to remind yourself of important terms or jargon used
throughout the module. Should you find terms here that you are not able to
explain, you should look for the terms in the module.
section), at the end of every topic or at the back of the module. You are
encouraged to read or refer to the suggested sources to obtain the additional
information needed and to enhance your overall understanding of the course.
PRIOR KNOWLEDGE
A basic knowledge and skills in problem solving and C syntax that you would
have learned from CBCP2101 are very useful to be used for this module. Learners
will continue to practise common programming control and techniques by
applying the knowledge and skills.
ASSESSMENT METHOD
Please refer to myINSPIRE.
REFERENCE
Marini Abu Bakar, Norleyza Jailani & Sufian Idris. (2000). Bahasa Pengaturcaraan
C. Kuala Lumpur: Prentice Hall.
INTRODUCTION
In Topic 2 of CDCP2101, you have learnt how to solve problems using the
sequence, selection and repetition control structures. C language has a few
selection structures that control the flow of the program which is if, switch
and break.
1.1 if STATEMENT
The if statement is used to represent the selection structure. The selection
structure allows us to choose and execute only one of the many choices available
based on a certain condition. Selection structure is divided into three main types,
which are if selection, if-else selection and nested if selection.
if(expression)
statement;
The if statement above will only be executed when the value of the expression is
true. If the statement is false, the statement will not be executed. Expression can
only be made up of relational or logical expressions that would have the value of
true or false.
Input a number: 8
8 is a positive number
The statements above have been executed because the value of the expression is
true. If the value is false, then there would not be any message displayed on the
screen.
#include <stdio.h>
#define LEAPYEAR 2000
void main()
{
int days = 365;
int year;
printf(“Input year: “);
scanf(“%d”, &year);
if (year == LEAPYEAR)
days += 1;
printf(“Number of days this year is %d”, days);
}
Output:
In Example 1.2 above, the if statement determines the number of days in a year.
If the year is a leap year, then it will add one extra day to the number of days for
that year. Notice however, if statement has one statement only, which is days
+=1;. The printf() after the if statement will be executed, whether the if
statement is true or false.
ACTIVITY 1.1
Write a C program that will display the value of square root for an
integer number.
if(expression)
statement-1;
else
statement-2;
#include <stdio.h>
void main()
{
int num;
printf(“Input an integer number: “);
scanf(“%d”, &num);
if (nom > 0)
printf(“%d is a positive number.\n”, num);
else
printf(“%d is a negative number.\n”, num);
}
Output:
In Example 1.3, the if expression tests the input entered, and the expression
returns true. As 3 > 0 is true, the first statement is displayed, „3 is a positive
number‰.
Example 1.4: Comparing two integer numbers to get the smaller of the two.
Output:
In Example 1.4, the comparison of two integer numbers input is made. The
program will evaluate the value of the expression num1 < num2 as false.
Therefore, the second statement will be printed, „8 is less than 17‰.
Copyright © Open University Malaysia (OUM)
TOPIC 1 SELECTION CONTROL STRUCTURE 5
ACTIVITY 1.2
if(expression-1)
statement-1;
else if(expression-2)
statement-2;
else
statement-3;
Example 1.5: Display a message whether the value entered is positive or negative
or zero.
#include <stdio.h>
void main()
{
int num;
printf(“Input an integer number: “);
scanf(“%d”, &num);
if (num > 0)
printf(“%d is a positive number.\n”, num);
else if (nom < 0)
printf(“%d is a negative number.\n”, num);
else
printf(“%d is zero.\n”, num);
}
Output:
In Example 1.3, the condition is checked for more than zero to be positive, but
zero or less than zero is displayed as negative values, which is a problem.
ACTIVITY 1.3
This statement is very useful when the choice is dependent on the value for one
variable or simple expression. The value for the expression can only be of type
int and char, but not of type float. Consider the syntax for the statements
switch and break:
switch (expression) {
case expression-1 :
statement-1;
break;
case expression-2:
statement-2;
break;
:
case expression-m :
statement-m;
break;
default :
statement-n;
break;
}
The break statement will bring the program control out of the switch
statement without executing the next case statement. If the break statement is
not given, then the next statement will be executed, regardless the case value
matches or not.
#include <stdio.h>
void main()
{
int digit;
printf(“Input a digit: “);
scanf(“%d”, &digit);
switch (digit)
{
case 1: printf(“One”);
break;
case 2: printf(“Two”);
break;
case 3: printf(“Three”);
break;
case 4: printf(“Four”);
break;
Copyright © Open University Malaysia (OUM)
8 TOPIC 1 SELECTION CONTROL STRUCTURE
case 5: printf(“Five”);
break;
case 6: printf(“Six”);
break;
case 7: printf(“Seven”);
break;
case 8: printf(“Eight”);
break;
case 9: printf(“Nine”);
break;
default : printf(“Not a digit”);
}
}
Output:
Input a digit: 5
Five
ACTIVITY 1.4
Write a C program that will display the name of a colour when the
first letter of the colour is input.
The differences between these two control statements are given in the following
Table 1.1:
ACTIVITY 1.5
(a) What would happen if the if statement does not have an else?
if (expression-1)
if (expression-2)
statement-1;
else
statement-2;
(c) What is the use of the reserved keyword break? What would
happen if the break statement is not given in the switch-
case control statement?
The following programs (Program 1.1, Program 1.2 and Program 1.3) are meant
for Self-Check 1.1. Kindly refer to the respective section to continue your
practices.
Program 1.1
/* if-else program. Prints a certain message according
to the body weight index */
#include <stdio.h>
void main() {
float weight, height, bodyWeightIndex;
printf(“Enter your weight (kg): ”);
scanf(“%f”, &weight);
Program 1.2
/* if-else program. P r i n t s a c e r t a i n
message according to the body weight
i n d e x */
#include <stdio.h>
void main() {
float weight, height, bodyWeightIndex;
printf(“Enter your weight (kg): ”);
scanf(“%f”, &weight);
printf(“Enter your height (m): ”);
scanf(“%f”, &height);
bodyWeightIndex = weight / (height * height);
Program 1.3
/* Prints character categories that is input using
logical expression */
#include <stdio.h>
void main() {
char chr;
scanf(“%c”, &chr);
if ((chr >= ‘a’ ) && (chr <= ‘z’))
printf(“Lower case letter\n”);
else if ((chr >= ‘A’) && (chr <= ‘Z’))
printf(“Capital Letter\n”);
else if ((chr >= ‘0’) && (chr <= ‘9’))
printf(“Digit\n”);
else
printf(“Special Character\n”);
}
SELF-CHECK 1.1
1. What is the value of bodyWeightIndex and output message
displayed for each of the cases below?
(a) Given the data above, edit, compile and execute Program
1.1. Fill in the information.
(b) Modify Program 1.1 to 1.2. Test the data above and fill in
the information.
(c) Edit, compile and execute Program 1.3.
SELF-CHECK 1.2
(b) int i;
i = 14;
if (i % 2 == 0)
printf(“Even Number\n”);
else
printf(“Odd Number\n”);
float i, j;
scanf(“%f”, &i);
if (i > 3.0)
if (i < 12.0)
j = i / 100 * 5;
else
j = 10 / i * 2.5;
else
j = 5.5 * i / 2;
printf(“%f”, j);
SELF-CHECK 1.3
SELF-CHECK 1.4
1. You do not need to write a program for this problem. Instead, you
need to solve how to calculate the charges for using water for a
particular month that is provided by the Water Utility Company.
Charges are calculated based on these information:
Outstanding payment amount;
Previous meter reading; and
Current meter reading.
2. Write a program that would calculate the marks needed for the
final examination by a student to enable him/her achieve a
particular grade in a course. Your program should have
input/output interaction as shown below:
Ć You have looked at the C syntax for the selection control. There are three
forms of the if statement ă if, if-else and nested if-else.
Ć You have also learnt how to use the switch and break statements.
INTRODUCTION
In the previous topic, you were introduced to the algorithm of a repetition
structure where a few statements can be repeated until a condition is satisfied. In
C, repetition structure can be represented by while, do-while and for
structure.
initialisation;
while(expression)
{
statement;
counter;
}
#include <stdio.h>
void main()
{
int x = 1;
while (x <= 10)
{
printf(“%d\t”, x);
x++;
}
}
Output :
1 2 3 4 5 6 7 8 9 10
In Example 2.1 above, the expression x <= 10, is true at the beginning. After
displaying 1 on the screen, x has been updated by 1, by the x++ statement.
Because the expression in the while expression,(2 <= 10) is still true,
therefore, 2 is also printed on the screen. These steps will be repeated until x
value is added 1 to be 11. The expression is now false, and the while statement
will end.
In Example 2.2, we will see how an input value is used in the while expression.
#include <stdio.h>
void main()
{
int num, x = 1, total = 0;
Output:
Input number: 10
Total of numbers from 1 to 10 is 55.
ACTIVITY 2.1
ACTIVITY 2.2
Discuss why the input is done twice in the program you have written
in Activity 2.1(b).
SELF-CHECK 2.1
initialisation;
do
{
statement;
counter;
} while (expression);
The initialisation always has a variable and its value will be tested at the end.
Update the counter to ensure that the expression value becomes false eventually
so that the do-while statement can end.
#include <stdio.h>
void main()
{
int x = 1;
do
{
printf(“%d\t”, x);
x++;
} while (x <= 10) ;
}
Output :
1 2 3 4 5 6 7 8 9 10
You would have noticed that this program is similar to the one in Example 2.1.
To solve the problem of displaying numbers from 1 to 10, you can use any
repetition structure, while or do-while. It is actually a choice of preference.
Next, you will see how to stop a loop (repetition) by using an input from the
user, in Example 2.4.
Example 2.4: Adding all positive numbers being input until 0 is entered.
Output:
Input a positive number to add, 0 to stop: 1
Input a positive number to add, 0 to stop: 2
Input a positive number to add, 0 to stop: 3
Input a positive number to add, 0 to stop: 4
Input a positive number to add, 0 to stop: 5
Input a positive number to add, 0 to stop: 0
Total of positive numbers entered : 15
ACTIVITY 2.3
SELF-CHECK 2.2
Write a code segment that uses a while loop which would execute
similarly to the execution of the do-while loop below.
do {
scanf(“%d”, &data);
} while (data != -1);
You will now see the program that displays the numbers 1 to 10, but using the
for statement instead.
#include <stdio.h>
void main()
{
int x;
for (x = 1; x <= 10; x++)
printf(“%d\t”, x);
}
Output :
1 2 3 4 5 6 7 8 9 10
You will notice that in example 2.1, 2.3 and 2.5, the output is the same, only those
different loops were used: while, do-while and for. All three loops have
similarities: initialisation, expression and counter. Which one of these loops
would you use and why?
(a) Initialisation ă without the initial value, the expression cannot be tested,
and therefore the statement is not executed.
(c) Counter ă most often forgotten, as in the while and do-while loops, it is
part of the compound statements. If the counter is not done, the program
might not end, as the expression might be true, based on the initial value.
According to C syntax, the for statement body has to be one statement. What
Copyright © Open University Malaysia (OUM)
26 TOPIC 2 REPETITION
Consider Program 2.1 that will read 10 numbers and then output the total and
average.
Program 2.1
#include <stdio.h>
void main () {
int x;
int number;
int total;
float average
Compound statement
total = 0;
for (x = 0; x < 10; x++)
{
printf (“Enter an integer value”)
scanf(“%d”, &number);
total = total + number;
}
ACTIVITY 2.4
Write a C program that can display the output below using for, do-
while or while loop:
*****
***
*
SELF-CHECK 2.3
3. Write the segment code again below by changing the for loop
with the while loop.
We can use the segment code below as a template to write a while loop which is
comparable to the for loop.
initialisation;
while (test) {
statement;
update;
}
ACTIVITY 2.5
Sketch the execution flow for the while loop code template above.
Compare that to the flow chart in Figure 2.2.
2
while (x) {
total += x;
x--;
}
Statement while 2 is comparable to statement while 1 since both will end when
the value of x reaches zero. Sometimes the test component of a while
statement is false at the beginning of the statementÊs execution. In this case, the
body of the loop will not be executed at all.
Copyright © Open University Malaysia (OUM)
TOPIC 2 REPETITION 29
In that code segment, an integer number will be input and assigned to the
variable num. Variable x is initialised to the value 0. The while statement will
increase variable x by 1 repeatedly until the value of the variable is the same as
the value of num.
The code segment above looks reasonable. Still, what will happen if a negative
value is input? We will see that the execution of the while statement will not
end. The test component for the statement is always true since the value of
variable x will not be the same as num. If this condition happens, we would say
that an endless loop has been created.
In Example 2.6, a program that shows an endless loop is given. Please execute
this program with care, ending all other applications before running this
program.
#include <stdio.h>
void main()
{
for ( ; ; )
printf(“This statement is never displayed”);
}
Program in Example 2.6 shows that a for loop can be written without the
initialisation, expression and counter, but with the correct syntax (semicolons ;) to
Copyright © Open University Malaysia (OUM)
30 TOPIC 2 REPETITION
divide the different parts. The program above can be executed, without any
syntax errors, but the statement is always true and therefore does not end.
ACTIVITY 2.6
Try to rewrite the program above using the for repetition control
structure.
Program 2.2
/* Input the number of data followed by the data itself.
Then count the number of even and odd numbers for input
data.*/
#include <stdio.h>
void main() {
int count, x, num, countEven, countOdd;
x = countEven = countOdd = 0;
printf(“Number of data:”);
scanf(“%d”,&count);
while(x<count){
printf(“Enter positive integer:”);
scanf(“%d”,&num);
if(num%2==0)
countEven++; Do these
else repeatedly: Read
countOdd++; the data and update
x++; the number of odd
} and even numbers
Calculated output
ACTIVITY 2.7
Think of the output for Program 2.2 if the input given is as follows:
Number of data: 5
Number of positive integer: 3 2 1 4 7
Therefore,
(a) Sentry value is the value that is out of the boundary of valid data.
(b) Loops like these are suitable to be used in situations where the number of
repetitions cannot be determined.
SELF-CHECK 2.4
continue statement is used when the statement immediately after in the loop is
not to be executed, and the program control will return to the while, do-while
and for statement.
Output:
0 even number
Prints even numbers only !
2 even number
Prints even numbers only !
4 even number
Prints even numbers only !
6 even number
Prints even numbers only !
8 even number
Prints even numbers only !
In Example 2.7 earlier, the for statement is repeated 10 times, from 0 to 9. Only if
the numbers are even ( x % 2 == 0 to test for even numbers), the first
printf() statement is executed. The second printf() statement is printed
every time the even numbers are printed, but not for when the numbers are odd
(as the continue statement controls the flow of execution to the for expression).
Example 2.8: Totalling numbers from 1 till total is more than 100.
#include <stdio.h>
void main()
{
int n, total=0;
for (n = 1; n <=25; n++)
{
total = total + n;
if (total >= 100)
break;
}
Copyright © Open University Malaysia (OUM)
34 TOPIC 2 REPETITION
Output:
Total value = 105
n value = 14
In Example 2.8, the break statement has caused the for statement to end before it
repeated 25 times as stated. It is because of the total has reached more than 100.
ACTIVITY 2.8
Ć You have been introduced to the three repetition constructs ă while, do-
while and for statements.
Ć The initialisation, expression and counter which are important for all
repetition constructs are explained.
Ć You have also seen the break and continue statements are used together
with the repetition constructs and how they can control the loopsÊ execution.
break Logical
continue Relational
counter Repetition
do-while Statement
for while
INTRODUCTION
C is a procedural language. It has functional features that enable us to structure
our programs better. So far, the program examples given are easy and small. In
fact, all program statements can be put into one function which is the main()
function. This structure is not suitable for large programs because it makes the
programs hard to read and understand. Proper code arrangement is needed so
that it can clarify logical structure and flow of program execution. This will make
sure programs are easier to read, understand and maintained.
In Figure 3.1 above, the main function will be executed first. At the statement call
functionA, the whole of functionA will be executed. After ending functionA,
control is transferred back to the main function. The next statement is call
function B, where the whole function B is executed. At the end of function
B, control is back to the function main and ends.
The function head is made up of three main parts: returned data type, function
name and parameter list. All three parts are important to determine the identity of
the function, and other functions cannot have the same function head.
The function body is made up of statements that you have learnt in the topics
before this, like declaring variables, input and output statements, selection and
repetition. The function body must be enclosed in { and }. The last statement in a
function should be the return statement (not necessary if returned data type is
void). There should only be one return statement per function.
Next, we will see some examples on how to write functions. Notice however, that
some of the examples are only showing functions and not the whole program
code. You cannot run these programs as they are. You should also include the pre-
processor files (#include <stdio.h>) and the main function.
In the above example, the display function does not have a returned data type
value and neither does it have any parameters. Therefore the word void is written
in its place. If nothing is written in the returned data type, it is of type int by
default.
Example 3.2: Function definition with a returned data type and a parameter list.
In Example 3.2, the returned data type is int, which means that the data is
returned from the function is of type integer. The name of the function is
addition and the parameter list has the declaration of two variables, x and y of
type integer. (Note: every variable must be defined separately in the parameter
list). The function body declares a variable called total, which will be assigned
the sum of x and y. The variable total value will be returned through the
return statement written on the last line of the function body.
#include <stdio.h>
void display_message (void); // function prototype
Output:
In function main
In function display_message
Return to function main
Let us look at some of the important sections of the program code in Example 3.3.
First, there is the function prototype, which will declare the name and returned
data type as well as any parameter types of the function. Next, is the function call.
Function call is where the function name is used and the control of the program is
transferred to the function. Lastly, the function definition which we have recently
seen. All of these sections will be explained in detail in the next section.
ACTIVITY 3.1
ACTIVITY 3.2
1. Can the function definition start with the name of the function
(without first writing the returned data type)?
The main reason the function prototype is written is to proved information of the
type of return value (if any), and the number and type of parameters. The
definition of function prototype is the same with the function head, and is ended
with the semicolon(;). The function prototype given below is also accepted, as the
name of the variables in the parameter list can be ignored.
One of the advantages of using a function prototype is that the programmer can
easily read and identify all the functions that are used in the program.
#include <stdio.h>
void square (int x); // function prototype
void main(void)
{
int num = 5;
square (num); // function call
}
In Example 3.4 above, the function prototype: void square (int x); is
checked when the function call: square (num); is made. Because of the
returned data type, function name and parameter list (an integer type variable) is
the same as the function prototype, there is no error.
In Example 3.5, shows how an error in the function prototype leads to the
program not able to run efficiently.
Example 3.5: How an error in the function prototype leads to the program not
able to run efficiently.
#include <stdio.h>
int print_message (int num);
void main(void)
{
Copyright © Open University Malaysia (OUM)
42 TOPIC 3 FUNCTIONS
No output.
In Example 3.5 above, the compilation error happens when the statement
print_message (number); is compiled. This is because there isnÊt any
function prototype found with the void returned data type (the function
prototype has an integer returned data type). To avoid having errors like this,
ensure that the function prototype written above the main function and the
function definition: returned data type, function name and parameter list match.
ACTIVITY 3.3
#include <stdio.h>
void main (void) {
int x;
printf (“Input a value: “);
scanf(“%d”, &x);
printf(“Absolute value: %d\n”, absoluteValue(x));
}
If there is data to be sent to the function, use the parameters after the name of the
function to be called.
calculateSum(input1, input2);
square(num1, num2);
Example 3.7: How the values returning from the function are assigned.
int result;
Function calls are determined by the type of the function. In the next examples,
explanations will be given on each type of function.
function_name;
Copyright © Open University Malaysia (OUM)
44 TOPIC 3 FUNCTIONS
Even though there is no value sent to the function, there are still brackets () after
the function_name. It is also not assigned to any variable.
Example 3.8: Function without returned data type and without parameter.
#include <stdio.h>
void display (void);
void main(void)
{
display(); // function call
}
void display(void)
{
printf(“Welcome to the world of C Programming\n”);
}
void draw_sides4(void) {
int row, columns;
for (row=0; row < 4; row++) {
for (column=0; column < 5; column++)
printf(“*”);
printf(“\n”);
}
}
Notice however the keyword void after the name of the function. This states
that the function is declared without any parameters.
void main(void) {
printf(“This is a square\n”);
draw_sides4();/*calling a function without
a parameter*/
printf(“Good Luck!”);
}
This is a rectangle
*****
*****
*****
*****
Good Luck!
function_name(parameter list);
#include <stdio.h>
void multiplication (int, int); // function prototype
void main(void)
{
Figure 3.3 shows another example of how the function can be utilised with
parameters.
The variable must be the same type as the returned data type that was written in
the called function head.
Let us now take a look at a function, Example 3.10, that shows how the function
maximum is called and the maximum value is returned to the main function.
#include <stdio.h>
int maximum (int, int);
void main(void)
{
int x, int y;
return max;
}
Notice that the variable x and y are declared as integer in the main function and
also in the function head of maximum function. This phenomena is called local
variables, where the variables are declared and used in a particular function, and
are not known outside the boundary of the function. You may name the variables
in different functions differently, or choose the same name, as their values are
kept in separate memory cells.
ACTIVITY 3.4
Write a C program that will use the function named positive that
receives one data of type integer, and returns the absolute value of it
to the main function where it is displayed.
C Language provides library functions that have many types of functions already
defined and can be used again by programmers. For example, sqrt() function
to calculate square root is available in the mathematics standard library. The next
example contains examples of reusing this sqrt() function.
#include <stdio.h>
#include <math.h> // math preprocessor file
void main(void)
{
double num, amount;
printf(“Enter number: “);
scanf(“%f”, &num);
amount = sqrt (num); // C standard function
printf(“Square Root of %lf: %lf”, num, amount);
}
Output:
Let us look at the sqrt() function calls in the program code above that causes
the execution of the function code. In the call, the value of the argument num is
passed from the calling function to be used in the calculation.
For example, let us say the number being input is 16.0. Therefore the variable
amount calls the sqrt() function to calculate the square root of that number.
After the function code is executed, the control of the program will move back to
the calling program. The result of the calculation will be returned and assigned to
the amount variable. The program ends by outputting the result of the
calculation using the printf() function.
Notice however that the program above contains the pre-processor directives
#include<math.h>. This instruction will cause the header file math.h to be
included with the program code before compilation. The header file is needed
because it contains useful information on the functions that are available in the
mathematics standard library including the function sqrt() that will be reused
in the program code above.
ACTIVITY 3.5
ACTIVITY 3.6
SELF-CHECK 3.1
What is the value returned by the function for the calls below:
(a) calcPay(35, 120)
(b) calcPay(50, 100)
******
******
******
******
Ć In this topic, we have learnt all about functions which are small programs
that can do a specific task.
Ć We have seen how to define and call functions. There are some functions that
require parameters when called. The parameters are input to the function.
Ć At the end, we have seen the C standard function that can be used after
adding the appropriate header files that contains the function in our
program.
Ć Two types of variables that have different scopes are local and global.
Ć A variableÊs scope determines the area where the variable can be reached.
INTRODUCTION
Data that is used in the programming examples in the topics before is only
temporary. After the program has ended, the data will be lost. Therefore, ways to
keep data permanently has to be known. In this topic, you will learn about files
used to store data.
There are two methods of accessing data that is stored in files, which is
sequential or random access. These access methods determine how data is read,
written, modified and deleted by the program.
Files in C language are categorised into two types: binary file or text file. Binary
files can keep data in smaller sizes but text files are easier to use.
4.2.1 fopen()
Before any operation can be carried out on a file, it must be opened first. In C,
when opening any file, we must send file name and access mode (either we want
to read, write or add data to a file). The relevant function used is fopen().
Format to invoke (call) it is as below:
fopen(file_name, access_mode)
The file_name is the name of the file to be opened, whereas access_mode is the
mode used to access the file and will be explained in detail later. The fopen()
function returns a pointer that will point to the file opened. This pointer is used
later in the operations that are carried out on the file. Usually, the pointer will be
kept in a variable type FILE *. Look at the code segment:
Copyright © Open University Malaysia (OUM)
54 TOPIC 4 FILES
FILE *fptr;
Fptr = fopen(“datafile”’ “r”);
fptr is a variable that is declared to keep the file pointer. After the calling of
fopen()function ends, the pointer pointing to the file „datafile‰ will be returned
by the function. The pointer will then be assigned to fptr.
Access mode of any file determines the operations that can be done on that file.
Table 4.1 shows the access modes that are specified in the fopen()function calls.
The code segment below shows the usage of fopen() function to open the file
input and file output. File input is opened for reading only whereas file output is
opened for writing only.
Sometimes the file that is required to be opened cannot be opened using the
fopen() function. For example, we want to open a file to be read, but the file
does not really exist. In this situation, the fopen() function will return a null
pointer (represented by the value NULL) if it fails to open the file in the required
mode.
It is important that we can trace the event so that the errors that cause the file
operation to return a null pointer can be avoided. The code segment below
shows how to trace the return of null pointer by fopen().
The if statement in the code segment tests whether the opening of inputfile is
successful or fails by testing if fptr is equivalent to NULL or not. If fptr is
NULL, it means that the file failed to be opened. If this happens an error message
will be displayed followed by calling of the exit()function. The exit()
function is a library function to stop execution of a program. To use it, we must
use the header file stdlib.h together with the program by entering the pre-
processor command at the beginning of the program.
#include <stdlib.h>
ACTIVITY 4.1
4.2.2 fclose()
When we have finished operating on a file, the file needs to be closed. The
fclose() function is a function to close a file.
To call to the function to close a file is pointed to by a file pointer fptr as shown
below:
fclose(fptr);
The following program shows an example calling both the fopen() and
fclose() functions to open and close the file.
#include <stdio.h>
#include <stdlib.h>
exit(1);
}
:
:
fclose(fptr); /* file closed */
}
4.2.3 fprintf()
We can use the fprintf() function to print all types of data from a file. The
syntax to call the function is as follows:
Calls to the fprintf() function is nearly the same as calling the printf()
function. The difference with printf() is that it has an additional parameter; the
first parameter is a file pointer to some output file.
fclose(fptr);
}
ACTIVITY 4.2
Write a program that will input three integer numbers. Calculate the
average of these numbers. Write to a file named „average.dat‰, these
three numbers and the average. Execute your program several times,
so that the data in the average.dat file is written to every time you run
your program.
4.2.4 fscanf()
The fscanf() function can be used to read many types of data from a file. The
syntax to use the function is as follows:
We will see how the fscanf() function resembles the scanf() function; the
difference is in the fscanf() first parameter which is a file pointer to some input
file.
Example 4.2 below reads data from file data1 and displays the data on the screen.
The data that is contained in the file is the matric number as well as the grade for
a group of students.
Example 4.2: Read data from file and displays on the screen.
#include <stdio.h>
#include <stdlib.h>
After the file data1 has been successfully opened, the program will read the first
data in the file which is the total number of students. Based on the number of
students, the program will loop to read the matric number and the grade for each
student. An example of the file data1 that is appropriate to the program is given
below:
File: data1
10
1101 C
1102 E
1202 A
1203 B
1302 B
1305 C
1306 D
1401 C
1402 B
1500 C
Copyright © Open University Malaysia (OUM)
TOPIC 4 FILES 59
The first line in file data1 has the total number of students, which is 10. Each line
after that has data for each student, which is the matric number, followed by the
grade. The output generated by the program for the data file is given below:
If the fscanf() function reaches the end of the file while reading, it will return
an EOF value. This value can be used as a sentinel value while reading data from
a file.
ACTIVITY 4.3
ACTIVITY 4.4
Write a C program that will read lowercaseletter.txt file and write to a
new file uppercase.txt after changing each character in the file
lowercaseletter to capital letters.
SELF-CHECK 4.1
1. Assume that the program below is kept in a file atur1.c. Write the
output that will be produced by the program if the file that is
opened is the program file itself.
#include <stdio.h>
void main(void)
FILE *fptr;
char aks;
fptr = fopen(“atur1.c”, “r”)
if (fptr == NULL) {
printf(“Error opening atur1.c\n”)
exit(1);
}
while (1) {
aks = getc(fptr)
if (aks == EOF
break;
if (‘a’ <= aks && aks <= ‘z’
aks = ‘A’+(aks - ‘a’);
printf(“%c”, aks)
}
fclose(fptr)
}
}
fscanf(fptr, “%d”, &bil);
for (i=0; i < num; i++)
display(i,num);
fclose(fptr)
}
void display(int length, int height) {
int i, j
for (i=0; i < height; i++) {
for (j=0; j < height; j++
printf(“*”);
printf(“\n”);
}
}
Write the output that will be generated if the contents of input file
is as this: 3
Ć In this topic, you have learnt how to do file input and output in C. In
particular, we have learnt how to open and close files, read data from files as
well as writing to files.
Ć We have seen the usage of some library functions that are relevant which are
fopen(), fclose(), fprintf(), and fscanf().
fclose() NULL
fopen() Pointer
fprintf()
Random
fscanf()
Sequential
Appendix
Nowadays, there are lots of IDEs for C programming available either as:
(a) Freeware;
(b) Open source software; or
(c) Commercial software.
You may be wondering why the list contains C++. Can they run C language?
Yes! These IDEs are built to run both C and C++ languages. You just need to
know the correct way to save it before you compile and run your respective C
programs.
For this course, we are going to use Orwell Dev-C++ (by Orwell). Actually, this
IDE is a modified version from Bloodshed Dev-C++. Take a look at the following
steps on how to download, install and use Orwell Dev-C++.
Before you start writing a C program, click on the new file icon 1 and
Once the New Source File is loaded on the screen, choose menu File > Save
As⁄ as shown in Figure 4.
Figure 4: Save as
In the Save As dialogue box, make sure of the following (refer to Figure
A.5):
When you save the file, the tab of the respective file will be renamed as
shown in the interface 6 in Figure 6. You may start writing your first C
program here 7 (refer to Figure 6). You are advised to write this main
block every time you start writing C program. By practicing this method,
you will not miss any codes especially the opening and closing braces.
After you finish writing the codes, press the Compile button 8 (refer to
You need to see the bottom part of the Windows, whether you get any
there is any error, double click on each error listed to see the respective line
of code that contains the error. Find solutions to fix it. If there is no error,
the compilation is indicated as successful.
10
If the program is successfully compiled, press the Run button or
11
press F10 to run and get the output of the program as shown in
Figure 9.
IDE in Linux
If you are working on the Linux platform, you can use Geany as an application to
write, compile and run C program. How to get and install it? In this tutorial, we
use Ubuntu as the most popular and easiest Linux distribution. For your
information, any Linux platforms come with pre-installed C compiler called
GNU Compiler Collection (GCC), so you do not have to worry about C compiler
anymore. Geany is an editor to be used to write C codes, but it has an ability to
compile and run C program because of the integration with GCC.
To get Geany, you can open the Ubuntu Software Center and search for Geany
(refer to Figure 10). Later, you can press the Install button and let the system
install it for you. Additional plugin called g++ also need to be installed. You just
need to search „g++‰, find and install it through the Ubuntu Software Centre.
After the installation is completed, press the Window button on the keyboard
and type „Geany‰. Click on the icon to fire up Geany (refer to Figure 11).
Before you start writing codes in Geany, we need to do a little change in the
Preference menu. Kindly go to Edit > Preference menu and set the output of the
program must be shown in gnome-terminal. You just need to replace the value
inside the dialog box with „gnome-terminal‰ (refer to Figure 12).
Figure 12: Replace the value inside the dialog box with „gnome-terminal‰
Once completed, you can proceed with your programming codes as follows
(refer to Figure 13):
(a) To begin the C program, click on File > Save As⁄;
(b) Select a folder to save the file;
(c) Write the file name together with the extension of .c (for example,
HelloWorld.c); and
(d) Press the Save button.
After completing the codes, you can do the following necessary steps in order to
accomplish your programming tasks:
5
(a) To compile program: Press this button (refer to Figure 14);
6
(b) To run program: Press this button (refer to Figure 14); and
Figure 14: Write your program, compile and run in the editor
Okay, you are done with IDE, not for Windows platform only, but also for Linux
platform. Enjoy your learning and always remember ă programming is fun!!
OR
Thank you.