Progamming 2 Revision
Progamming 2 Revision
COMPUTER
PROGRAMMING
II
LECTURE NOTES
These lecture notes are prepared by İbrahim ERŞAN for a second year
engineering course Computer Programming II (with course code ENG203) in
Computer Engineering Department, Faculty of Engineering, Girne American
University,
Lecture notes are divided into eight sections and course will be followed
according to the order of these sections.
Students who are taking this course or following this document are strongly
recommended to write the given codes using any desired C++ compiler and
execute them, in order to learn and understand the subjects well.
Special thanks to Ms. Dilay Gök (she was one of my dedicated students in this
course) for her participation in typing phase of some sections of this document.
i
Table of Contents
Unbundled Bundled
Page Page
0. Computer Programming I - Revision 0.1/5 1
Loops 0.1/5 1
If - Statements 0.2/5 2
Arrays 0.3/5 3
Revision Practices 0.5/5 5
I. Two Dimensional Arrays 1.1/16 6
Matrix Definition 1.1/16 6
Matrix Generation 1.4/16 9
Matrix Multiplication and Addition 1.6/16 11
Exercises and Solutions on Matrix Generation 1.14/16 19
Exercises for you to try 1.16/16 21
II. Strings 2.1/10 22
Entering a String from Keyboard 2.2/10 23
Entering String in Initialization 2.3/10 24
String Processing Functions 2.3/10 24
String Conversion Functions 2.9/10 30
III. Structures 3.1/4 32
How to Define and Access 3.1/4 32
IV. Introduction to Functions 4.1/6 36
Function Declaration and Function Definition 4.2/6 37
Parameter Passing (Pass by Value) 4.4/6 39
V. Parameters in Functions 5.1/7 42
User Defined Structure as Parameter 5.1/7 42
Pass by Value vs Pass by Reference 5.3/7 44
Pass by Reference 5.4/7 45
Passing Arrays as Parameters 5.6/7 47
Global Variables 5.7/7 48
VI. Function Examples 6.1/5 49
Example: Passing Array as Parameter 6.1/5 49
Example: Taking Power of a Number 6.2/5 50
Example: Swap Integers and Character Arrays 6.3/5 51
Example: Global Matrix Processing Functions 6.4/5 52
Example: String Processing Functions 6.5/5 53
ii
VII. Files 7.1/20 54
Why we are using files & How files are stored? 7.1/20 54
Basic Steps 7.2/20 55
Writing to a File 7.3/20 56
Reading from a File 7.8/20 61
Important Detail about Reading Data from File 7.9/20 62
Finding the End of File (EOF & NULL) 7.12/20 65
Line Break Issue 7.14/20 67
Moving in a File with fseek statement 7.16/20 69
Current Position is a File with ftell statement 7.17/20 70
File Management 7.18/20 71
Check Existence or Accessibility of a File 7.18/20 71
Change name of a File with rename statement 7.19/20 72
Delete a File with remove statement 7.19/20 72
Appendix of Files Lecture Set 7.20/20 73
iii
ENG203 – Computer Programming II Prepared by Assoc.Prof.Dr. İbrahim ERŞAN
ENG203
COMPUTER PROGRAMMING II
As we all know, this course is the continuation of Computer Programming I (ENG102) course.
Without knowing the main topics of ENG102, it will not be possible to continue with this course. There
are some study questions related with ENG 102. Please try to solve them yourself and check your
solutions by comparing given answers. If you are not able to solve these questions at all, please study
your ENG102 lecture notes because you’ll have difficulties about understanding the subjects of this
course without enough knowledge about ENG102. The main subjects covered in ENG102 that will be
prerequisites in this course are,
In the following questions almost all of these subject are tried to be mentioned. With enough ENG102
knowledge all of them can be solved easily. If you have any missing or uncomplete subjects about
ENG102, please try to complete as soon as possible.
Loops - Question 1:
X
XX
XXX
XXXX
Answer 1:
#include <stdio.h>
int main()
{
int x,y;
for (x=0; x<4; x++)
{
for (y=0; y<=x; y++)
printf("X");
printf("\n");
}
return(0);
}
0. 1/5
ENG203 – Computer Programming II Prepared by Assoc.Prof.Dr. İbrahim ERŞAN
If Statements Answer 3:
Question3: #include <stdio.h>
int main()
Write a program that, if {
‘1’ is entered from int i,n,sum;
keyboard computer will printf("Please enter 1 for odd 2 for even:");
add up odd numbers scanf("%d",&n);
between 0 and 101 if ((n<1)||(n>2))
(0&101 is included) and printf("Wrong Entry");
will add up even else
numbers if ’2’ is {
sum=0;
entered. If any number
for(i=0; i<=101; i++)
is entered other than 1 {
or 2, then computer will if ((n==1) && ((i%2)!=0))
warn user. sum+=i;
if ((n==2) && ((i%2)==0))
sum+=i;
}
printf("Result :%d",sum);
}
return(0);
}
0. 2/5
ENG203 – Computer Programming II Prepared by Assoc.Prof.Dr. İbrahim ERŞAN
Arrays - Question 4:
Answer 4:
#include <stdio.h>
Write a C program, int main()
{
i. To find, print on screen and store in int n,i,arr[12];
an array, multiplication-table for any float ave;
given number N. Multiplication-table i=1;
will range from 1 to 12 and this section printf("Enter Number : ");
will be done using do-while loop (N will scanf("%d",&n);
be entered from keyboard). do
{
ii. Finally, find the average of stored printf("%dx%d=%d\n",n,i,n*i);
arr[i-1]=n*i;
values (of array) using for loop and
i++;
print average on screen.
}
while (i<=12);
ave=0;
for (i=0; i<12; i++)
ave+=arr[i];
printf("Average : %f",ave/12);
return(0);
}
OUTPUT of QUESTION 4
0. 3/5
ENG203 – Computer Programming II Prepared by Assoc.Prof.Dr. İbrahim ERŞAN
Arrays - Question 5:
Write a C program to do the following tasks (All tasks will be done in one program),
i. Two integer arrays (arrx and arry) with 10 locations will be created.
iii. All numbers in arrx will be copied to arry in reverse order (i.e. number in arrx will be copied to
location in arry, number in arrx will be copied to location in arry, and so on.)
Answer 5:
#include <stdio.h>
int main()
{
int i,arrx[10],arry[10],max;
for (i=0; i<=9; i++)
scanf("%d",&arrx[i]);
for (i=0; i<=9; i++)
arry[9-i]=arrx[i];
max=arrx[0];
for (i=0; i<=9; i++)
if (arrx[i]>max) max=arrx[i];
for (i=0; i<=9; i++)
if (arry[i]==max) printf("Location :%d\n",i);
return(0);
}
OUTPUT of QUESTION 5
0. 4/5
ENG203 – Computer Programming II Prepared by Assoc.Prof.Dr. İbrahim ERŞAN
Revision Practices:
3. Write a program to enter 5 number from keyboard into an array and find
i. minimum
ii. maximum
iii. average of these numbers, then print on screen.
0. 5/5
ENG203 – Computer Programming II Prepared by Assoc.Prof.Dr. İbrahim ERŞAN
ENG203
COMPUTER PROGRAMMING II
Matrix Definition
One dimensional array can be thought as a field of data. Two dimensional array can be
thought as a ‘matrix’.
Example 1: Define a 3x3 array and enter an integer value for each location of array from
keyboard, then write these values on screen in a matrix form.
Answer 1:
#include <stdio.h>
int main()
{
int r,c,arr[3][3];
for (r=0; r<3; r++)
for (c=0; c<3; c++)
scanf("%d",&arr[r][c]);
for (r=0; r<3; r++)
{
for (c=0; c<3; c++)
printf("%3d",arr[r][c]);
printf("\n");
}
return(0);
}
OUTPUT:
1
2
3
4
5
6
7
8
9
_ _ _1_ _ _2_ _ _3
4 5 6
7 8 9
1. 1/16
ENG203 – Computer Programming II Prepared by Assoc.Prof.Dr. İbrahim ERŞAN
Example 2: Define a 3x3 array and assign values 1,2,3,4,5,6,7,8 & 9 to that array using initializer
list. Print content of the two dimensional array on screen in matrix form.
Answer 2:
#include <stdio.h>
int main()
{
int r,c,arr[3][3]={1,2,3,4,5,6,7,8,9};
for (r=0; r<3; r++)
{
for (c=0; c<3; c++)
printf("%2d",arr[r][c]);
printf("\n");
}
return(0);
}
OUTPUT:
_ _1_ _2_ _3
4 5 6
7 8 9
Example 3: Continue with the previous example and print transpose of defined matrix.
Note:
Answer 3:
In order to print transpose, following code will be added to the previous code.
1. 2/16
ENG203 – Computer Programming II Prepared by Assoc.Prof.Dr. İbrahim ERŞAN
Answer 4:
#include <stdio.h>
int main()
{
int min,max,r,c,arr[3][5],i;
float ave;
for (r=0; r<3; r++)
for (c=0; c<5; c++)
{
printf("Enter value %d,%d: ",r,c);
scanf("%d",&arr[r][c]);
}
for (r=0; r<3; r++)
{
for (c=0; c<5; c++)
printf("%4d",arr[r][c]);
printf("\n");
}
min=arr[0][0];
max=arr[0][0];
ave=0;
i=0;
for (r=0; r<3; r++)
for (c=0; c<5; c++)
{
if (arr[r][c]>max) max=arr[r][c];
if (arr[r][c]<min) min=arr[r][c];
if (arr[r][c]%2==1)
{
ave+=arr[r][c];
i++;
}
}
printf("Maximum =%d\n",max);
printf("Minimum =%d\n",min);
if(i!=0)
printf("Average =%f\n",ave/i);
return(0);
}
1. 3/16
ENG203 – Computer Programming II Prepared by Assoc.Prof.Dr. İbrahim ERŞAN
Matrix Generation
If elements of a matrix have a relation between them or they are located in a hormony
then it is possible to generate them without entering one by one or reading from a file. Let’s
illustrate it with an example:
Answer 1:
As can be seen there is a relation
#include <stdio.h> between elements of our output
int main() matrix. First row starts with one and
{ as row number increases element
int c,r,a[3][3]; values also increases by 1.
for(r=0; r<=2; r++)
{ There is no need to change entire
for(c=0; c<=2; c++)
code. Just by changing one line it will
{
a[r][c]=r; be possible to obtain this result.
}
}
for(r=0; r<=2; r++)
{
for(c=0; c<=2; c++)
{
printf("%3d",a[r][c]);
}
printf("\n");
}
return(0);
}
OUTPUT :
1. 4/16
ENG203 – Computer Programming II Prepared by Assoc.Prof.Dr. İbrahim ERŞAN
Example 2:
Let’s solve another example to understand it better. Now we’ll try to obtain a different output.
Again we have a relation but this time we may need conditional statements rather than
arithmetic statements to solve this example.
OUTPUT :
Answer 2:
#include <stdio.h>
int main()
{
int c,r,a[3][3];
for(r=0; r<=2; r++)
{
for(c=0; c<=2; c++)
{
if (r>c) a[r][c]=1; Most of the time modificating this
else if (r<c) a[r][c]=2; section will be enough to create
else a[r][c]=0; another matix BUT NOT all the time!
}
}
for(r=0; r<=2; r++)
{
for(c=0; c<=2; c++) Output in matrix form is same in all
{ examples. Just the boundaries of for
printf("%3d",a[r][c]); loops changes.
}
printf("\n");
}
return(0);
}
OUTPUT :
1. 5/16
ENG203 – Computer Programming II Prepared by Assoc.Prof.Dr. İbrahim ERŞAN
Let’s try to write a program which multiplicates a 3 elements vector (which can be denoted as a
1 by 3 matrix) with a 3 by 2 matrix. As we all know from the rules of matrix multiplication for
( x ) x ( x ), must be equal to . In our example its (1x3) x (3x2) so multiplication can
be done.
First we’ll enter the values of these matrices from keyboard then, we’ll multiply them and print
the result on screen in matrix form.
Answer 1:
#include <stdio.h>
int main()
{
int sum,c,r,y[3],z[3][2];
printf("Enter y(1x3)\n");
for (c=0; c<=2; c++)
{
printf("row%d col%d :",0,c);
scanf("%d",&y[c]);
}
printf("Enter z(3x2)\n");
for (r=0; r<=2; r++)
{
for (c=0; c<=1; c++)
{
printf("row%d col%d :",r,c);
scanf("%d",&z[r][c]);
}
}
printf("\nResult :\n");
for (r=0; r<=1; r++)
{
sum=0;
for (c=0; c<=2; c++)
{
sum=sum+(y[c]*z[c][r]);
}
printf("%3d",sum);
}
return(0);
}
1. 6/16
ENG203 – Computer Programming II Prepared by Assoc.Prof.Dr. İbrahim ERŞAN
0 y[0]=1
1 y[1]=2
2 y[2]=3
0 0 z[0][0]=1
1 0 z[0][1]=2
0 1 z[1][0]=1
1 1 z[1][1]=2
0 2 z[2][0]=1
1 2 z[2][1]=1
0 0 0
0+1=1
1+2=3 1 0
3+3=6 2 0
0 0 1
0+2=2
2+4=6 1 1
6+3=9 2 1
OUTPUT :
1. 7/16
ENG203 – Computer Programming II Prepared by Assoc.Prof.Dr. İbrahim ERŞAN
For this example, in order to ease process, well use predefined matrices. I mean, we’ll not
enter matrices from keyboard. So, let’s perform the operation on following matrices. We’ll first
initialize these matrices with an initializer list and then multiply them and directly print the
result on screen in matrix form.
3 4 1 2 3 19 26 33
2 1 x 4 5 6 = 6 9 12
2x2 2x3 2x3 This is the expected result
Answer 2:
#include <stdio.h>
int main()
{
int sum,c,r,x;
int y[2][2]={3,4,2,1};
int z[2][3]={1,2,3,4,5,6};
printf("Matrix y :\n");
for (r=0; r<=1; r++)
{
for (c=0; c<=1; c++)
{
printf("%3d",y[r][c]);
}
printf("\n");
}
printf("Matrix z :\n");
for (r=0; r<=1; r++)
{
for (c=0; c<=2; c++)
{
printf("%3d",z[r][c]);
}
printf("\n");
}
Program continues on next page, in this part of code we just initialize the matrices and print
the initialized matrices on screen in matrix form, on next page, two matrices will be multiplied
and also printed on screen in the same nested for-loop.
1. 8/16
ENG203 – Computer Programming II Prepared by Assoc.Prof.Dr. İbrahim ERŞAN
printf("\nResult of YxZ:\n");
for (x=0; x<=1; x++)
{
for (r=0; r<=2; r++)
{
sum=0;
for (c=0; c<=1; c++)
{
sum=sum+(y[x][c]*z[c][r]);
}
printf("%4d",sum);
}
printf("\n");
}
return(0);
}
0 0 0 0+3
1 0 0 3+16=19
0 1 0 0+6
1 1 0 6+20=26
0 2 0 0+9
1 2 0 9+24=33
0 0 1 0+2
1 0 1 2+4=6
0 1 1 0+4
1 1 1 4+5=9
0 2 1 0+6
1 2 1 6+6=12
OUTPUT :
1. 9/16
ENG203 – Computer Programming II Prepared by Assoc.Prof.Dr. İbrahim ERŞAN
1. 10/16
ENG203 – Computer Programming II Prepared by Assoc.Prof.Dr. İbrahim ERŞAN
Answer 4:
#include <stdio.h>
int main()
{
const int dims=99;
int r,c,x,sum,r1,c1,r2,c2;
int m1[dims][dims];
int m2[dims][dims];
int rs[dims][dims];
printf ("Please Enter Row Count of First Matrix (Less Than %d) :",dims+1);
scanf ("%d",&r1);
printf ("Please Enter Column Count of First Matrix (Less Than %d) :",dims+1);
scanf ("%d",&c1);
printf ("Please Enter Row Count of Second Matrix (Less Than %d) :",dims);
scanf ("%d",&r2);
printf ("Please Enter Column Count of Second Matrix (Less Than %d) :",dims);
scanf ("%d",&c2);
if ((r1>dims) || (r2>dims) || (c1>dims) || (c2>dims))
printf ("Row and Column Values must be less than %d",dims+1);
else if (r2!=c1)
printf ("Column count of First Matrix Must be equal to Row count of Second Matrix");
else
{
printf ("\nEnter Values of First Matrix (M1)\n");
for (r=0;r<r1;r++)
{
for (c=0;c<c1;c++)
{
printf("Matrix 1, Row %d, Column %d :",r,c);
scanf("%d",&m1[r][c]);
}
}
printf ("\nEnter Values of Second Matrix (M2)\n");
for (r=0;r<r2;r++)
{
for (c=0;c<c2;c++)
{
printf("Matrix 2, Row %d, Column %d :",r,c);
scanf("%d",&m2[r][c]);
}
}
printf ("\nResult of M1xM2=RS :\n");
for (x=0;x<r1;x++)
{
for (r=0;r<c2;r++)
{
sum=0;
for (c=0;c<c1;c++)
{
sum=sum+(m1[x][c]*m2[c][r]);
}
printf("%4d",sum);
rs[x][r]=sum;
}
printf("\n");
}
}
return(0);
}
1. 11/16
ENG203 – Computer Programming II Prepared by Assoc.Prof.Dr. İbrahim ERŞAN
It’s a good exercise to understand coding for matrices and writing reasonably large scale codes
for generalized usage. Notice, in software development bussiness, this much lines of code is not
accepted as ‘large scale’, here it is large scale if we compare it with our examples.
OUTPUT :
Now we can continue with another example that performs the same strategy with one
exception. It will NOT for matrix multiplicaiton BUT for matrix addition. In the following page
you can find the example question and its solution.
1. 12/16
ENG203 – Computer Programming II Prepared by Assoc.Prof.Dr. İbrahim ERŞAN
Example 5:
Write a program to add two matrices. Dimensions of these matrices will be entered from
keyboard BUT each dimension must not exceed 99x99. If one of dimensions exceeds 99,
program will warn user. Row and Column count of both matrices must be exactly same in order
to be able to add them. After defining dimensions, all values of both matrices will be entered
from keyboard one by one. Finally, program will add both matrices and print result on screen in
a matrix form.
Answer 5:
#include <stdio.h>
int main()
{
const int dims=99;
int r,c,r1,c1;
int m1[dims][dims];
int m2[dims][dims];
int rs[dims][dims];
printf (“Please Enter Row Count of Matrices (Less than %d): “,dims+1);
scanf(“%d”,&r1);
printf (“Please Enter Column Count of Matrices (Less than %d): “,dims+1);
scanf(“%d”,&c1);
if ((r1>dims)||(c1>dims))
printf (“Row and Column values must be less than %d”,dims+1);
else
{
printf (“\nEnter values of first matrix\n”);
for (r=0;r<r1;r++)
for (c=0;c<c1;c++)
{
printf (“Matrix 1, Row %d, Column %d:”,r,c);
scanf (“%d”,&m1[r][c]);
}
printf (“\nEnter values of second matrix\n”);
for (r=0;r<r1;r++)
for (c=0;c<c1;c++)
{
printf (“Matrix 2, Row %d, Column %d:”,r,c);
scanf (“%d”,&m2[r][c]);
}
printf (“\nResult of M1+M2=RS:\n”);
for (r=0;r<r1;r++)
{
for (c=0;c<c1;c++)
{
rs[r][c]=m1[r][c]+m2[r][c];
printf (“%5d”,rs[r][c]);
}
printf (“\n”);
}
}
return(0);
}
1. 13/16
ENG203 – Computer Programming II Prepared by Assoc.Prof.Dr. İbrahim ERŞAN
1 1 1 1 1 1 0
1 1 1 1 1 0 2
1 1 1 1 0 2 2
1 1 1 0 2 2 2
1 1 0 2 2 2 2
1 0 2 2 2 2 2
0 2 2 2 2 2 2
Answer 1:
#include <stdio.h>
int main()
{
int c,r,a[7][7];
for (r=0;r<=6;r++)
for (c=0;c<=6;c++)
{
if (c<(6-r)) a[r][c]=1;
else if (c>(6-r)) a[r][c]=2;
else a[r][c]=0;
}
for (r=0;r<=6;r++)
{
for (c=0;c<=6;c++)
printf (“%3d”,a[r][c]);
printf (“\n”);
}
return(0);
}
OUTPUT :
NOTICE: Instead of using for-loop, you can try to solve the same problem using While-Loop.
1. 14/16
ENG203 – Computer Programming II Prepared by Assoc.Prof.Dr. İbrahim ERŞAN
1 1 1 1 1 1 1
2 2 2 2 2 2 2
3 3 3 3 3 3 3
5 5 5 5 5 5 5
8 8 8 8 8 8 8
13 13 13 13 13 13 13
21 21 21 21 21 21 21
Answer 2:
#include <stdio.h>
int main()
{
int c,r,a[7][7];
for (r=0;r<=6;r++)
for (c=0;c<=6;c++)
{
if (r<2) a[r][c]=r+1;
else a[r][c]=a[r-1][0]+a[r-2][0];
}
for (r=0;r<=6;r++)
{
for (c=0;c<=6;c++)
printf ("%3d",a[r][c]);
printf ("\n");
}
return(0);
}
OUTPUT :
NOTICE: Instead of using for-loop, you can try to solve the same problem using While-Loop.
1. 15/16
ENG203 – Computer Programming II Prepared by Assoc.Prof.Dr. İbrahim ERŞAN
Generate following matrices, locate them in a two dimensional array and print the content of
created array on screen in matrix form.
1 0 3 0 5
0 2 0 4 0
1 0 3 0 5
0 2 0 4 0
1 0 3 0 5
0 0 0 0 0
0 1 2 3 4
0 2 4 6 8
0 3 6 9 12
0 4 8 12 16
1 2 3 4 5
5 4 3 2 1
1 2 3 4 5
5 4 3 2 1
1 2 3 4 5
5 5 5 5 5
4 4 4 4 4
3 3 3 3 3
2 2 2 2 2
1 1 1 1 1
1 2 3 4 5
6 7 8 9 10
11 12 13 14 15
16 17 18 19 20
21 22 23 24 25
1. 16/16
ENG203 – Computer Programming II Prepared by Assoc.Prof.Dr. İbrahim ERŞAN
ENG203
COMPUTER PROGRAMMING II
In C language there is no specific data type for strings. If we want to use strings, we have
to define an array of characters. In some libraries it is possible to find functions related with
strings but in basic library that we’re using (stdio.h), we don’t have such functions and
definitions. If we can perform string operations with a character array, what is the difference
between a string and a character array? There is only one difference. If we have a character
array, in order to be able to say that it is a string, it must finish with a string termination byte
(or character). So, at the end of all strings there is an invisible character which tells to the
computer that this is the end of string.
As far as computers are working with numbers only, each character is coded with a number
(each character is enumerated). These numbers are standard for all operating systems
(Windows, Linux, Android, IOS etc.). So there is a look-up table in BIOS of your PC, Laptop or
Smart Phone which keeps this table as standard. This table is called ASCII (American Standard
Code for Information Interchange) table and numbers given to the characters is called ASCII
codes. Each character is represented with a byte so each ASCII code reserves 1 byte space.
Some codes are visible (which we can see on our monitors) and some codes are not (which are
called control characters). String termination character is a control character so it’s not possible
to see it. As we cannot see these control characters, they have names related with the task that
they are doing. String termination character is named as NULL in ASCII table (first character of
table). You can find all ASCII codes in following table.
2. 1/10
ENG203 – Computer Programming II Prepared by Assoc.Prof.Dr. İbrahim ERŞAN
Now, with respect to the information given in previous page, we know that, strings are series of
characters which are kept in a character array and after the last character there is a termination
character. What happens when we enter a string from keyboard? Simply all characters that we
enter from the keyboard is located in a character array and automatically a termination
character is located at the end. So, if you are planning to keep maximum 15 characters in an
array, it will be appropriate to reserve 16 locations.
We can enter strings from keyboard in two ways, either using scanf or using gets. In fact
these are not the only functions that can be used but in this course we’ll use these two.
i. using scanf
NOTE : In scanf function for character
#include <stdio.h> arrays we are not using “&”
int main() (ampersand) sign before variable
{ name. This point is very important
char nm[40]; because & means “address of”. Scanf
printf("Enter your name :"); function uses the addresses of
scanf("%s",nm); variables (not their names), this
printf("Hello %s",nm); means that an array name (without
return(0);
index) gives us the address of very
}
first location of that array.
OUTPUT :
gets is only used to get strings from keyboard and puts is only used to print string on screen.
Any format (%d , %f etc.) cannot be applied in puts (there is no problem in using \n). Puts
automatically jumps to the next line after printing the content on screen.
2. 2/10
ENG203 – Computer Programming II Prepared by Assoc.Prof.Dr. İbrahim ERŞAN
#include <stdio.h>
int main()
{
char a[]="Programming";
char b[3]="is\0"; All three string assignments are same
char *c="Good";
OUTPUT :
Four string functions will be examined in this course. There are a lot of string functions
but these important ones are sufficient for now.
iv. strcat (string1,string2) : concatenates two strings in one. The process that will be
carried out can be depicted as string1=string1+string2
There are also two more functions which are not related with string processing BUT related
with conversions. These two functions will also be discussed.
2. 3/10
ENG203 – Computer Programming II Prepared by Assoc.Prof.Dr. İbrahim ERŞAN
Before solving examples, let’s try to understand strcmp() function first because others are easily
understandable but we need to know how this function works in order to be able to use it.
Let’s have a closer look by comparing two strings “broade” and “broaft”. In fact this function
just subtracts the ASCII values of second parameter from first parameter and returns the
difference of first occurrence of different characters (which the result will not be zero). If result
is zero in all subtractions then function returns zero.
b r o a f t
98 114 111 97 102 116
Let’s continue with examples related with string processing functions in order to understand
them better.
#include <stdio.h>
#include <string.h>
int main()
{
char nm[50];
printf ("Please enter your name :");
scanf ("%s",nm);
printf ("Number of characters in your name :%d",strlen(nm));
return(0);
}
OUTPUT
2. 4/10
ENG203 – Computer Programming II Prepared by Assoc.Prof.Dr. İbrahim ERŞAN
OUTPUT :
Please enter a string :TEST
Analysis Results
Address=1245016, Character=T, Code=84
Address=1245017, Character=E, Code=69
Address=1245018, Character=S, Code=83
Address=1245019, Character=T, Code=84
2. 5/10
ENG203 – Computer Programming II Prepared by Assoc.Prof.Dr. İbrahim ERŞAN
#include <stdio.h>
#include <string.h>
int main()
{
char nm[50];
int i,r,c;
printf ("Please enter a string :");
scanf ("%s",nm);
for (c=strlen(nm)-1;c>=0;c--)
{
printf ("%c",nm[c]);
}
return(0);
}
Before solving “strcpy” example please keep in your mind that, it is NOT possible to assign a
string value to a string array directly with assignment operator (=). Only in definition stage, it is
possible to locate a string value.
2. 6/10
ENG203 – Computer Programming II Prepared by Assoc.Prof.Dr. İbrahim ERŞAN
#include <stdio.h>
#include <string.h>
int main()
{
char defpas[]="teatime";
char pas[50];
puts ("Please Enter Password");
gets (pas);
if (strcmp(defpas,pas)==0)
puts ("CORRECT Password");
else
puts ("Access DENIED");
return(0);
}
2. 7/10
ENG203 – Computer Programming II Prepared by Assoc.Prof.Dr. İbrahim ERŞAN
OUTPUT
2. 8/10
ENG203 – Computer Programming II Prepared by Assoc.Prof.Dr. İbrahim ERŞAN
Example:
#include <stdio.h>
#include <stdlib.h>
int main()
{
char a[10];
printf("Please Enter a String : ");
scanf("%s",a);
printf("Integer Conversion : %d\n",atoi(a));
printf("Integer Conversion x 2: %d\n",atoi(a)*2);
printf("Integer Conversion / 2: %d\n",atoi(a)/2);
printf("Float Conversion : %f\n",atof(a));
printf("Float Conversion x 2 : %f\n",atof(a)*2);
printf("Float Conversion / 2 : %f",atof(a)/2);
return(0);
}
By using this example it is possible to understand the behaviour of function because we are also
performing simple arithmetic operations to understand the returned number exactly. It will be
better to run the code for 3 times. In the first run we’ll enter an integer, in the second run we’ll
enter a float and in the third run we’ll enter a non-numeric value to see the results in output.
OUTPUT :
2. 9/10
ENG203 – Computer Programming II Prepared by Assoc.Prof.Dr. İbrahim ERŞAN
Answer :
#include <stdio.h>
#include <string.h>
int main()
{
char s[50],a[50][50];
int r,c;
printf ("Enter a String :");
scanf ("%s",s);
for(r=0;r<strlen(s);r++)
for(c=0;c<strlen(s);c++)
if ((r%2)==1)
a[r][c]=s[strlen(s)-(c+1)];
else
a[r][c]=s[c];
for(r=0;r<strlen(s);r++)
{
for (c=0;c<strlen(s);c++)
printf("%c ",a[r][c]);
printf("\n");
}
return(0);
}
SAMPLE OUTPUTS
2. 10/10
ENG203 – Computer Programming II Prepared by Assoc.Prof.Dr. İbrahim ERŞAN
ENG203
COMPUTER PROGRAMMING II
A structure is a user defined data type in C/C++. A structure creates a data type that can be
used to group items of possibly different types into a single type.
In this example (above) the name of the new data type is mydata. This new type includes one
ineteger, one float, one character and one character array (with ten elements). So if we define
a new variable with data type mydata, all these variable types will be in the definition.
3. 1/4
ENG203 – Computer Programming II Prepared by Assoc.Prof.Dr. İbrahim ERŞAN
strcpy (worker.name,"Jack");
strcpy(worker.sname,"Daniels"); Instead of writing this section, we
worker.age=25; can assign values directly after
worker.gender='M'; defining variable.
worker.salary=1435.5;
OUTPUT :
3. 2/4
ENG203 – Computer Programming II Prepared by Assoc.Prof.Dr. İbrahim ERŞAN
3. 3/4
ENG203 – Computer Programming II Prepared by Assoc.Prof.Dr. İbrahim ERŞAN
#include <stdio.h>
int main()
{
struct person
{
char name[50];
float mark[3];
}; OUTPUT
person student[3],leader;
int k,r,p;
float ave,max=0;
printf("Enter Names and Marks\n");
for(r=0;r<3;r++)
{
printf("\nStudent %d Name :",r+1);
scanf("%s",student[r].name);
ave=0;
for(k=0;k<3;k++)
{
printf("Student %d Mark %d:",r+1,k+1);
scanf("%f",&student[r].mark[k]);
ave+=student[r].mark[k];
}
ave/=3;
if(max<ave)
{
max=ave;
p=r;
}
}
leader=student[p];
printf("\nLeader Name :%s",leader.name);
for(r=0;r<3;r++)
printf("\nLeader Mark %d:%.2f",r,leader.mark[r]);
return(0);
}
Again, we have a loop, to print all marks of the student having the greatest
average.
3. 4/4
ENG203 – Computer Programming II Prepared by Assoc.Prof.Dr. İbrahim ERŞAN
ENG203
COMPUTER PROGRAMMING II
Functions are sub-procedures which can be called from main procedure or other sub-
procedures. Advantages of using functions are:
1. Programmer can get rid of code repetitions. You may need to run same code section
more than one time. In that case instead of writing the same lines again and
reserving more space in RAM, it can be written in a function and called as much as
needed.
6. When a functionality is enhanced, there is no need to search the entire code and
apply the same enhancement. As we are calling the same function for the enhanced
functionality, in complete code all sections which uses that functionality will be
enhanced.
If we talk about the structure of C language, main() procedure is also a function itself but
main() function is a special function that execution of a C program always starts from this
function. Like mathematical functions it is possible to assign some variables to them and get a
result. In programming terminology assigning variables to a function is “sending parameters to
a function” and getting a result is “returning a value from function”. So, we can send
parameters to a function and depending on these parameters functions can return a value
back. In this topic we will discuss how to,
1. Declare a function
2. Define a function
3. Call a function
4. Send parameters to a function
5. Return values from a function
Notice: Examples are designed to teach you how to write functions. So, discussed functions
may not be very useful in a real application. In order to be able to write useful functions, first of
all we need to learn how to write functions.
4. 1/6
ENG203 – Computer Programming II Prepared by Assoc.Prof.Dr. İbrahim ERŞAN
It is said that execution always starts from main() function, so in your code, location of
your function code (function definition) is important. If you define a function after main()
function, it must be declared before the main() function. If you define a function before the
main() function then there is no need for function declaration. Declaring a function means, you
are telling to the C compiler that, there will be a function definition in the code after the main()
function.
The first thing that we need to write while declaring or defining a function is the data type that
will be returned from the function. For example, if the function returns an integer value then
we’ll start by writing int (this is also valid for other data types). If the function is NOT returning
any value back then we have to start with void.
Example: Write two functions, one of them will print “Hello” on screen and the other one will
print “World” on screen. The first function will be written before main() function and the
second one will be written after main() function. So, according to the definition, second
function needs a declaration before main() function. Both functions are not taking any
parameters and they are not returning any value back.
#include <stdio.h>
Both functions are not returning any value so we
void hf() define them as void.
{
printf("Hello\n"); We can give any name we want to our functions so
} for the first function we named it as hf and second
function as wf.
void wf();
Now we learn how to declare and how to define a function. What will happen if we need to
return a value from a function?
Example: Write two functions. The first one will print on screen a welcome message and it will
not return anything back. Name the first function as greeting. The second function which will
be named as askpas, will ask for a defined password and wait for a password entry. After
entering the password, the function will check if password entry is correct, if so it will return
integer value 1 and if password is NOT correct, it will return 0. Note that, the correct password
will be defined as “teatime”. Locate all of your functions after main function. In the main
function call greeting and askpas functions respectively then print a message on screen if the
entered password is correct or not (in order to be able to print this message on screen, you
need to check the returned value).
If you check the code
written for the function
#include <stdio.h> askpas, you can see that
#include <string.h> the statement that we are
Here, we’re calling the using to return a value
void greeting();
function and also checking if back is return(). Whatever
int askpas();
returned value is equal to 1. the value that we write
int main() inside the paranthesis of
{ return() statement (of
greeting(); course it must be integer
if (askpas()==1) because we designed it
printf("\nCorrect Password");
so), will be returned back
else
printf("\nPasswors is NOT Correct"); as result of function. The
return(0); other imporant point is
} that, when we reach to
return() statement
void greeting() function will exit back
{
printf("Wellcome to My Program\n"); (wherever the return is).
printf("This program is Password Protected!\n\n");
}
int askpas()
{
char ps[20];
printf("Please Enter Your Password :"); POSSIBLE
scanf("%s",ps); OUTPUTS_
if (strcmp(ps,"teatime")==0)
return(1);
else
return(0);
}
4. 3/6
ENG203 – Computer Programming II Prepared by Assoc.Prof.Dr. İbrahim ERŞAN
At this point we can declare, define and call a function. Also a function can return a value back
to wherever it is called. What is left about a function? How to send a parameter to it. We will
start with a very simple example to understand how it works, then we will continue with details
after understanding these basic points. Note that, without having a clear understanding about
these basics, it will not be possible to understand details that will be discussed later.
It is possible to send parameters to a function as much as we want and in any data type
we want. We need to define the data type that will be sent and also give a variable name to
these parameters inside the parenthesis of function. If we have more than one parameter to
send, these parameters must be separated with comma. In parenthesis it is written “Pass by
Value”. It is possible to send parameters to a function in two ways either with “Pass by Value”
or with “Pass by Reference”. In order to understand the difference we need to discuss “Pass by
Reference”, so it will be explained later.
Example: Write a simple function with name operate. This function will take three parameters.
First two parameters will be integers and third parameter will be a character. Function will
perform one of the four operations ( +, -, *, / ) on integers and print the result on screen. The
operation will be decided using third parameter. E.g. If the character is ‘+’ then it will add up
the numbers. In main function one character and then two integers will be taken from
keyboard and send to the function.
#include <stdio.h> This is how we declare parameters
void operate (int, int, char); of a function. Variable names are
NOT given in declaration.
int main()
{
int a,b;
char c;
printf("Enter Operation\n");
scanf("%c",&c);
printf("Enter First Value\n");
scanf("%d",&a);
printf("Enter Second Value\n");
scanf("%d",&b);
operate(a,b,c);
printf("\n%c operation done on %d & %d",c,a,b);
return(0); Typical OUTPUT
}
void operate (int x, int y, char z)
{
printf("Result :");
if(z=='+') printf("%d",x+y);
else if(z=='-') printf("%d",x-y);
else if(z=='*') printf("%d",x*y);
else if(z=='/') printf("%f",1.*x/y);
else printf("Invalid Operation");
}
Now let’s change our function a little bit and see what will be the result for exactly the same
numbers and same operation.
4. 4/6
ENG203 – Computer Programming II Prepared by Assoc.Prof.Dr. İbrahim ERŞAN
Example: Using same main function of the previous example, let’s change the operate function
as following and examine the output. Let’s use the same numbers in execution also. Are you
expecting any difference in result?
Example: In main function the variable names, that we are using, are a and b for integer, and c
for character. Using same main function of the previous example, let’s change the operate
function as following (and use variable names a, b and c instead of x, y and z respectively) and
examine the output. Let’s use the same numbers in execution also. Are you expecting any
difference in result?
There is a very important thing that we can learn from these examples, even we are using the
same variable names the variables that we are using inside operate function and variables that
we are using inside main function, are not affecting each other. When we change the value of a
variable in a function, this modification will not affect the variables outside of that function. So,
we can say that, lifetime of a variable in a function, depends on lifetime of that function. When
the function finishes all of the variables in that function will be removed from memory.
We will continue to discuss this point later, while we are examining ‘global variables’ and ‘pass
by reference’ subjects of functions topic.
Let’s overlearn the things that we learned in this section with a final function example which
both sends and receives parameter.
4. 5/6
ENG203 – Computer Programming II Prepared by Assoc.Prof.Dr. İbrahim ERŞAN
Example: Write a function that will take an integer value (let’s say x) and return an integer
value back. This function will find the factorial of x and return the result back.
In given question it is NOT asking for a main function. Question just asks for a function so there
is no need to write a complete program. Above solution finds the factorial of any parameter
which is send.
In order to check if our solution is working correctly, we can write a main function and test it as
shown below,
#include <stdio.h>
int main()
{
int k;
printf("Enter a positive integer value :");
scanf("%d",&k);
printf("Factorial of %d is %d",k,factorial(k));
return(0);
}
4. 6/6
ENG203 – Computer Programming II Prepared by Assoc.Prof.Dr. İbrahim ERŞAN
ENG203
COMPUTER PROGRAMMING II
It is possible to send and return structured data types as parameters. Also it is possible to
send arrays and memory addresses of variables as parameters. Now we’ll continue with
illustrative examples on parameter passing.
Example:
Define a structure with name “person”. In “person” structure it will be possible to keep name,
age and salary of an employee. Write two functions. One function (with name output) will
receive a variable in type of “person” and will print the content of variable on screen. The other
function (with name input) will ask name, age and salary of an employee that will be entered
from keyboard and locate this information in a “person” variable then return it back. main
function will call input function first, to get the information about an employee, and then call
output function to print the obtained information on screen.
int main()
{
person worker; OUTPUT
worker=input();
output(worker);
return(0);
}
We have two important points that can be discussed about previous example. The first one is
that, it is possible to send and return a user defined variable type to a function. But we have to be
careful about the structure definition. The structure must be defined on top of all functions and
all declarations, otherwise the functions and/or declarations above structure definition will not
be able to access to that definition. You can try that just by changing the location of one of the
declarations (Either void output(person); or person input();) and moving it on top of
structure definition. The compiler will give you an error message ('person' was not declared in
this scope).
The other important point is related with input function. We can only return a single item with a
function. If we return a user defined structure then it will be possible to return more than one
variable (whatever the number of variables in defined structure) with a function.
Example:
Let’s play with the main function of the previous example. Assume we have 4 workers and we’ll
enter them in an array one by one and then print all of them on screen (again one by one). Entry
for the first worker will be done with an initializer list, second worker will be done with
assignment and last two (third and fourth) will be done with input function. There is no need to
modify input and output functions.
5. 2/7
ENG203 – Computer Programming II Prepared by Assoc.Prof.Dr. İbrahim ERŞAN
All parameter passing performed until now were “Pass by Value” method (mentioned in
previous lecture set). It is also possible to pass parameters with “Pass by Reference” method.
First of all we need to understand the difference. In “Pass by Value” we’re sending the value
(content) of a variable to a function, in “Pass by Reference” we’re sending the address of the
variable as reference to that variable (not the value of it). Let’s start with definitions of R-Value
and L-Value then try to understand by showing them on memory map.
R-Value (or Right Value, because R-Values are located to the right side of a statement) refers to
data value that is stored at some address in memory. L-Value (or Locator Value) refers to
memory location which identifies a data object. Simply we can think L-Values as containers and
R-Values as things contained in the containers.
How it will be possible to access R-Values and L-Values? There are two operators for this
purpose, these are & (ampersand) and * (star) operators. We are using these operators with
variable names. Meanings of these operators plays an important role in understanding “Pass by
Reference” method.
Assume that we have a variable X, we are using this variable to point (to show) another variable
Y. So variable X shows (points) us variable Y. Let’s continue with meanings of operators.
And finally, in order to define (in definition phase) a pointer (a variable which points (shows)
another variable) we are using * (star notation). E.g. int y; is used to define an integer variable
and int *x; is used to define a pointer variable which shows an integer variables (so x is an
integer pointer).
After understanding given information above, it will be possible for us to understand the
memory map below,
For the given memory map,
Y=5
Z=12
X=1200
&Y=1200
&Z=1201
&X=2500
*X=5 (X=1200 so Content of address 1200 is 5)
(*X)++ will make value of Y=6
*(X+1)=17 (X+1=1201 so Content of address 1201 is 17)
5. 3/7
ENG203 – Computer Programming II Prepared by Assoc.Prof.Dr. İbrahim ERŞAN
int main()
{
int y=5;
int *x;
x=&y;
printf("%d\n",y);
printf("%d\n",*x);
printf("%d\n",(*x)++);
printf("%d\n",y);
return(0);
}
In this example we reserve a space in memory for y and x. By using a * while defining x (int *x;)
we are telling to the comkpiler that x will point an integer value. We’re locating 5 in y and the
address of y in x. By this way x starts to point (show) variable y. In third printf(), while showing
the content of address which x points, we also incrementing it’s value by 1 with ++. If in third
printf we modify the code as,
printf("%d\n",++(*x));
Pass by Reference
When we pass the reference (address) of a variable, it will be possible for the function to
change the value of that variable. So the variable that we send to the function will be accessible
by the function. If you take a look at the fifth page of previous lecture set (page 4.5/6) you will
see that in Pass by Value it is not possible for a function to change the value of a parameter
which is sent to it but in Pass by Reference this can be done.
Let’s solve an example to illustrate this property. It will be good to solve the same example of
previous lecture set which is related with Pass by Value (first example on page 4.5/6) but this
time instead of Pass by Value we will solve the example by passing the parameters with Pass by
Reference.
Exactly the same code will be written again and it will be executed with same values. Of course,
while writing the code we’ll learn how to pass parameters with Pass by Reference (instead of
values of variables, addresses of variables will be sent to function).
5. 4/7
ENG203 – Computer Programming II Prepared by Assoc.Prof.Dr. İbrahim ERŞAN
OUTPUT
We are doing exactly the same operation more or less using
the same commands. The only difference here is that, in
operate function instead of using value of parameter (e.g. x),
we are using address (reference) of parameter(e.g. *x) so it is
possible to change the parameter’s value.
After changing the values of parameters in operate function, when we return back to main
function, in previous one the values of variables a and b are not changing BUT in current example
when we change them in operate function they are also changing in main function.
5. 5/7
ENG203 – Computer Programming II Prepared by Assoc.Prof.Dr. İbrahim ERŞAN
Because naturally we are sending addresses. So, for the function there is no difference if the
address belongs to a single integer or an integer array.
Finally, the output is a proof that arrays are sent with pass by reference because original value in
the first location of array was 3 BUT it is modified by our function (just before the return
statement).
5. 6/7
ENG203 – Computer Programming II Prepared by Assoc.Prof.Dr. İbrahim ERŞAN
Global Variables
Global variables are the variables that can be accessed by all functions in a program.
Before we discussed that, variables defined in main function can only be accessed by the
statements in main function and variables defined is a sub-function can only be accessed by the
statements of that sub-function. If we define a variable outside of all functions at the beginning
(after #include<>) then it will be a global variable. Consider following 3 programs to understand
the difference.
5. 7/7
ENG203 – Computer Programming II Prepared by Assoc.Prof.Dr. İbrahim ERŞAN
ENG203
COMPUTER PROGRAMMING II
Write two functions with names sortarray and printarray. Sortarray will be used to sort
any array sent to it as parameter and printarry will be used to pri nt array on screen (again the
array will be sent). Both functions will take two parameters, one integer array and one integer.
The second parameter is the dimension of integer array. It is possible to write a main function
to check if your functions are working correctly. In main function, create an integer array with
10 elements. İnitialize it with 10 numbers as you wish and then call defined functions to
examine the result.
#include <stdio.h>
OUPUT
void sortarray(int *, int);
void printarray(int *, int);
int main()
{
int a[10]={ 24,41,91,15,52,13,30,74,87,69};
printarray(a,10);
sortarray(a,10);
printarray(a,10);
return(0);
}
6. 1/5
ENG203 – Computer Programming II Prepared by Assoc.Prof.Dr. İbrahim ERŞAN
Write a function with name power, that will take two integer numbers as parameter
(let’s say x and y). This function will find xy and return the result back. If we consider that, these
integer numbers can be negative, the function must return a float value (e.g. 22 = 4 but 2-2 =
1/22 = 0.25). Like previous example, write a main function to check, if your power function is
working correctly. Notice: Only “stdio.h” library will be used.
#include <stdio.h>
int main ()
{
int n,p;
printf ("For x^y Enter x:");
scanf("%d",&n);
printf ("Enter y:");
scanf("%d",&p);
printf ("%d to the power of %d is %f",n,p,power(n,p));
return(0);
}
6. 2/5
ENG203 – Computer Programming II Prepared by Assoc.Prof.Dr. İbrahim ERŞAN
Write two functions with names swapi and swaps. Both functions are not returning any
parameter. swapi function will take two integers and swap their values (e.g. if it takes v1 and
v2, and value of v1=3 and value of v2=5, function will assign v1=5 and v2=3). swaps function
will take two strings (character arrays) and again swap their content. Only “stdio.h” and
“string.h” libraries will be used. Write a main function to check your functions.
#include <stdio.h>
#include <string.h>
int main ()
{
int a=5;
int b=9;
char c[]={"Apple"};
char d[]={"Strawberry"};
return(0);
}
6. 3/5
ENG203 – Computer Programming II Prepared by Assoc.Prof.Dr. İbrahim ERŞAN
6. 4/5
ENG203 – Computer Programming II Prepared by Assoc.Prof.Dr. İbrahim ERŞAN
Write two functions with names lens and revs. lens function will be used to find the
length of a string (like strlen function) and revs function will be used to convert order of string
to its reverse . both functions will take a string as parameter. lens function will return an
integer (as the lenght of the taken parameter) and revs function will not return anything (as it is
reversing the taken string). Only “stdio.h” library is allowed. Write a main function to check
your functions.
#include <stdio.h>
int main()
{
char s[100];
printf("Enter a string :");
gets(s);
printf("\nLength :%d",lens(s));
revs(s);
printf("\nReverse :%s",s);
return(0);
}
6. 5/5
ENG203 – Computer Programming II Prepared by Assoc.Prof.Dr. İbrahim ERŞAN
ENG203
COMPUTER PROGRAMMING II
All processes and their results can be kept in RAM but we lose our data when we exit
from the program. In order to prevent that, desired data must be recorded to an auxillary unit
like HDD, SSD, Flash Memory, SD Card etc. Data is stored to in storage units in form of files.
All storage units (including Random Access Memory) works with same principle. Entire storage
area is divided into fixed sized untis (which is one byte) and each unit has an address. So it is
possible to visualize structure of storage units as structure of memory.
If this is the case we need a variable which holds the address of current location, in other words
we need a pointer which shows current location in file. This is called file pointer. All files can be
defined as series of bytes (because we are storing data in bytes). Accessing to a file and reading
data from that file means going to the location where file pointer shows and taking these bytes
into memory.
If files are just series of bytes, there must be a starting point (starting address) and size (total
number of bytes) for each file. This information is kept in File Allocation Table (FAT) in your
HDD. In order to access to a file we are using the name of a file. Corresponding addresses for all
filenames are available in FAT. As result, filepointer takes the necessary address information
from FAT and starts to point any desired file.
After this brief and simplified information about how files are stored and how computers
accesses to files, let’s discuss how C manages file operations.
7. 1/20
ENG203 – Computer Programming II Prepared by Assoc.Prof.Dr. İbrahim ERŞAN
Basic Steps
Following steps must be applied in all file operations that will be performed using C
programming language.
Step 1) First of all a file pointer must be defined before opening a file. This file pointer will be
used to open and process the file. Filepointer will keep the address of current location in file
which will be used.
Any name can be used as a pointername. By writing above line a filepointer will be created.
Step 2) When a filepointer is defined, just after the definition it will not point any file till the
opening process. So, after defining a file pointer in order to make pointer to point a file, desired
file must be opened using fopen command.
fopen command takes two parameters, the first one is the logical location of file and filename
(e.g. C:\myfiles\test.txt). The second parameter defines the intend of usage (e.g. opening a file
to read data from file or to write data to file).
After fopen command, defined filepointer will take the address of desired file from FAT, and
from that command on, it will start to point the desired file. Simply fopen is used to set the
address of file to filepointer.
Step 3) Between Step 2 and Step 3 desired file operations like reading, writing etc. can be done.
After completing desired processes with opened file then it must be closed. In order to close a
file, fclose command is used. By this way filepointer will be free again and available to point any
other desired file.
7. 2/20
ENG203 – Computer Programming II Prepared by Assoc.Prof.Dr. İbrahim ERŞAN
We have two main operations, these are Reading and Writing. Appending is also a kind
of writing. We’ll start with writing operation.
Writing to a File
Three commands will be discussed for writing process, these are fprintf, fputs and putc. Writing
to a file is similar to writing on screen. The only difference is that, data will not be shown on
screen but will be recorded to a text file. Required parameters and syntax is given below,
The most important one is fprintf because it is possible to write data to file in any desired
format. Formatting is exactly the same as printf function.
#include <stdio.h>
int main() If path is not given, file will be
{ created wherever the source code
char n[30],s[30]; is.
int m,r;
FILE *fp;
fp=fopen("student.txt","w"); Be aware that, if “student.txt”
for (r=1;r<=5;r++) exists, it will be overwritten.
{
printf("Sudent %d\n",r);
printf("Enter Name :"); Hint: If you change fprintf with
scanf("%s",n); printf function, whatever you see
printf("Enter Surname :"); on screen, will be located in file
scanf("%s",s); using fprintf function.
printf("Enter Mark :");
scanf("%d",&m);
fprintf(fp,"%-30s %-30s %d \n",n,s,m);
}
fclose(fp); Remember: %-30s means, reserve
printf("Record Entry Completed"); 30 space and start filling up
return(0); reserved area from left
}
Don’t forget to close file with fclose function after
completing the processes related with file.
7. 3/20
ENG203 – Computer Programming II Prepared by Assoc.Prof.Dr. İbrahim ERŞAN
#include <stdio.h>
int main() Instead of “w”, “a” is used to append at the
{ end of an exsisting file. Note that, if file
FILE *fp; does not exists, it will be created.
fp=fopen("student.txt","a");
fprintf(fp,"%-30s %-30s %d\n","Belmont","Jewel",86);
fclose(fp);
printf("Record Entry Completed");
return(0);
}
write :
fputs("Belmont Jewel 86\n",fp);
31 Characters 31 Characters
7. 4/20
ENG203 – Computer Programming II Prepared by Assoc.Prof.Dr. İbrahim ERŞAN
#include <stdio.h>
#include <string.h>
int main()
{
char s[30];
int r;
FILE *fp;
printf ("Enter a string :");
scanf ("%s",s);
fp=fopen("reverse.txt","w");
for (r=strlen(s)-1;r>=0;r--)
putc(s[r],fp);
fclose(fp);
printf("File Recorded"); Exercise: Try to solve the same example
return(0); without using “string.h” library
}
7. 5/20
ENG203 – Computer Programming II Prepared by Assoc.Prof.Dr. İbrahim ERŞAN
7. 6/20
ENG203 – Computer Programming II Prepared by Assoc.Prof.Dr. İbrahim ERŞAN
int check(student k)
{
int ret=1;
if(strlen(k.name)>30)
{
printf("\nName must not be greater than 30 characters");
ret=0;
}
if(strlen(k.sname)>30)
{
printf("\nSurname must not be greater than 30 characters");
ret=0;
}
if(k.mark>100)
{
printf("\nMark cannot be greater than 100");
ret=0;
}
if(k.mark<0)
{
printf("\nMark cannot be a negative number");
ret=0;
}
return(ret);
}
void save (student y)
{
FILE *zx;
zx=fopen("recs.txt","a");
fprintf(zx,"%-30s%-30s%.2f\n",y.name,y.sname,y.mark);
fclose(zx);
}
int main()
{
student rec;
int c;
printf("Student Record Entry Program");
do
{
rec=entry();
if (check(rec)==0)
{
printf("\nPlease enter again");
c=1; Recommendation: Write this
} code and execute it. After
else being sure that it is working
{
if (confirmation(0)==1)
correctly, examine main
save(rec); function carefully and try to
c=confirmation(1); understand how it works. At
} the end, there must not be any
} question or doubt in your mind
while(c==1);
about how it works.
return(0);
}
7. 7/20
ENG203 – Computer Programming II Prepared by Assoc.Prof.Dr. İbrahim ERŞAN
Three commands will be discussed for reading process, these are fscanf, fgets and getc.
Reading from a file is similar to getting data from keyboard. The only difference is that, data will
not be taken from keyboard but will be taken from a text file. Required parameters and syntax
is given below,
NOTICE: In some examples of this section, a text files with name “f.txt” is used. Full content of
this text file is given at the end of the lecture set. It is possible to copy and paste it. If you copy
and paste it, please be careful about number of characters reserved for each data item (If not
copied correctly, just fix it by adding or removing spaces between fields).
7. 8/20
ENG203 – Computer Programming II Prepared by Assoc.Prof.Dr. İbrahim ERŞAN
There is a common point in all file reading functions which is very important and we have
to understand how it works. When we open a file in intend of reading, the file pointer will
automatically be located to the beginning of file. All reading functions starts taking data from the
location of file pointer. So, reading functions will start taking data from the beginning of file just
after opening the file. After a reading operation (in all reading functions) the file pointer will
automatically be moved to the end of data that is taken from file. For example, if you are using
getc function, after reading a character pointer will not point the beginning of file anymore. It
will automatically move to the next character. This is the same for all other functions, like, if you
are reading an integer with fscanf function from a file which consists all integers, pointer will
move to the beginning of next integer.
Examine following illustration about the position of file pointer. There are two files in given
example, in first file the content is “hello” and in the next file the content is “15, 78 and 95”.
Assume that, first file is read using getc and second file is read using fscanf (in order to read an
integer as we can guess %d must be used).
As can be seen, getc function is used to read one character from file so file pointer moved one
character automatically after reading. In given illustration fscanf function is used to read an
integer (e.g. fscanf (filepointer,”%d”,&k);) so file pointer moved to the next integer
automatically after reading.
7. 9/20
ENG203 – Computer Programming II Prepared by Assoc.Prof.Dr. İbrahim ERŞAN
30 Characters 30 Characters
As first example, read only the first record and print it on screen.
#include <stdio.h>
int main () Spaces are used to define fields. Number of
{ spaces are not important while using fscanf
char n[31]; function, because more than one space is
char s[31]; NOT taken into consideration (remember
int m; scanf function).
FILE *p;
p=fopen("f.txt","r");
fscanf(p,"%s%s%d",n,s,&m); OUTPUT
fclose(p);
printf("Name :%s\n",n);
printf("Surname :%s\n",s);
printf("Mark :%d",m);
return(0);
}
#include <stdio.h>
int main ()
{
char n[20][31];
char s[20][31]; Exercise: Modify given code by making some
int r,m[20]; additions to the code to print the average of
FILE *p; class at the end of the list.
p=fopen("f.txt","r");
for (r=0;r<20;r++)
fscanf(p,"%s%s%d",n[r],s[r],&m[r]);
fclose(p);
printf("%-30s%-30s%s\n","Name","Surname","Mark");
for (r=0;r<20;r++)
printf("%-30s%-30s%d\n",n[r],s[r],m[r]);
return(0);
}
7. 10/20
ENG203 – Computer Programming II Prepared by Assoc.Prof.Dr. İbrahim ERŞAN
7. 11/20
ENG203 – Computer Programming II Prepared by Assoc.Prof.Dr. İbrahim ERŞAN
Finding the End of File with EOF constant & NULL pointer
In examples that is used for reading, number of records in file is given. In most of the
tasks that we face with in real applications, the number of record may not be known. In such
cases, as we don’t know the exact boundaries, it will not be possible to use a classical for-loop.
Solution can be found with a while-loop but in that case we need a condition to stop reading
file. There must be a way to understand that we reach to the end of file and there is no more
record after this point. This can be achieved with EOF constant or NULL pointer.
When a function is used to get data from a file (usually we need to use a function), that
function (or read operation) returns a value back. If returned value is equal to EOF or NULL
(depending on function that you are using), it means that end of file is reached. EOF is a
constant indicating that end-of-file has been reached in a file. Likely, NULL means there is
nothing left in file for the file pointer to point.
fscanf function and getc function returns EOF back when the end of file is reached, and fgets
function returns NULL back when the end of file is reached.
If we are using fscanf function, we can test EOF by writing a condition in while-loop as,
If we are using fgets function, we can test EOF by writing a condition in while-loop as,
If we are using getc function, we can test EOF by writing a condition in while-loop as,
7. 12/20
ENG203 – Computer Programming II Prepared by Assoc.Prof.Dr. İbrahim ERŞAN
#include <stdio.h>
int main ()
{
char n[31],s[31]; In this example EOF is used to
int c=0,m; detect the end of file
FILE *p;
p=fopen("f.txt","r");
while ((fscanf(p,"%s%s%d",n,s,&m))!=EOF)
{
printf("%-30s%-30s%d\n",n,s,m);
c++;
}
printf("Total Number of Records :%d",c);
fclose(p);
return(0); OUTPUT
}
#include <stdio.h>
int main ()
{ In this example NULL is used
char rec[65];
int c=0;
to detect the end of file
FILE *p;
p=fopen("f.txt","r"); Note that, there is no need to
while ((fgets(rec,65,p))!=NULL) use ‘\n’ in printf function
{
because fgets also reads jump
printf(rec);
c++; to the next line characters.
}
printf("\nTotal Number of Records :%d",c); Exactly the same output will
fclose(p); be obtained.
return(0);
}
7. 13/20
ENG203 – Computer Programming II Prepared by Assoc.Prof.Dr. İbrahim ERŞAN
Discussion
For the file “tiny2.txt” everything seems fine and as expected. When we look at the content,
there are 10 characters in file. When we check the properties of file its size is 10 bytes, as we all
know, each character requires 1 byte. When we execute our program, in output we can see
that number of characters counted as 10.
But what about “tiny1.txt” file? When we look at the content, there are 10 characters in file.
When we check the properties of file its size is 14 bytes! When we execute our program, in
output we can see that number of characters counted as 12! Why we have these differences?
The answer is directly related with Line Break (Jumping to the next line).
In a text file, there must be an indicator which shows the end of line and make the application
which gives us output, jump to the next line. This indicator differs depending on operating
system and they can be found as control characters in ASCII table.
CR : Carriage Return, ASCII code is 13 (in Hex. 0D) – Enter or Return key on keyboard
LF : Line Feed, ASCII code is 10 (in Hex. 0A)
As result, if we jump to next line, in Windows operating systems, two invisible characters
(because they are control characters) are added at the end of the line.
In file “tiny1.txt”, after words “My” and “Test”, we are jumping to the next line, so we have 2
line breaks (for each line break we need 2 bytes) which makes 4 bytes in total + we have 10
characters. That’s why the size of file is 14 bytes.
One of the characters which is used for line break is CR (Enter or Return Key on Keyboard) and
Enter key is used to terminate input for any input function, which means input operation stops
whenever CR is found (e.g. scanf, gets, fscanf, fgets and getc). So input functions are not able to
take CR as input but they can take LF. Which means LF can be counted but CR cannot be
counted. At the end of “My” and “Test” words, LF is also counted as one extra character (but CR
is NOT) . That’s why the result of count is 12 characters.
After learning the details about how text files are managed, it is possible to continue with
another important subject which is moving file pointer in a file for desired number of bytes (or
characters).
7. 15/20
ENG203 – Computer Programming II Prepared by Assoc.Prof.Dr. İbrahim ERŞAN
Moving in a file without using any file reading statement is possible with fseek
statement. By moving the file pointer, which shows the current location in a file, forward and
backward, moving in a file is possible.
As discussed before, a file is recorded to your HDD (or SSD) as a series of bytes (like a single
line). According to that explanation, following figure depicts how this file will be recorded and
where will be the pointer when it is opened (SP stands for Blank-Space, CR & LF is known),
#include <stdio.h>
int main ()
{
char s[50];
int m;
FILE *p;
p=fopen("mids.txt","r");
fseek(p,14,0);
fscanf(p,"%s%d",s,&m);
printf("%-10s%d\n",s,m);
fseek(p,0,0);
fscanf(p,"%s%d",s,&m);
printf("%-10s%d\n",s,m);
fseek(p,28,0);
fscanf(p,"%s%d",s,&m);
printf("%-10s%d\n",s,m);
fseek(p,-14,2);
fscanf(p,"%s%d",s,&m);
printf("%-10s%d\n",s,m);
fseek(p,-12,1);
fscanf(p,"%s%d",s,&m);
printf("%-10s%d\n",s,m);
fclose(p);
return(0);
}
7. 16/20
ENG203 – Computer Programming II Prepared by Assoc.Prof.Dr. İbrahim ERŞAN
ftell statement simply returns the current file position of the specified file pointer with
respect to the starting of the file. When you move in a file with fseek statement or read a data
form file using any input statement, the position of file pointer changes. Whenever ftell
statement is executed, it returns the current position of file pointer at that moment.
fseek(p,28,0);
printf("%d\n",ftell(p));
fscanf(p,"%s%d",s,&m);
printf("%-10s%d\n",s,m);
printf("%d\n\n",ftell(p));
fseek(p,-14,2);
printf("%d\n",ftell(p)); Exercise:
fscanf(p,"%s%d",s,&m);
printf("%-10s%d\n",s,m);
How we can find the size of any file in
printf("%d\n\n",ftell(p)); term of bytes? Write a code which finds
and prints the size of any desired file.
fseek(p,-12,1);
printf("%d\n",ftell(p)); Hint:
fscanf(p,"%s%d",s,&m); When you move the file pointer at the
printf("%-10s%d\n",s,m);
printf("%d\n\n",ftell(p)); end of a file (using fseek function) and
find the position of pointer at that
fclose(p); location (using ftell function), it will give
return(0); you the size of a file.
}
7. 17/20
ENG203 – Computer Programming II Prepared by Assoc.Prof.Dr. İbrahim ERŞAN
FILE MANAGEMENT
There are a lot of file management statements and methods but we’ll deal with only the
ones which will be useful in your lectures related with computer programming, computer
laboratory, iterative solutions, simulations etc.
While dealing with files we need three basic management processes, these are, checking
existence of a file, renaming and removing a file.
It is possible to check if a file exists or accessible. It will be appropriate to perform this check,
otherwise you will not be able to access and all read statements may return null OR you will get
an error message. When a file pointer is created, till a file address is assigned to that file pointer
(with fopen statement), it points NULL location (nothing).
After opening a file and assigning it to a file pointer if file pointer still points a NULL location, it
means that either file does not exists or accessible.
#include <stdio.h>
int main ()
{
FILE *p;
p=fopen("mids.txt","r");
if(p==NULL)
printf("File Does NOT Exists or NOT accessible");
else
printf("File exists and accessible");
fclose(p);
return(0);
}
Possible OUTPUTS
7. 18/20
ENG203 – Computer Programming II Prepared by Assoc.Prof.Dr. İbrahim ERŞAN
Syntax: rename(“CurrentFilename”,”NewFilename”);
After execution, rename statement returns an integer back. By checking this integer value it is
possible to understand if process completed successfully or not. If rename is done, function
returns 0, if it is NOT done, function returns -1. (If file does not exists OR not accessible due to
being in use by another application, rename process will fail and return -1 but it will not give an
error message).
After execution, remove statement returns an integer back. By checking this integer value it is
possible to understand if process completed successfully or not. If remove is done, function
returns 0, if it is NOT done, function returns -1. (If file does not exists OR not accessible due to
being in use by another application, remove process will fail and return -1 but it will not give an
error message).
30 30 3
63 Characters
7. 20/20