Professional Documents
Culture Documents
CBCP2202 Comp Programming II Caug14 (RS) (M)
CBCP2202 Comp Programming II Caug14 (RS) (M)
CBCP2202
Computer Programming II
Kalaivani K. Radakrishnan
Topic 2 Repetition 23
2.1 while Statement 23
2.2 do-while Statement 27
2.3 for Statement 30
2.3.1 The Relationship between for and while 34
Statements
2.4 Controlling Loops 35
2.4.1 Endless Loop 36
2.4.2 while Loop Controlled by Condition 37
2.4.3 while Loop Controlled by Sentry 39
2.5 continue Statement 40
2.6 break Statement 41
2.7 Nested Loops 42
2.7.1 Tracing Nested Loops 42
2.8 Case Study 44
2.8.1 Problem 44
2.8.2 Analysis 45
2.8.3 Design 45
Summary 49
Key Terms 50
Topic 3 Functions 51
3.1 What are Functions? 52
3.2 Function Definition 53
3.3 Function Prototype 56
3.4 Function Calls 58
3.4.1 Functions without Returned Data Type and 59
without Parameters
3.4.2 Functions without Returned Data Type but 61
with Parameters
3.4.3 Functions with Returned Data Type and with 62
Parameters
3.5 Library Functions of C 64
3.6 Variable Scope 67
3.7 Recursion 75
3.8 Functions and Top Down Design 79
Summary 82
Key Terms 83
Topic 4 Files 84
4.1 File Support in C Programs 84
4.1.1 Binary File 85
4.1.2 Text File 85
4.2 File Operations 85
4.2.1 fopen() 85
4.2.2 fclose() 87
4.2.3 fprintf() 88
4.2.4 fscanf() 89
4.2.5 getc() 92
4.2.6 putc() 93
Summary 96
Key Terms 96
Appendix 97
INTRODUCTION
CBCP2202 Computer Programming II is an advanced course and a continuation
of CBCP2101 Computer 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 Bachelor 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.
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 practice 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.
X INTRODUCTION
In Topic 2 of CBCP2101, 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;
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;
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‰.
ACTIVITY 1.2
Write a C program to determine if a student passes the examination (A
student passes the examination if the score obtained is more or
equivalent to 50).
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, 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
Write a C program that will show different messages according to the
value of the waterÊs temperature:
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;
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
Discuss these questions:
(a) What would happen if the if statement does not have an
else?
(b) Explain the if-else statement syntax given below:
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
Weight
Height (m) bodyWeightIndex Output Message
(kg)
80.0 1.5
60.0 1.5
55.0 1.5
(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);
1.4.2 Analysis
To simulate this game, we will write a program that will allow a user (player 1) to
play with a computer (player 2). Both players can choose an integer 0, 1 or 2 that
will each represent paper, rock and scissors.
Representation Number
Paper 0
Rock 1
Scissors 2
As an example, let us say rand() returns 1694. The expression value (rand()
% 3) is 2. To ensure the rand() function creates a different number every time
the program is executed, we would use the following function call:
srand(time(NULL));
The time (NULL) function returns seconds calculation that has been lapsed since
1 January 1970 (UNIX systems date of birth). By passing this integer second
calculation (it will surely be different each time the time(NULL) function is called)
to the srand()function, will determine where the rand() function starts. Thus, the
value returned by the rand()function will always be different. Both the
rand()and srand() function prototypes is in the file stdlib.h whereas the
time()function prototype is in the time.h file. As a result, we need to insert the
preprocessor instruction #include <stdlib.h> and #include <time.h> in
the program. It is easier to decide the winner if we build the table below:
P Computer
l
0 1 2
a Legend:
0 T P C T = Tie
y
1 C T P P = Player wins
e C = Computer wins
r 2 P C T
T shows a tie result that will be obtained when the choices of the Player and the
Computer are the same. P shows the combination of choices by the Player and the
Computer that ends with the Player winning. T shows the combination of choices
by the Player and the Computer that ends with the Computer winning. Therefore,
we have seven conditions to show the game results message that is to be printed.
Input
Output
1.4.4 Design
Initial Algorithm
1. Start.
2. Display introductory message and instruction.
3. Input player choice as integer value.
4. Generate computer choice as integer value.
5. Do comparison to display player and computer choice in
text form.
6. Do comparison to determine the winner based on the player
and the computer choices and display the result.
7. End.
Steps 1, 2, 3 and 7 are simple and do not need any details. On the other hand,
steps 4, 5, and 6 need more details. Let us see the detailed steps as follows:
end_if_1
if_else if (computer == 1) start_if_2
5.3.2 Display “ROCK”.
end_if_2
if_else if (computer == 2) start_if_3
5.3.3 Display “SCISSORS”.
end_if_3
end_if_1
if_else if ( ((player == 0) && (computer ==
1))|| ((player == 1) && (computer == 2)) ||(player
== 2) && (computer == 0))) start_if_2
6.1.2 Display “YOU WIN!”.
end_if_2
if_else if ( ((computer == 0) && (player ==
1)) || ((computer == 1) && (player ==
2))||((computer == 2) && (player == 0)))
start_if_3
1.4.5 Implementation
Program 1.4
/* Paper, Rock and Scissors Game Program */
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
void main(){
int player, computer;
printf(“\n%s\n”, “***PAPER, ROCK, SCISSORS***\n In this
game you are given three choices:\n”);
printf(“Input your choice: “);
scanf(“%d”, &player);
srand(time(NULL));
computer = rand() % 3;
printf(“\n%15s %15s %15s\n”, “YOUR CHOICE”, “COMPUTER”,
“RESULT”);
printf(“%15s %15s %15s\n”, “===========”, “=========”,
=========”);
switch (player){
case 0: printf(“%15s “, “PAPER”);
break;
case 1: printf(“%15s “, “ROCK”);
break;
case 2: printf(“%15s “, “SCISSORS”);
break;
}
switch (computer){
case 0: printf(“%15s “, “PAPER”);
break;
case 1: printf(“%15s “, “ROCK”);
break;
case 2: printf(“%15s “, “SCISSORS”);
break;
}
if (player == computer)
printf(“%15s\n”, “DRAW”);
else if ( ((player == 0) && (computer == 1)) ||
((player == 1) && (computer == 2)) ||
((player == 2) && (computer == 0)) )
printf(“%15s\n”, “YOU WIN!”);
SELF-CHECK 1.3
By stating the Analysis, Data Requirements, Design and
Implementation, solve the following problem:
SELF-CHECK 1.4
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.
Ć The differences between these control structures are also given.
X 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. As 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
(a) Write a program that will display even numbers from 2 to 20.
(b) Write a program that will input positive numbers, which ends
when 0 is entered.
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.
total += num;
} while (num != 0);
printf(“Total of positive numbers entered : %d”, total);
}
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);
The for statement is to write loops in an easy format, but the number of loops
are to be known at the time of writing the program.
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 examples 2.1, 2.3 and 2.5, the outputs are the same, only
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
happens if a group of statements needs to be repeatedly executed? The way is to
combine the statements into a compound statement. The compound statement is
formed by surrounding the statements with the symbols { and }.
Consider Program 2.1 that will read 10 numbers and then output the total and
average.
Program 2.1
/* Input 10 numbers and then output the total and
average */
#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 belowusing for,
do-while or while loop:
*****
***
*
SELF-CHECK 2.3
1. What is the output generated by the following 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.
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
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,
(i) Sentry value is the value that is out of the boundary of valid data.
(ii) Loops like these are suitable to be used in situations where the number of
repetitions cannot be determined.
SELF-CHECK 2.4
Consider the program below:
scanf(“%d”, &data);
while (i != -1) {
printf(“%d “, data/5);
scanf(“%d”, &data);
}
1. What is the sentry data used in the code segment above?
2. What is the output generated by the code segment above if the
input data is 5, 10, 15, 20, -1?
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;
}
printf(“Total value = %d\n”, total);
printf(“n value = %d\n”, n);
}
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
Notice that the code segment has two for statements that are marked as A and
B. Statement B is part of the statement that is in the body of statement A. From
the heading of statement A, we know that the statement execution is done twice.
The same as statement B, the body will repeat five times.
Program 2.3
There are two for statements that are involved and are marked A and B.
Statement A will repeat its execution of body for every number set that needs
processing. For every repetition, the following items will be executed for every
number set:
(i) Input how many numbers will be input for that set.
(ii) Input every number in that set and at the same time update its totals.
(iii) Calculate the average for that set.
(iv) Output the average for that set.
Execution of step (ii) would surely need looping because for every set, the
numbers would be input one at a time.
SELF-CHECK 2.5
scanf(“%d”, &data);
for (row=1; row <= data; row++) {
for (col=1; col <= row; col++)
printf(“%d”, col);
printf(“\n”));
}
2.8.1 Problem
Many programs need input from users. Examples of programs that we have seen
so far will display a message when some data have been inputted. This message
will give the users an indication about the type or choice of input needed by the
program.
One technique of interaction between a program and its user is using the menu.
The menu is a list of items that can be selected by the user. Once the menu is
displayed, the program will wait for the user to input his or her choice. After the
user has chosen the item, the program will continue processing based on that
item.
The program will display a menu to get the type of conversion required. Once
that is done, it will ask the user for the input to be converted, do the calculation
and then display the result. After that, the program will display the menu again
and the process will continue until the user decides to stop the program.
2.8.2 Analysis
The following formula is used to do the conversions:
1 hour = 60 minutes
1 foot = 0.3048 metres
1 Celsius = (5/9) * (Fahrenheit ă 32)
2.8.3 Design
The menu to be displayed by the program is based on the selection listed in Table
14.1:
Users choose the type of conversion by entering the corresponding code. If the
user enters a 0, the program ends. If the user enters any value other than the code
numbers in Table 2.1 above, it will be ignored. The program will re-display the
menu and the user has to choose again.
Variable Explanation
Choice Users choice from the menu
Minutes Value of minutes input by the user
Hours Keeps the converted value from minutes to hours
Feet Value of feet input by the user
Metres Keeps the converted value from feet to metres
Fahrenheit Value of Fahrenheit input by the user
Celsius Keeps converted value from Fahrenheit to Celsius
1. Start
2. Do
2.1 Choose conversion type
2.2 IF (1 <= choice and choice <= 3) Start_IF
a. Do the conversion and display the result
End_IF
End_DO (choice != 4)
3. End
Notice how the second step involves a loop to repeat Steps 2.1 and 2.2 until the
user chooses to stop the program when the choice value is 4.
2.8.4 Implementation
Program 2.4 below is an example of a program to implement the design above.
Program 2.4
void main(void) {
int choice;
int min; /* minutes */
float hr; /* hours */
float ft; /* feet */
float mtr; /* metres */
float fahr; /* fahrenheit */
float celc; /* celsius */
do {
/* display menu */
printf(“\n\t\tCONVERTER\n”);
printf(“\t\t==================\n”);
printf(“\t1. Time: minutes to hours\n”); printf(“\t2.
Distance: feet to metres\n”);
printf(“\t3.Temperature: Fahrenheit to Celsius\n”);
printf(“\t4. Program End\n”);
printf(“\tYour Choice: “);
scanf(“%d”, &choice);
if (1 <= choice && choice <= 3) {
switch (choice) {
case 1 :
printf(“Time in minutes: “);
scanf(“%d”, &min);
hr = (float) min / 60;
printf(“%d minutes = %.2f hours\n”,min,hr);
break;
case 2 :
Copyright © Open University Malaysia (OUM)
TOPIC 2 REPETITION W 49
case 3 :
printf(“Temperature in Fahrenheit: “);
scanf(“%f”, &fahr);
celc = (5.0/9.0) * (fahr - 32);
printf(“%.2f Fahr = %.2f Celcius\n”,fahr, celc);
break;
}
}
} while (choice != 4);
}
SELF-CHECK 2.6
Modify Program 2.4 so that an error message would be displayed if
the user does not enter the correct code during menu selection.
• 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.
(a) Controlling loops can be done either through controlled condition or
controlled by sentry value. Endless loop must be avoided.
(b) Nested loops are useful in generating loop statement within another
loop statement.
break Logical
continue Relational
Counter Repetition
do-while Statement
for while
X 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 called
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
Write a C program that will add two floating point numbers in a
function called addition and the total is returned and displayed from
the main function.
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 prove 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)
{
int number = 10;
print_message (number);
}
ACTIVITY 3.3
Correct the errors in the program below, so that no syntax error is
reported.
#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;
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
Write a C program that will:
(a) Get an integer number from a function called numberinput.
The programme will exit when a 0 is entered.
(b) Use a function named NumberToText that will receive an
integer number from 1 to 10 only and display it in Text.
ACTIVITY 3.6
1. Write two standard function names that you normally use.
2. What are some advantages of using standard C functions?
SELF-CHECK 3.1
What is the value returned by the function for the calls below:
(a) calcPay(35, 120)
(b) calcPay(50, 100)
Look at the program below. Variable x and y defined in the main() function is a
local variable. This means that it can only be reached directly through that
function. This variable cannot be reached directly in the function f1().
The next program declares both variables x and y as global variables. Thus, it can
be reached in any of the functions in the program.
#include <stdio.h>
int x, y; /* pembolehubah sejagat */
void f1(void) {
printf(“x = %d y = %d\n”, x, y);
}
void main(void) {
printf(“Include two numbers: “);
scanf(“%d%d”, &x, &y);
f1();
}
Program 3.1
#include <stdio.h>
void calcSquare(float a, float b) {
/*a and b are calSquare()’s local variables*/
b = a * a;
}
void main(void) {
float x, y; /*main() function’s local variables */
x = 3;
y = 20;
calcSquare(x,y);
printf(“%1.1f square is %2.1f\n”, x, y);
}
Notice that x and y are local variables for the function main(), whereas a and b
are local variables in the calcSquare() function. When the program starts to
execute, the main()function becomes active and the local variables x and y are
created. Figure 3.5 below shows the state of the variables before calling the
calcSquare() function.
When the function calcSquare() is called, the memory space for variables a
and b is created. After that, the values x and y are sent to the function with the
respective values copied into parameters a and b. The program control is later
transferred to the calcSquare() function. Memory space that is created when
the function is called is shown in Figure 3.6.
Let us look at the box above that represents the memory area for the entire
program. The box labelled as main shows the memory area for the function
main(). The memory of local variables for the function x and y are created from
this memory area.
Two small boxes labelled x and y represent memory for both the variables. Just
like the main() function, a labelled box represents memory space for the
calcSquare() function. Two small boxes labelled a and b in the box represent
memory area for local variables which are parameters a and b. Notice that the
values of a and b each represent values x and y. This is because of parameter
passing that happens when the function calcSquare() is called.
Next, the statement in the calcSquare() function body is executed that makes
the value of the expression a * a is assigned to b. The result, value of b is now
9, as shown in Figure 3.7.
The program output above shows that the execution of the program is not what
we had hoped. From the output, we found that the value of b did not change
after the call to calcSquare(). Even when the calcSquare() function does
the square calculation and keeps the value in b, the result of the calculation is not
assigned to y when returning from the function. This is why the value of y is still
the same before the call to the function.
#include <stdio.h>
double calcSquareArea(double width, double height)
double area; /*local variable */
area = width * height;
return area;
}
double calcCircleArea(double radius) {
double area; /*local variable */
area = 22.0/7 * radius * radius;
return area;
}
void main(void) {
double radius, l, t, area; /*local variables*/
printf(“Enter width and height: “);
scanf(“%f%f”, &l, &t);
area = calcSquareAread(l, t);
printf(“Square Area: %lf”, area);
printf(“Enter radius: “);
scanf(“%f”, &radius)
area = calcCircleArea(radius);
printf(“Circle Area: %lf”, area);
}
Notice that the name area was used to name three local variables, that were
declared in the main() function, calcSquareArea() and calcCircleArea().
Similarly with the radius, it is used to name a variable in the main() function
and another variable in the calcCircleArea().
In the program code above, every reference to the variable is matched to the
variable declaration. As an example, consider the statement area = 22.0/7 *
radius * radius; in the calcCircleArea() function. Radius referred to in
the statement is to the local variable radius in the function and not the variable
radius in the main()function.
C does not allow us to declare more than one local variable with the same name.
Nevertheless, we can declare a local variable that has the same name as a global
variable.
#include <stdio.h>
int x, y; /* x and y are global variables */
void f1() {
int x;
x = 0; /* local variables */
y = 0;
}
void main(void) {
x = 10;
y = 15;
f1();
printf(“x = %d y = %d\n”, x, y);
}
In this program, two global variables are declared as x and y. Function f1()
also declares a local variable by the name x. The arrow at the statement x = 0;
in function f1() shows that the reference to x in the statement is referring to the
local variable x and not the global variable x.
With that, the value of the global variable x does not change when the function
f1() is called in the main() function. On the other hand, f1()function has
changed the local variable y to 0. The output generated by the program is as
follows:
x = 10 y = 0
ACTIVITY 3.7
SELF-CHECK 3.2
#include <stdio.h>
int A(int x) {
printf(“Value received by A(): %d\n”, x);
x = x*x;
printf(“Value returned by A(): %d\n”, x);
return x;
}
void main(void) {
int x;
x = 10;
printf(“Value of x in main() before sent to
A(): %d\n”, x);
A(x);
printf(“Value of x in main() after returning from
A():
%d\n”, x);
}
ACTIVITY 3.8
3.7 RECURSION
If n is a round number, then the value of its factorial written as n! is determined
by the following formula:
1, if n = 0
n! =
n*(n-1)*...*2*1, if n > 0
The formula to calculate the factorial value for n (if n > 0) is as follows:
Notice that (n-1)*(n-2)*...*1 is the value for the factorial (n-1). In other words,
The diagram below shows the calculation of the value for factorial 4 based on the
observation above. To calculate the value of factorial 4, we would need to get the
value of factorial 3. Likewise, to calculate the value for factorial 3, we would
need to get the value of factorial 2. This continues until the value of factorial 0 is
needed to calculate factorial 1. Case 0! is a special case because the formula
above cannot be used for value of n which is equivalent to 0. For this case, the
factorial value of 0 is defined as 1.
4! = 4 * 3!
= 4 * (3 * 2!)
= 4 * (3 * (2 * 1!))
= 4 * (3 * (2 * (1 * 0!)))
= 4 * (3 * (2 * (1 * 1)))
= 4 * (3 * (2 * 1))
= 4 * (3 * 2)
= 4 * 6
= 24
Based on the above, the formula to calculate the value of a factorial for a round
number n is shown below:
1, if n = 0
n! =
n*(n-1)!, if n > 0
We can write a function to calculate the value of a factorial based on this formula.
Notice the function factorial() code on the next page:
int factorial(int n) {
if (n == 0)
return 1;
else
return n * factorial(n-1);
}
The following Program 3.2 inputs a number between 0 and 15 and continuously
calls the function factorial() to calculate its factorial value for that number
recursively.
Program 3.2
/* Counting factorial value of n recursively */
#include <stdio.h>
void main(void) {
int n;
long int factorial(int);
printf(“Enter value n “);
scanf(“%d”, &n);
if ((n < 0) || (n > 15))
printf(“n is outside range\n”)
else
printf(“%d! = %ld\n”, n, factorial(n));
}
long int factorial(int n) {
if (n == 0)
return 1; /* stopping condition */
else
return (n * factorial(n-1));/* recursion */
}
Two things must be taken into consideration when we write recursive function
definition; both are regarding the stopping of the function. The first is there
should be a condition to stop the function. Once the condition is satisfied, the
function should not call itself. This is because as long as the function calls itself,
the execution will not end. This situation is called endless recursion. This is
shown by the following function definition:
void forever(void) {
printf(“I will not end\n”);
forever();
}
Refer to the recursive function factorial() that we saw earlier. The condition to
stop is when the value of its parameter is zero, which is n = = 0 . When this condition
is met, the function will immediately return the value 1 to its caller. The Figure 3.9
below shows the role of the condition in the execution of factorial(4).
The second is to ensure that for every call towards the recursive function, the
condition to stop has to be fulfilled at last. Consider the function printLines()
definition below:
void printLines(int i) {
if (i <= 0)
return;
else {
printf(“*”);
printLines(i-1);
}
}
This function will display recursively one line of ‘*’ whose length is determined
by its parameter. For example, if we call printLines(10), ten ‘*’ characters
will be displayed on one line.
Consider the else part which contains the call to itself. The parameter that is
passed is i-1. This means that every time the function calls itself, the parameter
passed will decrease by 1. This is so that the final call will be printLines(0)
and this will ensure that the stopping condition is fulfilled. Notice that the
stopping condition for the function is i <= 0 and not i == 0. This is to ensure
that the function will end even when the parameter received is a negative value.
ACTIVITY 3.9
SELF-CHECK 3.3
#include <stdio.h>
long int prod(int lgt) {
if (lgt <= 0)
return (long int) -1;
else if (lgt == 1)
return (long int) 1;
else
return 10*prod(lgt-1) + 1;
}
void main(void) {
printf(“prod(-2): %ld\n”, prod(-2));
printf(“prod(0): %ld\n”, prod(0));
printf(“prod(1): %ld\n”, prod(1));
printf(“prod(8): %ld\n”, prod(8));
}
Notice that the stick-woman is made up of an oval, a triangle and two lines
joined at an angle. Therefore, the problem of drawing a stick-woman can be
broken into three sub-problems.
Beginning Algorithm:
1. Draw Oval
2. Draw Triangle
3. Draw Two Lines Joined at an Angle
Refining Step 2:
2. Draw Triangle
2.1. Draw Two Lines Joined at an Angle
2.2. Draw Horizontal Line
At this level, any sub-problem introduced can be solved easily. We can build a
structure chart like the one shown in Figure 3.11 that shows the original problem
and sub-problems and the relationship between them.
Program 3.3
/* Drawing Stick-Woman */
#include <stdio.h>
void draw_oval(void);
void draw_joinedLine(void)
void draw_horizontalLine(void);
void draw_triangle(void)
void main(void) {
draw_oval();
draw_triangle();
draw_joinedLine ();
}
void draw_oval(void) {
printf(“ ** \n”);
printf(“ * * \n”);
printf(“ * * \n”);
}
void draw_triangle(void) {
draw_joinedLine();
draw_horizontalLine();
}
void draw_joinedLine(void) {
printf(“ /\\\n”);
printf(“ / \\\n”);
printf(“/ \\\n”);
}
void draw_horizontalLine(void) {
printf(“———\n”);
}
Ć 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.
X 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.
Copyright © Open University Malaysia (OUM)
TOPIC 4 FILES W 85
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:
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
1. Write a code segment to open an existing file, named student.txt,
for reading and writing.
2. What are the statements that need to be inserted into a program to
test if the file to be opened exists in the system or not?
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>
}
:
:
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>
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 W 91
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.
4.2.5 getc()
The getc()function can be used to read a character from a file. The prototype of
this function is as follows:
getc(FILE *ptr);
The ptr is a pointer that the file will read. The getc()function would return the
character that was read from the file. If the function returns an EOF value, this
means the end of the file has been reached.
Program 4.1 aims to show the contents of a file to the screen. It uses the getc()
function to read the next character from the file and the putchar() function is
to display the character on the screen. This process continues until the getc()
function reaches the end of the file.
Program 4.1
#include <stdio.h>
#include <stdlib.h>
void main (void) {
FILE *fptr;
char nfile[20]
char letter;
}
do {
letter = getc(fptr);
if (letter == EOF)
break;
putchar(letter);
} while (1);
fclose(fptr);
}
4.2.6 putc()
We can use the putc() function to print a character to a file. Below is the
prototype for this function:
aks is a character that will be the output; whereas ptr is a pointer to the output file.
Program 4.2 below uses the putc()function to copy the contents of an input file
to another output file.
Program 4.2
#include <stdio.h>
#include <stdlib.h>
void main (void) {
FILE *f_input, *f_output
char input_name[20];
char output_name[20];
char letter;
printf(“Enter input file name: “);
gets(input_name);
f_input = fopen(input_name, “r”);
if (f_input == NULL) {
printf(“Error in opening file %s\n”,
input_name);
exit(1);
}
printf(“Enter output file name: “);
gets(output_name);
f_output = fopen(output_name, “w”);
if (f_output == NULL) {
printf(“Error to open file %s\n”,
output_name);
exit(1);
}
printf(“\nCopying File %s to file %s\n”,
input_name, output_name);
ACTIVITY 4.5
So far, you have learnt a few instructions in this topic. Can you state the
use of each instruction listed below?
Instruction Usage
1. fopen()
2. fclose()
3. fprintf()
4. fscanf()
5. getc
6. putc
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)
}
2. Consider the program code below:
#include <stdio.h>
#include <stdlib.h>
void main(void)
FILE *fptr;
int length, height, num, i;
fptr = fopen(“input”, “r”);
if (fptr == NULL) {
printf(“Numbers File cannot be opened.”)
exit(1);
}
fscanf(fptr, “%d”, &bil);
for (i=0; i < num; i++)
display(i,num);
fclose(fptr)
}
Write the output that will be generated if the contents of input file
is as this: 3
3. Write a program that would read every positive integer number
from a file named number and then outputs the average on the
screen.
4. Modify the program in (3) so that the average output is to a file
named output.
Ć 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
fprintf() Pointer
fscanf() Random
fopen() 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++.
Choose this
option to
download
the 64-bit
version
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.
6
7
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.
10
11
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.
1
3
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
5 6
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.