0% found this document useful (0 votes)
18 views77 pages

Progamming 2 Revision

Uploaded by

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

Progamming 2 Revision

Uploaded by

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

ENG203

COMPUTER
PROGRAMMING
II

LECTURE NOTES

Assoc.Prof.Dr. İbrahim ERŞAN

GİRNE AMERICAN UNIVERSITY


FACULTY OF ENGINEERING
COMPUTER ENGINEERING DEPARTMENT
Preface

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

Lecture Set 0 – COMPUTER PROGRAMMING I - REVISION

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,

(1) General Syntax of C programming language


(2) Variable definitions (int, float etc.)
(3) Input – Output Functions (printf, scanf etc.)
(4) Arithmetic Operators and their priorities (+, -, *, /, %)
(5) Loops (for, while, do-while)
(6) Decision Statements (if-else, switch)
(7) One dimensional arrays

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:

Write a C program using for loop to obtain the following pattern.

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

Loops - Question 2: Answer 2:


#include <stdio.h>
Write a program that will create following pattern #include <math.h>
as output using for loop. It is important that int main()
height of triangle will be entered by user. {
int x,y,h,w;
printf ("Enter Height:");
scanf ("%d",&h);
for (x=0; x<h; x++)
{
w=pow(2,x);
e.g. for (y=0; y<w; y++)
height printf("X");
is 6 printf("\n");
}
return(0);
}

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.

ii. 10 numbers will be entered from keyboard and located in arrx.

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

iv. Find the maximum value in arrx and print on screen.

v. Print location(s) of maximum value in arry.

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:

1. Write a program to find and print the result of


R= (N!+M!) / (N-M)! using for loop
Note: N and M will be entered from keyboard and N must be greater than M.

2. Repeat the question using while loop.

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.

4. Write a complete C program to do the following


a. Define a character array with 100 locations and initialize it as you wish
b. Display on screen, the total number of characters in array and number of vowels
c. Display how many characters are there for each vowel
e.g. a=5, e=2, i=0, u=1, o=3

0. 5/5
ENG203 – Computer Programming II Prepared by Assoc.Prof.Dr. İbrahim ERŞAN

ENG203
COMPUTER PROGRAMMING II

Lecture Set I – TWO DIMENSIONAL ARRAYS (MATRICES)

Matrix Definition

One dimensional array can be thought as a field of data. Two dimensional array can be
thought as a ‘matrix’.

One dimensional array Two dimensional array

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.

for (r=0; r<3; r++)


{
for (c=0; c<3; c++)
printf("%2d",arr[c][r]);
printf("\n");
}

1. 2/16
ENG203 – Computer Programming II Prepared by Assoc.Prof.Dr. İbrahim ERŞAN

Example 4: Define a 3x5 integer array.


i. Enter a value for each location from keyboard (Inform user for entries)
ii. Print formed matrix on screen
iii. Find minimum number, maximum number, average of all odd numbers and print.

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:

Example 1: Output will be Now, let’s change our example a


little. Instead of setting all elements
As can be seen the example to 1, let’s try to generate following
is very simple. All elements matrix:
of matrix is 1. Let’s assign
all values to 1.

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 :

As can be seen from this example upper & lower triangle is


seperated and also diagonal is separated.

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

Martix Multiplication and Addition


More examples will be solved on matrix generation in following pages but now we will perform
a mathematical operation on matrices. We’ll try to make a matrix multiplication. First of all
we’ll start with vector multiplication with a matrix.

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.

Example 1 (Multiplication of a Vector with a Matrix):

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

Trace of the example :

sum c r y[c] z[c][r]

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

Example 2 (Multiplication of two Matrices):


Now we’ll try to multiplicate two matrices. This process needs three nested loops compared to
the previous one. We’ll try to multiplicate a (2x2) matrix with a (2x3) matrix.

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

Trace of multiplication part :


c r x sum

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

Example 3 (Addition of two matrices ):


Compared with previous two examples this one is more easy. As we all know in matrix addition
(or subtraction) process There are two matrices Y and Z.

4 3 2 1 2 3 Values of these matrices will be entered using


Y= 1 1 2 Z= 3 2 1 initializer list.
3 4 3 1 2 3 i. Show contents of matrix Y as output.
ii. Show contents of matrix Z as output.
iii. Add two matrices and assign result to
Answer 3: another matrix A.
#include <stdio.h> iv. Show contents of matrix A as output.
int main()
{
int c,r;
int y[3][3]={4,3,2,1,1,2,3,4,3};
int z[3][3]={1,2,3,3,2,1,1,2,3};
int a[3][3];
printf("Matrix Y :\n");
for(r=0;r<=2;r++)
{
for(c=0;c<=2;c++)
{
printf("%3d",y[r][c]);
}
printf("\n");
}
printf("Matrix Z :\n");
for(r=0;r<=2;r++)
{
for(c=0;c<=2;c++)
{
printf("%3d",z[r][c]);
}
printf("\n");
}
for(r=0;r<=2;r++)
{
for(c=0;c<=2;c++)
{
a[r][c]=y[r][c]+z[r][c];
}
} OUTPUT
printf("Result of Y+Z :\n");
for(r=0;r<=2;r++)
{
for(c=0;c<=2;c++)
{
printf("%3d",a[r][c]);
}
printf("\n");
}
return(0);
}

1. 10/16
ENG203 – Computer Programming II Prepared by Assoc.Prof.Dr. İbrahim ERŞAN

Example 4 (Complete Matrix Multiplication Solution):


Now, we’ll try to solve matrix multiplication problem for large matrices for variable dimensions.
Write a program to multiplicate two matrices M1 and M1 (M1xM2). Dimensions of these
matrices will be entered from keyboard BUT each dimension must NOT exceed 99x99. If one of
the dimensions exceeds 99, program will warn user. By the way, if column count of M1 is NOT
equal to row count of M2, program will warn user also. After defining dimensions, all values of
both matrices will be entered from keyboard one by one. Finally, program will multiplicate both
matrices and assign result to another matrix RS. Meanwhile output will be printed on screen.

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

Exercises and Solutions on Matrix Generation

Exercise 1: Generate following matrix using loops,

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

Exercise 2: Generate following matrix using loops,

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

Exercises for you to try

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

Lecture Set II - STRINGS

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.

Entering a String from Keyboard

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 :

ii. using gets

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.

#include <stdio.h> OUTPUT


int main()
{
char nm[40];
puts("Enter your name :");
gets(nm);
puts("Hello");
puts(nm);
return(0);
}

2. 2/10
ENG203 – Computer Programming II Prepared by Assoc.Prof.Dr. İbrahim ERŞAN

Entering String in Initialization (String Assignment with Initializer)

#include <stdio.h>
int main()
{
char a[]="Programming";
char b[3]="is\0"; All three string assignments are same
char *c="Good";

puts(a); In this one legth of ‘is’ is 2. But we define


puts(b); array with 3 elements because, for defined
puts(c);
array lengths last character must be ‘null’ ,
return(0);
character which indicates the end of string.
}

OUTPUT :

String Processing Functions

Four string functions will be examined in this course. There are a lot of string functions
but these important ones are sufficient for now.

i. strlen (string) : returns length of string.

ii. strcpy (string1,string2) : copies information from string 2 to string 1.

iii. strcmp (string1,string2): compares two string & returns an integer.


Comparison takes place alphabetically.

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.

Important : these four functions are located in ‘string.h’ header file.

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.

e.g. strcmp("Blue","Blue"); returns 0


First parameter is exactly the same as second parameter

strcmp("Blue","Red"); returns a negative number


First parameter is prior alphabetically

strcmp("Red","Blue"); returns a positive number


Second parameter is prior alphabetically

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.

98 114 111 97 100 101


b r o a d e

b r o a f t
98 114 111 97 102 116

Difference 0 0 0 0 -2 -2 will be returned

Let’s continue with examples related with string processing functions in order to understand
them better.

Example 1 (strlen Function):


Find the total number of characters in a string entered from keyboard.

#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

Example 2 (strlen Function):


Find each character’s memory address and Ascii Code in a character array (string).
#include <stdio.h>
#include <string.h>
int main()
{
char nm[50];
printf ("Please enter a string :");
scanf ("%s",nm);
printf ("Analysis Results\n");
for (int i=0;i<strlen(nm);i++)
{
printf ("Address=%u, Character=%c,
Code=%d\n",&nm[i],nm[i],nm[i]);
}
return(0);
}

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

Example 3 (strlen Function):


After entering a string from keyboard, a triangular pattern will be created as following example,
with respect to your entry

Please Enter a String : AHMET SOLUTION


A
#include <stdio.h>
AH #include <string.h>
AHM int main()
AHME {
AHMET char nm[50];
int i,r,c;
printf ("Please enter a string:");
scanf ("%s",nm);
i=strlen(nm);
for (c=0;c<i;c++)
{
for (r=0;r<=c;r++)
{
printf ("%c",nm[r]);
}
printf ("\n");
}
return(0);
}

2. 5/10
ENG203 – Computer Programming II Prepared by Assoc.Prof.Dr. İbrahim ERŞAN

Example 4 (strlen Function):


After entering a string from keyboard, program will print the entered string on screen in
reversed order.

e.g. Entry : HELLO


Result : OLLEH

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

Example 5 (strcpy Function):


Copying one string variable to another can be done in two ways, following example shows us
both.
#include <stdio.h> This for-loop copies string
#include <string.h> content of “nm” array to “cpy1”
int main() array. Note that, it starts
{ copying starting from index 0 till
char nm[50];
the length of string (included).
char cpy1[50];
char cpy2[50]; When we count, result is total
int i,r,c; length + 1. This extra 1 is used
printf ("Please enter your name :"); for the NULL character at the
scanf ("%s",nm); end of string. That’s why in for-
for (c=0;c<=strlen(nm);c++) loop we’re using “<=” instead
{
“<”.
cpy1[c]=nm[c];
}
strcpy(cpy2,cpy1); The same operation can be done
printf ("%s",nm); with this single function.
printf ("\n%s",cpy1);
printf ("\n%s",cpy2); As result, contents of “nm”,
return(0);
}
“cpy1” and “cpy1” arrays will be
the same.

2. 6/10
ENG203 – Computer Programming II Prepared by Assoc.Prof.Dr. İbrahim ERŞAN

Example 6 (strcmp function):


Write a program that will enter a string from keyboard and compare entered string with a
defined password string. Define password string as “teatime”. If entered string and defined
string are same program will prompt user that password is correct otherwise it will prompt user
that access is denied.

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

Example 7 (strcmp function): OUTPUT 1 :


Repeat previous example but this time if password is NOT
Please Enter Password
correct, program will allow user to make three entries.
Entry 1 :abc
Entry 1 is NOT correct
#include <stdio.h>
Entry 2 :ser
#include <string.h>
Entry 2 is NOT correct
int main()
Entry 3 :test
{
Entry 3 is NOT correct
int r;
Access DENIED
char defpas[]="teatime";
char pas[50];
puts ("Please Enter Password"); OUTPUT 2 :
for (r=1; r<4; r++)
Please Enter Password
{
Entry 1 :tea
printf ("Entry %d :",r);
Entry 1 is NOT correct
gets (pas);
Entry 2 :teatime
if (strcmp(defpas,pas)==0)
CORRECT Password
r=4;
else
printf ("Entry %d is NOT correct\n",r);
}
if (r==4) puts ("Access DENIED");
if (r==5) puts ("CORRECT Password");
return(0);
}

2. 7/10
ENG203 – Computer Programming II Prepared by Assoc.Prof.Dr. İbrahim ERŞAN

Example 8 (strcat function):


Write a program that will take name and surname of user from keyboard in two arrays (let’s say
“nm” and “sn” respectively) and then locate them in a single array (let’s say “nmsn”) with one
space in between. And print the content of “nmsn” array on screen.
#include <stdio.h>
#include <string.h>
int main() For a space in between we need only
{ one space character BUT in spite of
char nm[50]; needing one character we’re using
char sn[50]; double quotes (“) NOT single quote (‘)
char nmsn[50]; because strcat() function can only
printf ("Please enter your name:"); work with strings (NOT with
scanf ("%s",nm); characters). If you try to use single
printf ("Please enter your surname:"); quote, you’ll get an error.
scanf ("%s",sn);
strcpy(nmsn,nm);
strcat(nmsn," "); strcat() function always adds the
strcat(nmsn,sn); second parameter to the end of first
printf("%s",nmsn); parameter.
return(0);
}

OUTPUT

Example 9 (strcat function):


Repeat the same example but this time in “nmsm” array, there will be the first letter of name
and then a space, and then surname. Despite of getting full name from keyborad, you’ll just use
the first letter of name.
#include <stdio.h>
#include <string.h>
int main()
{
char nm[50];
char sn[50];
char nmsn[50];
printf ("Please enter your name:");
scanf ("%s",nm);
printf ("Please enter your surname:");
scanf ("%s",sn);
strcpy(nmsn,nm);
nmsn[1]='\0'; OUTPUT
strcat(nmsn," ");
strcat(nmsn,sn);
printf("%s",nmsn);
return(0);
}

2. 8/10
ENG203 – Computer Programming II Prepared by Assoc.Prof.Dr. İbrahim ERŞAN

String Conversion Functions


These functions are located in “stdlib.h” library file. atoi function is used to convert string to
integer and atof function is used to convert string to float (real number).

Syntax : atoi (string);


atof (string);

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

Complementary Example for Strings and Arrays


Enter a string from keyboard and assign it into an array, character by character, as
shown below, then display created array on screen. By solving this example it will be possible to
practice both strings and matrices.
e.g. Entry : PARTY (Lenght of entry is 5)
Array : PARTY (Created Matrix is 5x5)
YTRAP
PARTY
YTRAP
PARTY

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

Lecture Set III - STRUCTURES

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.

Array : A set of elements of the same data type.


Structure : A set of elements of different data types (A new data type).

How we can define a structure?


When we define a structure, we are not defining a new data but we are defining a new data
type. After defining this new data type, then it is possible to define a new data using this new
type.

Syntax: struct mydata


{
int a;
float c;
char d;
char e[10];
};

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.

How we can define a variable with new data type?


Just like defining a variable with any data type. You’ll first write data type then variable name.

e.g. mydata abc; //creates a variable with name abc

How we can access to a variable in structured data?


Names that we use inside the structure definition will be used for the access. If you assign any
value to these names (in definition phase), these values will be accepted as default values for
that portion of structured data. For accessing any portion, dot operator will be used.

e.g. printf(“%d”,abc.a); //prints the integer part of abc

3. 1/4
ENG203 – Computer Programming II Prepared by Assoc.Prof.Dr. İbrahim ERŞAN

Example 1 (definition, assignment, access):

#include <stdio.h> We define data type ‘person’ using


#include <string.h> struct statement, before ‘main’
routine. By this way our definition is
struct person
global. If we define it inside a function
{
it’ll be accesible only by that function.
char name[30];
char sname[30];
int age; We can also define
char gender; any desired variable
float salary; just after declaration.
} ;
Variable definition
int main()
{
person worker; Assignment

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;

By changing this line as


Person worker = {"Jack","Daniels",25,’M’,1435.5};

printf("Name :%s %s\n",worker.name,worker.sname);


printf("Age :%d\n",worker.age);
printf("Gender :"); So, it is possible to use “initializer
if(worker.gender='M') list” in structured variables.
printf("MALE");
else
printf("FEMALE");
Access
printf("\nSalary :%.2f",worker.salary);
return(0);
}

OUTPUT :

3. 2/4
ENG203 – Computer Programming II Prepared by Assoc.Prof.Dr. İbrahim ERŞAN

Example 2 (structures in arrays and keyboard enrty):


Assume we have a class with three students. For each student we will keep a name and a mark
(grade) as float. Name and mark of each student will be entered from keyboard and program
will find and print on screen, the student having the maximum mark
#include <stdio.h>
int main()
{
struct person
{
char name[50];
float mark;
};
person student[3],leader;
int r,p;
float max=0;
printf("Please Enter Names and Marks\n");
for(r=0;r<3;r++)
{ It is possible to use following two
printf("Student Name %d:",r+1);
lines of code instead of this line.
scanf("%s",student[r].name);
printf("Student Mark %d:",r+1); The same result will be obtained.
scanf("%f",&student[r].mark); As far as it is possible to assign
if(max<student[r].mark) two variables, in same type, to
{ each other, there is no need to
max=student[r].mark; assign content one by one.
p=r;
} strcpy(leader.name,student[p].name);
} leader.mark=student[p].mark;
leader=student[p];
printf("\nLeader Name :%s",leader.name); Don’t forget that, if
printf("\nLeader Mark :%.2f",leader.mark); you do such an
return(0); assignment (one by
}
one), beacuse of
using ‘strcpy’
function, “string.h”
library must be
OUTPUT : included.

3. 3/4
ENG203 – Computer Programming II Prepared by Assoc.Prof.Dr. İbrahim ERŞAN

Example 3 (arrays in structures):


Repeat the previous example but this time “person” data type will include three marks (floats)
in an array. Instead of keeping one mark for a student we’ll keep three marks and these marks
will be kept in a one dimensional array. In order to find the leader, we’ll use the average of
three marks for each student.

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

As we have three elements in mark portion of person variable, we created a


loop to make entry to all elements.

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

Lecture Set IV – INTRODUCTION to FUNCTIONS

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.

2. In case of an error in a functionality, debugging can be done relatively easy because


error will be trapped in a function. Otherwise it will propagate to other
functionalities.

3. Program can be divided into manageable sections. It will be possible to organize


entire application with respect to functionalities carried out in application.

4. As far as functionalities are organized and separated, it will be relatively easy to


understand source code.

5. Adding/removing functionalities to an application will be more manageable and


easy. This is because, each functionality will behave as an independent unit.

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

Function Declaration and Function Definition

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

int main() As wf function is written after the main function, it is


{ declared before the main function. While declaring a
hf(); function, don’t forget to end-up with a semi-colon.
wf();
return(0); And in main function, we are calling hf and wf to
}
make them work. When you call a function, compiler
void wf() goes to that function, executes it and returns back to
{ where ever it was and program continues from that
printf("World"); point on.
}

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?

Now, let’s solve another simple function example to learn


how to return a value after executing the function. Don’t
forget, while defining and declaring such a function first
expression must be the data type that will be returned
back.
4. 2/6
ENG203 – Computer Programming II Prepared by Assoc.Prof.Dr. İbrahim ERŞAN

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

We have two possible outputs, either the password


is correct OR it is not correct. For both cases it is
possible to see the screen outputs on right.

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.

Parameter Passing (Pass by Value)

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?

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");
x--;
y++;
} There will not be any difference

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?

void operate (int a, int b, char c)


{
printf("Result :");
if(c=='+') printf("%d",a+b);
else if(c=='-') printf("%d",a-b);
else if(c=='*') printf("%d",a*b);
else if(c=='/') printf("%f",1.*a/b);
else printf("Invalid Operation");
a--;
b++;
} There will not be any difference

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.

int factorial (int x)


{
int j=1;
for(int y=1; y<=x; y++)
j*=y;
return(j);
}

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 factorial (int x)


{
int j=1;
for(int y=1; y<=x; y++)
j*=y;
return(j);
}

int main()
{
int k;
printf("Enter a positive integer value :");
scanf("%d",&k);
printf("Factorial of %d is %d",k,factorial(k));
return(0);
}

It is possible to find some typical outputs of the program below,

4. 6/6
ENG203 – Computer Programming II Prepared by Assoc.Prof.Dr. İbrahim ERŞAN

ENG203
COMPUTER PROGRAMMING II

Lecture Set V – PARAMETERS in FUNCTIONS

Parameter passing is very important in “Procedural Programming” because entire program is


designed using functions and all processes are carried out with function calls. Also, in
programming languages like C, where all commands are designed as functions, the importance of
functions increases. If this is the case, passing parameters to these functions and returning
parameters from these functions has a great role in efficiency of programming using functions.

User Defined Structure as Parameter

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.

#include <stdio.h> person input()


{
struct person person x;
{ printf("Enter Name :");
char name[50]; scanf("%s",x.name);
int age; printf("Enter Age :");
float salary; scanf("%d",&x.age);
}; printf("Enter Salary:");
scanf("%f",&x.salary);
void output (person); return(x);
person input(); }

int main()
{
person worker; OUTPUT
worker=input();
output(worker);
return(0);
}

void output (person x)


{
printf("\nName :%s\n",x.name);
printf("Age :%d\n",x.age);
printf("Salary :%f\n",x.salary);
}
5. 1/7
ENG203 – Computer Programming II Prepared by Assoc.Prof.Dr. İbrahim ERŞAN

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.

#include <string.h> OUTPUT


int main()
{
person worker[4]={"William",27,123.32};
strcpy(worker[1].name,"Henry");
worker[1].age=28;
worker[1].salary=321.23;
for(int i=2; i<4; i++)
{
printf("Entry for worker %d:\n",i+1);
worker[i]=input();
}
for(int i=0; i<4; i++)
output(worker[i]);
return(0);
}

As can be seen only the main function is modified. There is one


addition on top of the program. “string.h” library must be included,
because in main function strcpy command is used (which is located
in “string.h”). Because of having more than one worker we’re just
solving the problem by using a loop.

5. 2/7
ENG203 – Computer Programming II Prepared by Assoc.Prof.Dr. İbrahim ERŞAN

Pass by Value versus Pass by Reference

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.

* means : Content of (e.g. *N is content of location pointed by N)


& means : Address of (e.g. &M address of variable M)

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)

● *X is the R-value of address 1200 so it is 5


● Address 1200 is the R-value of X
● So, *X is the R-value of R-value of X

5. 3/7
ENG203 – Computer Programming II Prepared by Assoc.Prof.Dr. İbrahim ERŞAN

Example (Memory Map Proof):


Let’s prove the given memory map example with a simple code to understand it better and see
that it really works. BUT when you define two integer variables Y and Z, it is not possible to say
that these two variables will be created in memory successively (so it’ll not be possible to
simulate it right now but there is a way to perform it, this part will be discussed later).

#include <stdio.h> OUTPUT

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

output would be 5,5,6,6 instead if 5,5,5,6

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

Example (sending parameters with reference): While declaring a function if we want


to send a parameter by reference, we
#include <stdio.h>
have to use * (star) operator just after
void operate (int*, int*, char); data type.

int main() While sending parameters by


{ reference, as we are not sending
int a,b;
char c; values of variables, we have to use &
printf("Enter Operation\n"); (ampersand – address of) operator.
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);
} In function definition, just
like in declaration part, we
void operate (int *x, int *y, char z)
have to use * (star) operator.
{
printf("Result :");
if(z=='+') printf("%d",(*x)+(*y)); While we are using variables
else if(z=='-') printf("%d",(*x)-(*y)); in function, in order to
else if(z=='*') printf("%d",(*x)*(*y)); access the value of sent
else if(z=='/') printf("%f",1.*(*x)/(*y));
else printf("Invalid Operation");
address we have to use the
(*x)--; variables with * (address of)
(*y)++; operator.
}

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.

The result of operation is same in both examples but when


we look at the last line of the output, we can see the
difference between previous example (on page 4.5/6) and
current example.

Last line of previous example was

and, last line of this example is

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

Passing Arrays as Parameter

As it is possible to pass all kinds of variables as parameters, it is also possible to pass


arrays as parameter. There is one important point about passing arrays as parameters. In C
language, arrays can only be sent with Pass by Reference. It is NOT possible to pass an array to a
function as parameter with Pass by Value.

#include <stdio.h> This can be replaced with,


int findmax (int [], int); int findmax (int *, int);

int main() Because we’re sending the address of first


{ location of an array.
int a[10]={3,5,9,1,2,4,10,7,8,3};
printf("Max Value :%d",findmax(a,10));
printf("\nFirst Value :%d",a[0]);
return(0);
} While we’re discussing “&” in scanf function, it is said
that scanf function accepts addresses only, that’s why
int findmax (int x[], int r)
{ we are using “&” in parameters of scanf.
int max=x[0]; While entering strings, we discussed why we are NOT
for (int j=0; j<r; j++)
using “&” for character arrays, and it is said that, array
if (x[j]>max)
max=x[j]; names without indices gives us the address of first
x[0]=1; location of an array, that’s why we are NOT using “&” in
return(max); scanf while we’re entering strings.
}
Now, while we are sending an array as parameter, as
OUTPUT arrays can only be sent with pass by reference, we have
to send the address of an array, that’s why we are just
writing the name of array (without any index number,
e.g. a[0]).
From that point on, we can send an array to a function
as shown below (so, it is replaceable with following line),
printf("Max Value :%d",findmax(&a[0],10));

Try it! It will work.

Again, it is possible to replace this line as,


int findmax (int *x, int r)

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.

#include <stdio.h> #include <stdio.h> #include <stdio.h>

void sub () int a=1; int a=4;


{
int a=1; void sub () void sub ()
a+=2; { {
printf ("%d\n",a); a+=2; int a=1;
a+=2; printf ("%d\n",a); a+=2;
} a+=2; printf ("%d\n",a);
} a+=2;
int main () }
{ int main ()
int a=7; { int main ()
sub(); a=7; {
printf ("%d\n",a); sub(); int a=7;
return(0); printf ("%d\n",a); sub();
} return(0); printf ("%d\n",a);
} return(0);
}

OUTPUT OUTPUT OUTPUT


3 9 3
7 11 7

MEMORY MEMORY MEMORY

While examining the examples, keep in your mind that,


(1) Execution always starts from main function
(2) When a function is finished (when we reach to the end of function or return from a function)
all variables related to that function is also terminated with that function.
(3) A Global variable is accessed by all functions
(4) If the name of global variable and the name of variable defined in a function is the same,
always the one which is defined in function overrides the global one (third example).

5. 7/7
ENG203 – Computer Programming II Prepared by Assoc.Prof.Dr. İbrahim ERŞAN

ENG203
COMPUTER PROGRAMMING II

Lecture Set VI – FUNCTION EXAMPLES

Example 1: Passing Array as Parameter

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

void printarray(int x[], int r)


{
printf("\nArray:\n------\n");
for(int i=0;i<r;i++)
printf("%d\n",x[i]);
}

void sortarray (int x[], int r)


{
for (int j=0; j<r-1; j++)
for (int k=j+1; k<r; k++)
if (x[j]>x[k])
{
int t=x[j];
x[j]=x[k];
x[k]=t;
}
}

6. 1/5
ENG203 – Computer Programming II Prepared by Assoc.Prof.Dr. İbrahim ERŞAN

Example 2: Taking Power of a Number

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>

float power(int, int);

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

float power (int x, int y)


{
float m=1;
int i; Sample OUTPUTS
if (y>0)
{
for(i=1;i<=y;i++)
m=m*x;
return(m);
}
else
{
i=y*2;
y=y-i;
for(i=1;i<=y;i++)
m=m*x;
return(1/m);
}
}

6. 2/5
ENG203 – Computer Programming II Prepared by Assoc.Prof.Dr. İbrahim ERŞAN

Example 3: Swap two Integers & two Character Arrays

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>

void swapi(int *,int *);


void swaps(char *,char *);

int main ()
{
int a=5;
int b=9;
char c[]={"Apple"};
char d[]={"Strawberry"};

printf ("a=%d, b=%d",a,b);


swapi(a,b); OUTPUT
printf ("\nAfter Swap\n");
printf ("a=%d, b=%d\n\n",a,b);

printf ("c=%s, d=%s",c,d);


printf ("\nAfter Swap\n");
swaps(&c,&d);
printf ("c=%s, d=%s",c,d);

return(0);
}

void swaps(char s1[],char s2[])


{
char t[500];
strcpy(t,s1);
strcpy(s1,s2);
strcpy(s2,t);
}

void swapi(int *v1, int *v2)


{
int i;
i=*v1;
*v1=*v2; Discussion:
*v2=i; What is the bottleneck in
} this code?

6. 3/5
ENG203 – Computer Programming II Prepared by Assoc.Prof.Dr. İbrahim ERŞAN

Example 4: Global Matrix Processing Functions


There are three functions in given code.
#include <stdio.h>
One of the functions is used to show
int mat[5][5]; content of a two dimensional array
(matrix) on screen. The other function, is
void shwmat();
void sqrmat(); used to take the square of a matrix and
void entmat(); last one is used to enter values to a matrix
via keyboard. All functions are working on
int main ()
{
a global integer matrix definition
entmat(); (mat[5][5]). Examine given code and try to
printf("Matrix\n"); understand how it works.
shwmat();
sqrmat(); Sample OUTPUT
printf("Square of Matrix\n"); Enter Value r:0, c:0 =1
shwmat(); Enter Value r:0, c:1 =1
sqrmat(); Enter Value r:0, c:2 =2
printf("\nSquare of Matrix Square\n"); Enter Value r:0, c:3 =2
Enter Value r:0, c:4 =3
shwmat(); Enter Value r:1, c:0 =3
return(0); Enter Value r:1, c:1 =4
} Enter Value r:1, c:2 =4
Enter Value r:1, c:3 =5
Enter Value r:1, c:4 =4
void entmat() Enter Value r:2, c:0 =3
{ Enter Value r:2, c:1 =2
int r,c; Enter Value r:2, c:2 =1
for (r=0;r<5;r++) Enter Value r:2, c:3 =1
Enter Value r:2, c:4 =2
for (c=0;c<5;c++) Enter Value r:3, c:0 =3
{ Enter Value r:3, c:1 =4
printf ("Enter Value "); Enter Value r:3, c:2 =5
printf ("r:%d, c:%d =",r,c); Enter Value r:3, c:3 =5
Enter Value r:3, c:4 =3
scanf ("%d",&mat[r][c]); Enter Value r:4, c:0 =2
} Enter Value r:4, c:1 =5
} Enter Value r:4, c:2 =3
Enter Value r:4, c:3 =1
Enter Value r:4, c:4 =4
void shwmat()
{ Matrix
int r,c; 1 1 2 2 3
for (r=0;r<5;r++) 3 4 4 5 4
3 2 1 1 2
{ 3 4 5 5 3
for (c=0;c<5;c++) 2 5 3 1 4
printf ("%8d",mat[r][c]);
printf("\n"); Square of Matrix
22 32 27 22 29
} 50 67 63 59 64
} 19 27 26 24 30
51 64 61 59 62
void sqrmat() 37 52 44 41 51
{ Square of Matrix Square
int r,c,x,t[5][5]; 4792 6493 5930 5507 6339
for (x=0;x<5;x++) 11024 14894 13624 12670 14550
for (r=0;r<5;r++) 4596 6215 5674 5281 6077
10784 14567 13322 12385 14225
{ 8228 11132 10164 9448 10864
t[x][r]=0;
for (c=0;c<5;c++)
t[x][r]=t[x][r]+(mat[x][c]*mat[c][r]);
}
for (r=0;r<5;r++)
for (c=0;c<5;c++)
mat[r][c]=t[r][c];
}

6. 4/5
ENG203 – Computer Programming II Prepared by Assoc.Prof.Dr. İbrahim ERŞAN

Example 5: String Processing Functions

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 lens(char *);


void revs(char *);

int main()
{
char s[100];
printf("Enter a string :");
gets(s);
printf("\nLength :%d",lens(s));
revs(s);
printf("\nReverse :%s",s);
return(0);
}

int lens(char x[])


{
int cnt=0;
while (x[cnt]!='\0')
cnt++;
return(cnt); Sample OUTPUTS
}

void revs(char x[])


{
char c;
for (int k=0;k<lens(x)/2;k++)
{
c=x[k];
x[k]=x[lens(x)-(k+1)];
x[lens(x)-(k+1)]=c;
}
}

6. 5/5
ENG203 – Computer Programming II Prepared by Assoc.Prof.Dr. İbrahim ERŞAN

ENG203
COMPUTER PROGRAMMING II

Lecture Set VII - FILES

Why we are using files & How files are stored?

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.

Syntax : FILE *pointername;

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.

Syntax : pointername = fopen (“filename”, “openingtype”);

Path and name of file that will be used

Openingtype : “r” read existing file


“w” open a new file to write (existing terminated)
“a” append to an existing file (if not exists then created)
“r+” read/write existing file
“w+” read/write new file (existing terminated)
“a+” read/append existing file (if not exists then created)

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.

Syntax : fclose (pointername);

7. 2/20
ENG203 – Computer Programming II Prepared by Assoc.Prof.Dr. İbrahim ERŞAN

Main File Operations

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,

Syntax : fprintf (pointername,“formatstring”,entry1,entry2, …);


 All kinds of data can be written to a file with a format.
fputs (“entrystring”, pointername);
 Only strings can be written to a file without formatting.
putc (‘onecharacter’,pointername);
 Only single characters can be written to a file.

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.

Example (using fprintf function):


Write a program to enter names, surnames and grades of five students from keyboard and
record these entries to a file called “student.txt”.

#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

Example (appending to end of file with fprintf function):


Write a program to append a new student with name “Belmont Jewel” and grade “86” to
existing “student.txt” file.

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

Example (using fputs function):


30 characters reserved because of %-30s
Repeat previous example using fputs command.
+1 space given in format
Instead of :
fprintf(fp,"%-30s %-30s %d\n","Belmont","Jewel",86);

write :
fputs("Belmont Jewel 86\n",fp);

31 Characters 31 Characters

Example (using fputs function):


Write a program that whatever you entered from keyboard will be recorded to a file. When a
single ‘#” character is pressed, program will exit.
#include <stdio.h>
#include <string.h> User entry will be compared with “#”
int main () symbol in order to stop writing to the
{
file. In order to compare we need to use
char zzx[300];
FILE *abc; strcmp function, that’s why “string.h”
printf ("Enter Strings\n"); library is included.
abc=fopen("pr.txt","a");
do We don’t know how many letters will be
{
entered by user in each entry so, we just
gets(zzx);
if (strcmp(zzx,"#")!=0) give an approximate maximum value as
{ 300 characters.
fputs(zzx,abc);
fputs("\n",abc); Exercise: Repeat the same example but,
} locate every single key-press to file until
} “escape” key is pressed.
while (strcmp(zzx,"#")!=0);
fclose(abc); Hint: In order to detect “escape” key,
return(0); you will need the ASCII code of it, which
} is 27.

7. 4/20
ENG203 – Computer Programming II Prepared by Assoc.Prof.Dr. İbrahim ERŞAN

Example (using putc function):


Write a program that will enter a string from keyboard and write it to a file called “reverse.txt” in
reverse order using putc command.

#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
}

Example (using putc function):


Write a program that will enter a string from keyboard and write it to a file called “pattern.txt”
with following pattern using putc command.

e.g. Entry : MOUSE #include <stdio.h>


Pattern :M #include <string.h>
MO int main()
MOU {
char s[30];
MOUS
int r,k;
MOUSE FILE *fp;
printf ("Enter a string :");
scanf ("%s",s);
Same example is solved in Lecture Set 0, fp=fopen("pattern.txt","w");
for (r=0;r<strlen(s);r++)
but pattern was output on screen, here
{
we’re locating the pattern in a file. for (k=0;k<=r;k++)
putc(s[k],fp);
Exercise: Solve the same example with a putc('\n',fp);
different pattern, as shown below, }
fclose(fp);
printf("File Recorded");
Entry : MOUSE return(0);
Pattern : E }
SE
USE
OUSE
MOUSE

7. 5/20
ENG203 – Computer Programming II Prepared by Assoc.Prof.Dr. İbrahim ERŞAN

Example (a complete task about writing to a file):


Write a program that will enter records of students to a file called “recs.txt”. Name, surname
and mark (as float) of a student will be recorded to file. Maximum length for name and
surname is 30 characters for each.
(i) Define a structure with name student for variables of student.
(ii) Write a function with name entry, which performs record entry from keyboard and
returns entered values.
(iii) Write a function with name check, that will check if name or surname is greater than 30
characters and, if mark is not between 0 and 100. If so, it will write a message and return 0,
otherwise it will return 1. This function takes student data that will be checked, as parameter.
(iv) Write a function with name save, in order to record entered values to file. This function
takes student data that will be recorded to file, as parameter.
(v) Write a function with name confirmation. This function takes an integer parameter and
with respect to the value of parameter it performs two tasks. Either it will ask if user wants to
exit from program or it will ask if user wants to save entered record. For both cases if answer
of user is YES it will return 1, otherwise it will return 0.
#include <stdio.h>
#include <string.h>
#include <conio.h> In solution “conio.h” library is used. The
reason for this library is getch()
struct student command. Simply, this command waits
{
char name[100];
for a single character entry from
char sname[100]; keyboard and after user presses a key,
float mark; this key is returned back. So, if we write
}; such a code,
char x;
student entry ()
x=getch();
{
student x; Program waits for a keypress from
printf("\n\nEnter Name :"); keyboard and whatever user presses, it is
scanf("%s",x.name); assigned to x. Note that, there is no need
printf("Enter Surname :"); to press enter after character entry with
scanf("%s",x.sname); getch() command.
printf("Enter Mark :");
scanf("%f",&x.mark);
return(x); In our code getch() is used inside switch
} statement so, entered character will
return into switch as parameter.
int confirmation(int sw)
{
if (sw==0)
printf("\nDo you want to record this entry (Y/N)?");
if (sw==1)
printf("\n\nDo you want to continue (Y/N)?");
switch(getch())
{
case 'Y':
case 'y': return(1);
default : return(0);
}
}

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

Reading from a File

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,

Syntax: fscanf (pointername,“formatstring”,variable1,variable2, …);

 All kinds of data can be read from a file with a format.


Data taken from file with fscanf, are assigned to variables
according to determined format.
Exactly the same as scanf function. The only difference is that, instead of taking data from
keyboard, it takes data from file. Synactically the only difference is the first parameter
which must be given as the file pointer of file that will be used.
e.g. char n[31];
int a;
fscanf (fp,”%30s%d”,n,&a);

Syntax: fgets (variable, number of characters, pointername);


 Only strings can be read without a format.
Number of characters must be determined to read that
much character from file into variable.
Exactly same as gets function. The only difference is that, instead of taking data from
keyboard, it takes data from file. Syntactically it is a bit different, it takes three
parameters. The first parameter is the character array that will be used to store data
which is taken from file. The second parameter is the number of bytes that will be taken
from file. The last parameter is the file pointer of file that will be used.
e.g. char z[51];
fgets(z,50,fp);

Syntax: variable = getc (pointername);


 Only one character can be read.
It is a useful and simple function. If you want to read a file character by character getc
function is handy. It takes only file pointer as parameter and returns a character (which is
taken from file) back.
e.g. char k;
k=getc(fp);

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

IMPORTANT DETAIL about READING DATA FROM FILE

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

Example (using fscanf function):


We have a text file with name “f.txt” as follows. Names, Surnames and Grades of students are
located in file as records. 30 characters reserved for name and surname (seperately), and
remaining part of the record is used to keep grade of student. It is assumed that, there are 20
records (in other words 20 students) in this file (Full file can be found at the end of the lecture
set, so you can copy and paste, but be sure about reserving 30 characters).
f.txt
Anejo Highball 67
20 Records
Sherry Adonis 38
Arnold Palmer 79

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

Example (using fscanf and reading all records):


Use same file (from previous example, f.txt) to read all records and assign them into three
arrays, then show contents of arrays on screen as formatted in file.

#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

Example (using fgets and reading all records):


Repeat the previous example with fgets statement.

#include <stdio.h> In fgets, we’re trying to get 99 characters. 30


int main () characters for name + 30 characters for surname +
{ maximum 3 characters for mark = 63 characters. Don’t
char n[20][100]; forget that fgets works as gets statement. Entry is
int r;
FILE *p; terminated with carriage return (Enter or Return Key).
p=fopen("f.txt","r"); When we jump to the next line in file, it means Return
for (r=0;r<20;r++) Key is pressed, therefore entry for fgets will be
fgets(n[r],99,p); terminated and it will get 61 or 62 or 63 characters.
fclose(p);
printf("%-30s%-30s%s\n","Name","Surname","Mark");
for (r=0;r<20;r++)
printf("%s",n[r]); Exercise: Modify given code by making some additions
return(0); to the code to print the average of class at the end of
} the list. While doing these modifications, reading from
file must be done with fgets (this part must not be
modified).

This time it will be a little tricky ;-)

Example (using getc): Example (using getc):


Read the first and fourth Take only the name of first student from file
letter from file f.txt and write f.txt character by character and print it on
themon screen. screen with one space between each character.

#include <stdio.h> #include <stdio.h>


int main () int main ()
{ {
char n; char n;
FILE *p; FILE *p;
p=fopen("f.txt","r"); p=fopen("f.txt","r");
n=getc(p); do
printf("%c",n); {
n=getc(p); n=getc(p);
n=getc(p); printf("%c ",n);
n=getc(p); }
printf("%c",n); while(n!=' ');
fclose(p); fclose(p);
return(0); return(0);
} OUTPUT } OUTPUT

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,

e.g. while ((fscanf(filepointer,"%d",&i))!=EOF) {...}

If we are using fgets function, we can test EOF by writing a condition in while-loop as,

e.g. while ((fgets(s,99,filepointer))!=NULL) {...}

If we are using getc function, we can test EOF by writing a condition in while-loop as,

e.g. while ((c=getc(filepointer))!=EOF) {...}

Notes on EOF constant:


Function that we are using to read from file (in our lecture set these functions as fscanf and
getc) returns -1 when it reaches to the end of file so instead of EOF it is possible to use -1 also.
There is no -1 ascii code (which means there is no character or control character in ASCII table
having equivalent value as -1) but it is possible to make reading function return -1 artificially by
locating a control character in a text file. When reading function reads that control character it
returns -1.

Depending on operating system, mentioned control character varies. In Windows Operating


System this control character is SUB (stands for SUBTITUDE) or Ctrl+Z or ASCII Code of 26
(which is 1A in hexadecimal). In Linux, MacOS, Android Operating Systems this control
character is EOT (stands for END OF TRANSMISSION) or Ctrl+D or ASCII Code of 04 (which is
again 04 in hexadecimal).

7. 12/20
ENG203 – Computer Programming II Prepared by Assoc.Prof.Dr. İbrahim ERŞAN

Example (using EOF constant with fscanf function):


Assume that you don’t know the number of records in file f.txt (file that we used in previous
examples). Read all records from file one by one using fscanf function and print them on
screen. Also count the total number of records and print the result on screen.

#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
}

Example (using NULL pointer with fgets function):


Repeat previous example and get same output using fgets function.

#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

Example (using EOF constant with getc function):


Repeat the same example using getc statement BUT this time count the total number of
characters in file. While counting the number of characters don’t count blank-spaces.
#include <stdio.h>
int main ()
{
char s;
int c,m;
FILE *p;
c=0;
p=fopen("f.txt","r");
while ((s=getc(p))!=EOF)
{
printf("%c",s);
if(s!=' ') c++;
}
printf("\nTotal Number of Characters :%d",c);
fclose(p);
return(0);
}

Line Break Issue

Regarding previous example, a question


may come in our minds, are we counting the
characters correctly? It is possible to check with a
simple example. Let’s create two files with name
“tiny1.txt” and “tiny2.txt” using any desired text
editor (Notepad, TextPad, Notepad++ etc.) and
arrange the content of these file as shown on right,
then save them to a folder where the source code
will also be located. Now, we are sure that there
are 10 characters in our text files and there is no
blank-space. Apply the following code to both files
seperately and check the output.
#include <stdio.h>
int main () In order to apply it to
{ “tiny2.txt” you will just
char s; change the filename
int c=0,m;
FILE *p;
p=fopen("tiny1.txt","r");
while ((s=getc(p))!=EOF)
{
printf("%c",s);
c++;
}
printf("\nNumber of Characters :%d",c);
fclose(p);
return(0);
}
7. 14/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.

- In Windows and Symbian two bytes are used, these are CR + LF


- In Unix, Linux, Android and MacOSX one byte is used, that is LF
- In MacOS and MacOSX one byte is used, that is CR

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.

● Why the size of “tiny1.txt” is 14 bytes?

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.

● Why our program counts 12 characters for “tiny1.txt”?

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 with fseek statement

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.

Syntax : fseek (pointername, n, f);


n – moves file pointer by n bytes (characters)
f – can only take three values
0: Moves to top of file
1: Stays at current location
2: Moves to end of file

Example (using fseek function):


Create a text file with name “mids.txt” and locate three
records to that file (as shown on right). After entering the last
record press Enter Key to jump to the next line and then save
the file. Assume these are student numbers and midtern
grades of students. What will happen when following code is
executed on that file. DON’T FORGET that, in order to jump to
the next line, two bytes are located to the end of each line.

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

Current Position in a File with ftell statement

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.

Syntax : ftell (pointername);

Example (using ftell function):


Modify previous example by adding ftell in printf functions after every fseek and fscanf
function in order to examine position of file pointer after execution of these statements.
#include <stdio.h>
int main () OUTPUT
{
char s[50]; If you follow the code
int m; carefully and
FILE *p; compare it with the
p=fopen("mids.txt","r");
file pointer positions
fseek(p,14,0); of previous example,
printf("%d\n",ftell(p)); you will see that, ftell
fscanf(p,"%s%d",s,&m); function gives us the
printf("%-10s%d\n",s,m); pointer positions
printf("%d\n\n",ftell(p)); shown in figure of
fseek(p,0,0);
previous example.
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,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.

Check Existence OR Accessibility of 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.

Example (using NULL pointer):


Try the following code by changing the filename in fopen statement. If you write an existing
filename you will get a message as “File exists and accessible”. If you write a nonexistent
filename the message will be “File Does NOT Exists or NOT 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

Change Name of a File with rename statement


We may need to change the name of an existing file. rename statement is used for this
purpose. It takes two string parameters, the first parameter is the current name (with path) of
file that we want to change its name and the second parameter is the new name of the file.

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

Example (using rename function):


A very simple code snippet showing a standard rename operation
#include <stdio.h>
int main ()
{
int k;
k=rename("mids.txt","fins.txt");
if (k==0)
printf("Filename changed successfully");
else
printf("Rename operation could NOT be completed");
return(0);
}

Delete a File with remove statement


We may need to delete an existing file. remove statement is used for this purpose. It takes one
string parameter, which is the name (with path) of file that we want to delete.
Syntax: remove(“Filename”);

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

Example (using remove function):


A very simple code snippet showing a standard remove operation
#include <stdio.h>
int main ()
{
int k;
k=remove("mids.txt");
if (k==0)
printf("File deleted successfully");
else
printf("Delete operation could NOT be completed");
return(0);
}
7. 19/20
ENG203 – Computer Programming II Prepared by Assoc.Prof.Dr. İbrahim ERŞAN

APPENDIX of LECTURE SET 7

Content of F.TXT file that is used in some examples


Anejo Highball 67
Sherry Adonis 38
Arnold Palmer 79
Bramble Gin 46
Shandy Beer 64
Belmont Jewel 78
Danny Ocean 56
Cape Codder 69
Harvey Wallbanger 92
Margarita Hpnotiq 86
Jean Harlow 85
Rita Onrocks 74
Juan Collins 61
Mamie Taylor 81
Poinsettia Punch 49
Rose Berrybliss 72
Sabai Sabai 38
Vieux Carre 94
Velvet Hammer 59
Yaka Hula 77

30 30 3
63 Characters

7. 20/20

You might also like