You are on page 1of 22

St.

Joseph's College Notes for Programming Language C

r Lecture I
Objectives:
What is a program?
Why need programs?
The programming step
Introduction to C programming
What is a program?
A program is a set of computer instructions that direct the computer to operate according
to the sequence of the instructions.
A program mimics the ways that human beings work:
- sequence
- looping
- decision
Why needs programs?
- more reliable
- free people from routine work
- computer is more efficient in performing certain tasks.
The programming steps
- develop the algorithm for the task
Algorithm: is set of steps designed for solving a problem.
Stepwise refinement: is to express a routine with a step by step description.
For example,
1. Receive borrow book request from borrower.
2. Process book borrow request.
2.1 Chek borrowers’ ID is in registration.
2.2 Check book’s ID is in library.
2.3 If both OK, record down the borrower’s ID and book’s call number.
3. repeat step 1 until library closed.
- coding : is the process of transforming the requirement or algorithm into suitable
programming languages.
For example,
Algorithm in stepwise refinement:
1. read in a character.
2. if the character is ‘y’ or ‘Y’, then output ‘ok’ and repeat step 1.
3. if the character is ‘n’ or ‘N’, then output ‘bye’.
The corresponding C program for the above stepwise refinement:
#include <stdio.h>
#include <stdlib.h>
main( )
{ char c;
c=' ';
while (1)
{
if (c != '\n')
printf("Read in a character");
c = getchar( );
if ((c=='y') || (c=='Y'))
printf("ok");
if ((c=='n') || (c=='N'))
{
printf("bye");

Computer Studies Page 1


St. Joseph's College Notes for Programming Language C

exit(0);
}
}
}
- compiling : translating the source code into object code.
- linking : link different program modules and resolve the memory addresses to form an
executable code.
- loading : load the executable code into available free space and adjust the address.
- running : execute the programs.
- test and debug : test the program if they follow what we expected. Debug is to correct
any program errors in the program.
The program may contain errors.
Three major types of errors:
1. Syntax Error
Due to not following the grammer of programming language.
2. Semantic Error
Due to the program not conforming the requirment logic.
3. Run-time Error
Error discovered during run-time. For example, divide by zero.
- syntax error can be easily detected by compiler while the semantic error is more
difficult to correct.
- test plan should be carefully drafted to make sure the system behave as the users’
request.
- test cases can be generated by computer or input by users. Test cases can be either real
life or artificial.
Debugging Tools include:
- screen/file dump
- integrated debugging tools
* program trace step/procedure
* set watches/breakpoint
* browse the content of register/CPU/RAM
Introduction to C programming
+ Strengths of C
Small Size (A top-quality C compiler operate in only 256K of total memory)
Language Command Set is small
Original C language contain a mere 27 keywords
ANSI C stnadard has an additional 5 reserved words
Borland C++ added 45 more keywords
C provides a rich set of library functions for input/output, arithmetic operations and
string manipulation
Speed close to assembly language equivalents
Not strongly typed
A structured language
for-loop, if, if-else, case (switch) statements, while loops, local variables and call-by-
value
C supports the concept of separate compilation and linking (Support of Modular
Programming)
Easy interface to Assembly Language Routines
Bit Manipulation
Pointer Variables
Flexible Structures : Multidimensional arrangements are built from combinations of
one-dimensional arrays
Memory Efficiency : the lack of built-in functions saves programs from unnecessary
codes
Portability
Special Function Libraries : available : graphics and database, screen windowing,
communications.

Computer Studies Page 2


St. Joseph's College Notes for Programming Language C

+ Weaknesses of C
Not Strongly Typed
Side effect of unexpected change to a variable
Lack of Run-Time Checking
+ Spirit of C
Trust the programmer
Don’t prevent programmer from doing what needs to be done
Keep the language small and simple
+ Preprocessor Directive
- All preprocessor directives start with ‘#’
- Preprocessor directive allows programmer to include files or define constant /
expression / functions before the actual compilation takes place.
- The available preprocessor directives are:
#include
#define
- #include allows programmers to include content of another file into the current
program content.
+ Header File
The file extension is “.h” means header file.
Header files can be user-defined or system-defined.
The content of header files contains definition of some predefined constant /
expression / functions.
System-defined header files are constant / expression defined by the C compiler for
library reference.
User-defined header files are constant / functions / expression defined by users.
Header files promote standardization of constant / expression names.
If the header files are resided in system directory, they can be quoted with bracket.
For example,
#include <dos.h>
If the header files are resided in user directory, they can be double quoted.
For example,
#include “c:\user\header\myfile.h”
The most often used system-defined header files are:
- dos.h
- string.h
- stdio.h
- math.h
- graphics.h
- stdlib.h
- float.h

- #define allows programmers to relate symbols with constant or expression within the
program.
For example,
#define MAX_LINE 1000
#define MAX_USER 200
#define SQR(X) X*X

- main( )
Denote the main program. All programs start here.
For example,
#include <stdio.h>
#include <stdlib.h>
main( )
{
.....
}

Computer Studies Page 3


St. Joseph's College Notes for Programming Language C

- return (keyword)
Exits immediately from the currently executing function to the calling routine,
optionally returning a value.
Syntax
return [ <expression> ] ;
The C function complete and return to the caller function.
For example,
main( )
{
...
funcP(A);
}

...
char funcP (char *s)
{
...
return;
}
Note: return can also return a value.
For example
double sqr(double x)
{
return (x*x);
}

- Data Type
All data in C belong to a data type.
C language has a rich set of data types.
The most common data types are:
* integer
* char
* float : single-precision floating point
* double : double-precision floating point
* short : 16-bits integer
* long : 32-bits integer
* unsigned
Other more complicated data types are:
* array
* structure
* pointer
* file
Each data type has a size limit:
Type Length Range
unsigned char 8 bits 0 to 255
char 8 bits -128 to 127
enum 16 bits -32,768 to 32,767
unsigned int 16 bits 0 to 65,535
short int 16 bits -32,768 to 32,767
int 16 bits -32,768 to 32,767
unsigned long 32 bits 0 to 4,294,967,295
long 32 bits -2,147,483,648 to 2,147,483,647
float 32 bits 3.4 * (10**-38) to 3.4 * (10**+38)
double 64 bits 1.7 * (10**-308) to 1.7 * (10**+308)
long double 80 bits 3.4 * (10**-4932) to 1.1 * (10**+4932)

Computer Studies Page 4


St. Joseph's College Notes for Programming Language C

- Constants
Constants are used for denoting some values which will not be changed during
program execution.
long constant : terminated by "l" or "L"
unsigned long : terminated by "ul" or "UL"
float : terminated by "f" or "F"
octal : leading zero "0"
hexadecimal : leading "0x" or "0X"
character constant : enclosed by single quotes
For example,
numeric constant : 3444 45 4.5 455e34 0222 0xabc
character constant : ‘a’ ‘b’ ‘c’ (use ‘ ’)
string literal : enclosed by double quotes
string constant : “this is a boy” (use “ ”)
We can define symbol to represent constant.
enumeration constant : the first name in an enum has value 0, the next 1, and so on
e.g. enum boolean { NO, YES };
enum modes { LASTMODE = -1, BW40=0, C40, BW80, C80, MONO = 7 };
/*
"modes" is the type tag.
"LASTMODE", "BW40", "C40", etc. are the constant names.
The value of C40 is 1 (BW40 + 1); BW80 = 2 (C40 + 1), etc.
*/
constant expression evaluated during compilation rather than run-time
For example,
#define MAXLINE 1000
#define pi 3.14

- Variables
Variables are main memory storage for holding data values.
Variables are used to represent an object, for example:
AMY_SCORE, CAR_NO are variables denoting the score of Amy and car number.
Naming convention:
* allow characters: alpha-numeric / underscore.
* first character should be alphabetic / underscore.
* case-sensitive
Examples for valid variable names:
A
A1
_1
_a
A_1
Examples for invalid variable names:
1a
a!
a 3

- Declaration
variable declarations
e.g. int x, y, z; char ch, line[80];
variable declaration with an initializer
e.g. char esc = '\\'; int i = 0; int limit = MAXINT + 1; float x = 1.0e-5;
constant declarations
e.g. const double e = 2.71828182845905;
const char msg[ ] = "warning: ";

- /*.....*/
The pairs /* */ is for bracketing comment.

Computer Studies Page 5


St. Joseph's College Notes for Programming Language C

For example,
/* This program is for calculating personal tax */
The C compiler will ignore those comment.
They are not part of the executable code.
Comment is important for documenting the program, eg. the function, special
algorithm taken, the author, the written date etc.
Comment make the programs more readable.
- //
For single line comment, use // is more convenience.
For example,
c:=a+b; // c is sum of a and b
// effect from here to end of line

- statement terminator (;)


C program is composed of statements.
Each statement is the smallest indivisable instruction meaning to a computer just like
a sentence in English grammar.
Each statement is terminated with ‘;’.

- {.....}
for grouping a set of statements as a compound statement.
The compound statment is treated as a unit.
For example,
{
a=1;
b=3;
}
It also used for defining the start and end of subroutine.

- simple I/O function


*printf(.....)
printf is a system-defined function.
Output constant string or character to monitor.
For example,
printf(“hello”);
Output formatted string to monitor.
For example,
printf(“His name is %s”,boyname);
%s is replaced by the content of string variable boyname.
There are other place holders for other data type:
%s string
%d decimal
%c character
%f float
Special notation for non-printable characters.
All those special characters start with ‘\’.
For example,
\n newline
\t horizontal tab
\0 null character or string terminator.
\a alert [bell] character
\b backspace
\f formfeed
\r arriage return
\v vertical tab
\\ backslash
\? question mark
\' single quote

Computer Studies Page 6


St. Joseph's College Notes for Programming Language C

\" double quote


\000 octal number
\xhh hexadecimal number

- getchar( )
get a character from the standard input keyboard and return the values.
For example,
c=getchar( );
The getchar( ) function will get a value from the keyboard and assign to variable c.

- Assignment statement =
Put the value from the left side to variable on the right.
For example,
c=1;
d=c;
Both c and d contain same value 1.
Note: Assignment operator is destructive:
means the old value of the variable will be destroyed and replaced by the value of
the left side.
The left side of the assignment statement must be a variable.

r Lecture II
Objectives:
- Variation of assignment statement.
- Arithmetic and logic operators and their precedence.
- Conditional statements: if...else, switch.
- looping structures: for, while, do , break and continue.
- Classwork
Variation of assignment statement
- Simple assignment
For example,
a=4;
a=5;
- Multiple assignment
For example,
a=b=c=d=4;
variables a,b,c,d will be assigned with the same value 4.
- Initialised the variables
You can initialised the variable during declaration.
For example,
int c=4,b=5;
b and c will be initialised with values 4 and 5.
Arithmetic and logic operators and their precedence
Arithmetic operators:
addition +
substraction -
multiplication *
integer/float division / (quotient)
integer division % (remainder)
unary positive +n
unary negative -n (where n is a no.)
For example,

Computer Studies Page 7


St. Joseph's College Notes for Programming Language C

m=4;
n=3;
m=m+n;
m=m-n;
m=m*n;
m=m/n;
m=m%n;
Other variation of arithmetic operators:
m+=n equivalent to m=m+n;
m-=n equivalent to m=m-n;
m*=n equivalent to m=m*n;
m/=n equivalent to m=m/n;
m%=n equivalent to m=m%n;

Some special arithmetic operators:


m++;
++m; increment the value of m by 1.
n--;
--n; decrement the value of n by 1.
m=++n; increment the value of n by 1 before assigning to m.
m=--n; decrement the value of n by 1 before assigning to m.
m=n++; assigning the value of n to m before incrementing n.
m=n--; assigning the value of n to m before decrementing n.

Precedence level of arithmetic operators:


The arithmetic operators follow the rule multiplication and division come before
addition and subtraction.
Relational operators:
Compare the left value with the right.
== equal to
!= not equal
< less than
> greater than
<= less than or equal to
>= greater than or equal to
For example,
3==5 false
3!=3 false
a>b truth value depend on a and b’s value
m+n >= 3%2 truth value depend on m and n’s value
Logical operators:
&& Logical ‘AND’ operator
|| Logical ‘OR’ operator
! Logical ‘Not’operator
Example,
!((c>d) && (a<c))
(a!=b) || (b>2*n)
The truth value of the above expressions depend on the values of a,b,c.
Truth Table for ‘AND’
X Y X&&Y
T T T
T F F
F T F
F F F
Truth table for ‘OR’
X Y X||Y
T T T
T F T

Computer Studies Page 8


St. Joseph's College Notes for Programming Language C

F T T
F F F
Truth table for ‘Not’
X !X
T F
F T

Precedence
Precedence refers to the priority of the operator in evaluation.
Below is a priority list:
( ) function call/bracket
[] array element reference
-> pointer to structure member reference
. structure member reference
- unary minus
+ unary addition
++ increment
-- decrement
! logical negation
~ one’s complement
* address
sizeof size of an object
(type) type cast (coercion)
* multiplication
/ division
% modulus
+ addition
- subtraction
<< left shift a bit
>> right shift a bit
< less than
<= less than or equal
> greater than
>= greater than or equal
== equal
!= not equal
& bitwise AND
^ bitwise exclusive OR
| bitwise OR
&& logical AND
|| logical OR
?: conditional expression
= assignment operator
*=, /=, %=
+=, -=, &=
^=, |=
<<=, >>=

Operator Associativity
( ) [ ] -> . left to right
! - ++ -- - (type) * & sizeof right to left
* / % left to right
+ - left to right
<< >> left to right
< <= > >= left to right
== != left to right
& left to right

Computer Studies Page 9


St. Joseph's College Notes for Programming Language C

^ left to right
| left to right
&& left to right
|| left to right
?: right to left
= += -= etc. right to left

Explicit type conversions can be forced. It is called "coerced" or "cast".


e.g. sqrt ( ( double ) n )
the integer n is coerced into a double value before the function sqrt acts on it.

Order of evaluation
The precedence of the bitwise logical operators &, ^ and | falls below = = and ! =.
e.g. if ( ( x & MASK ) = = 0 )
the expression x & MASK must be fully parenthesized.
However, all relational operators have a greater precedence than logical operators,
thus no extra parenthese is needed for the following boolean expression.
e.g. (ch >= 'a' && ch <= 'z' || ch >= 'A' && ch <= 'Z')
More attention should be paid on expressions involving one of the associative and
commutative operators (+, *, &, ^, | ),
e.g. x = f( ) + g( )
f( ) may be evaluated before g( ) or vice versa, thus if either f( ) or g( ) alters an external
variable that the other depends on, x can depend on the order of evaluation.

The conditional statement


- If (condition)
action 1;
else
action 2;
If condition is true then action 1 else action 2.
For example,
if ((A>B) && (D<E))
i=3;
else
{
i=4;
j=5;
}
Note that the whole condition part should be bracketed.
There may be an ambiguity in the following example,
if ( n > 0 )
if (a > b)
z = a;
else
z = b;
because if wrong indentation is used, the else may be considered to go with the
outer if. If the else is really used for the outer if, the following program segment
should be used.
if ( n > 0 ) {
if (a > b)
z = a;
}
else
z = b;
- Switch (n)
{
case 1: printf(“single”);

Computer Studies Page 10


St. Joseph's College Notes for Programming Language C

case 2: printf(“married”);
case 3: printf(“divorced”);
default: printf(“single”);
printf(“ok”);
}
Another more simple conditional statement is
SWITCH statement.
Whenever the variable n match the conditional value, the path will be executed.
Note
- The switch body should be bracketed to define the effect of switch statement.
- There can be more than one statement in each conditional path.
- The matching continue even if successful match. If you want to stop the matching
after successful match, use BREAK statement.

The looping statement


Loop statement allows us to execute a set of statements repetitively.
There are three kinds of looping statements:
- while loop
- for loop
- do...while loop
They have different conditions to exit the loop.
- While loop provides the simplest way of doing repetitive job whenever the condition
part is true.
For example,
while (i<20)
{
printf(“%d\n”,i);
i++;
}
Note
- the execution may not execute at all depending on the value of i before entering the
loop.
- For loop
For loop is similar to while loop except it allows you to specify:
* the pre-condition
* condition for looping and
* the post-action
Each of the above parts is separated by “;”.
For example,
pre-cond. condition for loop post-action
for (i=0,j=0 ;(i<10) && (j<20) ;i++,j++)
printf(“%d”,i+j);
Before the loop is executed, both i, j set to 0.
(i<10) && (j<20) is the condition for the loop to be executed.
i++,j++ are the post actions to be executed after each loop.
You can omit the pre-condition, ending condition and the post-action.
For example,
for (;;)
printf(“A”);
But this will cause INFINITE loop !!!!
- do...while loop
Do...while loop provides an alternative for while loop.
Feature: must execute at least once.
For example,
do {
printf(“%d”,i);
i++;
} while (i<10);

Computer Studies Page 11


St. Joseph's College Notes for Programming Language C

The loop will be executed at least once no matter the initial value of i.
- break
The break statement will cause the exit of switch and loop structure.
for (i=0,k=2;i<20;i++,j++)
{
k-=1;
if (k<0)
break;
printf(“%d”,k);
}
The loop terminated for i<20 or k<0, depending on which case occured first.
Switch (a)
{
case 1: printf(“man”);break;
case 2: printf(“woman”);break;
case 3: printf(“boy”);break;
case 4: printf(“girl”);break;
default: printf(“human”);break;
}
Note if without break statement, all case statement will be checked.
- Continue statement
The continue statement complement the break statement.
The continue statement is used for loop and not for switch.
Whenever encounter the loop statement, the control flow is transferred back to the
condition
statement.
For example,
while (i>0)
{
k+=i;
if (k>20)
continue;
i--;
}
if k>20 then i-- statement will be ignored and the flow is back to checking for I>0.
Classwork
1. Use while-loop, print Celsius-Fahrenheit table for celsius = 0, 20, ..., 300. [Hint :
fahrenheit = (9 x celsius) / 5 + 32]
2. Use for-loop, print Fahrenheit-Celsius table for celsius = 0, 20, ..., 300.
3. Use the function scanf to get in an input integer n. Convert the input integer n
into a string with leading sign. (i.e. 78 convert to +78, -90 convert to -90).

Computer Studies Page 12


St. Joseph's College Notes for Programming Language C

r Lecture III Array


Objectives:
- What is array?
- More about array
- Array and loop

III.1 What is array?


- Array is a data type.
- Array is for storing a set of data with same data type.
- Each element in the array is referenced by the index.
- Declaration of array using square bracket.
For example,
int stdmrk[10];
The above declaration allocate ten slots.
Each slot can store an integer.
You can imagine an array as a list of boxes.
Each box is referenced by an index.
43 44 78 45 23 45 89 95 67 56
0 1 2 3 4 5 6 7 8 9
Note that the index number start from 0.
III.2 More about array
- you can initialise an array during declaration
For example,
int a[4]={1,2,3,4};
The effect is as follow:
array a
1 2 3 4
- Multi-dimensional array
Dimension refers to the number of reference index required to identify an element in the
array.
One dimensional array is called linear array.
Example for one dimensional array,
int stdmrk[40];
40 student marks for a class.
If more than one index is required is called multi-dimensional array.
Example for multi-dimensional array,
int stdmrk[2][4];
represents 2 classes with each class 4 students.
For initialising,
int stdmrk[2][4]={{1,3,2,4},{3,4,5,6}}
For the general multi-dimensional array of the form a[n][m][r], the total number of
elements is n x m x r.
Care must be taken not to assign value that exit the array size.
For example,
int stdmrk[5];
stdmrk[5]=3;
This type of errors may make the computer hang up.
III.3 Array and loop
- Array and loop has close relationship.
For initialising stdmrk[3][5],
stdmrk[0][0]=70;
stdmrk[0][1]=70;
stdmrk[0][2]=70;

Computer Studies Page 13


St. Joseph's College Notes for Programming Language C

.
.
stdmrk[2][2]=80;
stdmrk[2][3]=80;
stdmrk[2][4]=80;
For example, the above initialisation of array can be simplified by using loop,
for (i=0,j=0;(i<=2)&&(j<=4);i++,j++)
a[i][j]=70+i*10;

r Lecture IV
Pointer and String

What is pointer and its uses?


C subroutines for manipulating string
IV.1 What is pointer and its uses?
- Pointer is physically a variable contains the address of another variable, but logically, it
can be imagined as an arrow pointing to the variable.
- Each pointer has a data type which should be the same to that variable it pointed at.
- Pointer declaration is done by prefixing the variable name by ‘*’.
char *charpt;
int *intpt;
float *floatpt;
- The address operator (&)
char a,*b;
b=&a; //the pointer b is assigned a’s address
- The dereferencing operator (*)
char a,*b;
b=&a;
*b=‘c’; //the variable that pointed by b is assigned
// with value ‘c’.
// this statement is equivalent to a=‘c’
- Uses of pointer is usually for referencing the element of an array. Therefore, array name
itself is a pointer.
for example,
char c[10], *b;
b=c; //b is set to point at head of c
b++; //b is moved to second element of c
(*b)++; //2nd element of c is incremented by 1
IV.2 C subroutines for manipulating string
- A string is a sequence of characters ended with a string terminator.
- A string terminator is denoted by ‘\0’ (null character)
- A constant string is double quoted.
For example,
“he is a boy”
- String in C is usually declared as array of character.
For example,
char d[20]=“This is a string”;
- C provides a set of useful string function
The “string.h” should be included.
* strcpy
* strncpy
* strlen
* strcmp
* strncmp
* strcat
* strncat

Computer Studies Page 14


St. Joseph's College Notes for Programming Language C

* atoi
* atol
* atof
For atoi and atol, “stdlib.h” should be included.
For atof, one more header file “math.h” included.
char *strcpy(char *destin, char *source)
Return destin+strlen(source)
strcpy copies a string from source to target and add a string terminator at the end of
target string.
The target string should be large enough to hold the source string plus a string
terminator.
For example,
char ss[20]=“He is a boy”,ts[30];
strcpy(ts,ss); // ts contains “He is a boy”
char *strncpy(char *destin, char *source, int maxlen)
Return destin.
strncpy copies exactly maxlen characters from source into destination.
The target string might not be null-terminated if length of source is maxlen or more.
For example,
char ts[20],ss[20]=“He is a boy”;
int slen;
strncpy(ts,ss,10); //ts contains “He is a bo”
unsigned strlen(char *str)
Return the number of characters in str, not counting the null character.
strlen calculates the length of string
strlen returns the length of the string.
For example,
int stringlen;
char ss[20]=“He is a boy”;
printf(“ss length is %d”, strlen(ss));
int strcmp(char *str1, char *str2)
Returns <0 if str1 is less than str2;
=0 if str1 is equal to str2;
>0 is str1 is greater than str2.
strcmp comp ares str1 with str2.
For example,
char str1[20],str[20];
if (strcmp(str1,str2))
printf(“they are different”);
int strncmp(char *str1,*str2, int n)
Return <0 if first n characters of str1 < str2;
=0 if first n characters str 1 = str2;
>0 if first n characters str1 > str2.
strncmp compares the first n characters of str1 with str2.
For example,
int n=10;
char str1[20],str2[20];
if (strncmp(str1,str2,n))
printf(“The first 10 characters are different”);
char *strcat(char *destin, char *source)
Return a string which is equivalent to appending source to the end of destin.
strcat
concatenates the destin and source by appending source to the end of destin string.
For example,
char str1[20]=“I am”,str2[20]=“ a boy”;
printf(strcat(str1,str2)); // output “I am a boy”
char *strncat(char *str1, char *str2, int n);

Computer Studies Page 15


St. Joseph's College Notes for Programming Language C

Returns a string by appending n characters of str2 to the end of str1 and append a null
character at the end.
strncat
concatenates n characters from str2 to str1 and append a null character at the end.
For example,
int n=5;
char str1[20]=“I am”, str2[20]=“a boy”;
printf(strncat(str1,str2,n)); //output “I ama boy”
int atoi(char *nptr)
Return the 0 if the input string cannot be converted into integer; an integer if the input
string can be converted into integer.
For example,
int a=5,b=4;
char s[10]=“ 121”;
b=a+atoi(s);
printf(“%d”,b); // b is now 126
long atol(char *nptr)
Return the 0 if the input string cannot be converted into long; an long if the input string
can be converted into long.
For example,
long a=5,b=4;
char s[10]=“ 121”;
b=a+atol(s);
printf(“%d”,b); // b is now 126
double atof(char *nptr)
Return the 0 if the input string cannot be converted into floating number; an double if the
input string can be converted into double.
For example,
double a=5,b=4;
char s[10]=“ 121”;
b=a+atof(s);
printf(“%d”,b); // b is now 126

r Lecture V
Functions and storage classes
Why needs functions?
How to define functions?
Why need different storage classes and their characteristics?
V.1 Why needs functions?
- A powerful problem solving method is partition.
- A large problem can be partition into smaller manageable unit of problem.
- The manageable unit is more easier to be solved.
- Function implement the same concept of solving the smaller manageable unit.
Advantages of using functions:
- avoid duplicate code
- easier to code and more readable
- easier to debug
- logic more clear
V.2 How to define functions?
- Function declaration includes:
* function return data type
* function name
* function parameter list
- function data type

Computer Studies Page 16


St. Joseph's College Notes for Programming Language C

A function after execution should return a value of the designated data type to the main
program.
If no value need to be returned, using void.
- function name
A function should be called using its name.
When the program body reference the name of the function name, it is identical to execute
the statements inside the function.
- function parameter list
A function should take in value for processing.
The parameter list act as an interface between the function and the program body that
call it.
The value/variable passed in should match the parameter list data type.
For example,
int caltax(int salary, int bonus)
{
return ((salary+bonus)*0.1);
}
main( )
{
int a=10000,b=2000;
printf(“The tax is %d”,caltax(a,b));
}
* The function name is caltax.
* The return data type is integer.
* The formal parameter is salary and bonus.
* The actual parameter is a and b. The value of salary and bonus is replaced by salary
and bonus.
- Two ways of parameter passing
* passed by value
* passed by reference
The default way of passing parameter is passed by value in C.
- Passed by value
Only the value of the variable is passed into the actual parameter. The function itself
cannot alter the value of the variable passed in.
For example,
main( )
{
int a;
a=5;
functionA(a);
printf(“%d”, a); //still display 5
}
void functionA(int b)
{
b=4;
}
- Passed by reference
The address of the variables are passed into the function. The function can use this
address to modify the content of that variable.
For example,
main( )
{
int a;
a=5;
functionA(&a); //pass the address of variable a
printf(“%d”, a); //display 4 instead of 5
}
void functionA(int *b)

Computer Studies Page 17


St. Joseph's College Notes for Programming Language C

{
*b=4;
}
One of the uses of pointer is for passed by reference.
The default mode for parameter passing is passed by value.
The only way we can alter the variable passed in is through the pointer access to
access the variable.
V.3 Storage classes
- Variable scope
The scope of the variable refers to the effect or visibility region of that variable within the
program.
There are two types of variables classified by their scope:
* Global variables
* Local variables
- Global variables
The global variable is declared before any functions, even the main().
Global variables are visible at any where within the C programs.
Global variable is very convenience for accessing but it also creates a problem of
debugging the program
It is difficult to trace which program part alter the content of that global variable,
especially when the program size is large.
For example,
#include <stdio.h>
#include <stdlib.h>
#define MAXLINE 10
int a,b; //Global variables
main( )
{
......
a=3; //refer to global ‘a’
}
int functionA( )
{
.....
b=3; //refer to global ‘b’
}
- Local variable
As global variables creates debugging problem, we should better limit the scope of that
variable.
One way of limiting the scope is through the declaration of local variables.
Local variables are declared at the beginning of a function and is only visible within the
function.
If the local variable names are the same as the global one, the global one will be ignored.
Thus, local variables eliminates the possibility of modifying the global variable
accidentally even with the same global variable name.
For example,
#include <stdio.h>
#include <stdlib.h>
#define MAXLINE 10
int a,b; //Global variables
main( )
{
......
a=3; //refer to global ‘a’
b=8; //refer to global ‘b’
printf(“%d”,b); //output 8
}
int functionA( )

Computer Studies Page 18


St. Joseph's College Notes for Programming Language C

{
int b; // local variable b
.....
b=3; //refer to local ‘b’
// This assignment statement affect local
// but not global variable ‘b’
}
- Local variable are further divided into:
* Auto
* Static
They are different for the life span between the same function call for several time.
- Auto
Auto is the default mode for local variable.
That means the life span of that local variable is within the life span of that function.
After the function is executed, the auto mode local variables will be destroyed.
For example,
int functionA( )
{
auto int i;
printf(“%d”,i);
i=3;
}
When the functionA is first called, the auto variable i is set to 3. If the functionA is called
for second time, the value of the variable i may not be 3.
- Static
Local static variable will retain the value of the previous function call for next call.
The static variable will reside in the memory even after the function call.
int functionA( )
{
static int i; // variable i is made static in the memory
printf(“%d”,i);
i:=3;
}
For the first time to call functionA, output may be arbitrary number.
For the second time to call functionA, output must be 3. The previous value will be
retained after the functionA finished.
- Extern
A C program may be divided into partition called modules.
We can group several modules inside different program files.
Each program files can be separately compiled.
Different compiled program files are linked together to form an executable program.
Separate compilation saves time for compiling a small program file must be faster than a
large single program.
If the variables are defined in another program file but need to reference in this program
file, it should be declared as extern.
For examp le,
#include <iostream.h>
extern int i; // variable i is declared in somewhere
// else. This i occupies the same
// memory space as in the original i
// declared in other progrom file.
if i is not declared as extern, it will cause double declaration compilation error.

Computer Studies Page 19


St. Joseph's College Notes for Programming Language C

r Lecture VI
Files and Structures
Files uses and declaration
What is structure and its uses?
VI.1 File uses and declaration
- Files can be view as a sequence of related data with same type.
- Files are used for storing data of unlimited size theoretically.
- Files enable to store data permantely on external storage, i.e. disk.
- C supports files access in
* sequence mode
* random access mode
- Files variables are declared as a file pointer using the reserved word “FILE” which must
be in upper case.
For example,
FILE *myfile;
- C functions for handling files
* fopen
* fclose
* feof
* fscanf
* getc
* putc
* fputs
* fgets
* ftell
* fseek
- File *fopen(char *filename, char *type);
File names are divided into:
* Physical file name
The actual physical names found in disk.
eg. stddet.96
* Logical file name
The logical meaning file names are those
names reference in C program.
eg. student_detail_file_96
fopen allow us to bind the logical file name with that physical one.
For example,
FILE *student_detail_96;
student_detail_96 = fopen(“stddet.96”,”r”);
Using logical file name is more convenience in the program.
As you can bind different physical file names to that same logical name without the need
to change the program code after.
The second parameter denotes the open mode.
The available open modes are:
* r Open for reading only.
* w Create for writing only.
* a Append; open for writing at end of file or create for writing if the file does not exist.
* r+ Open an existing file for update (reading or writing).
* w+ Create a new file for update.
* a+ Open for append; open (or create if the file does not exist) for update at the end of
file.
- int fclose(FILE *stream);
You should close all the files or otherwise the files may not be updated.
fclose also free all the file buffers.
fclose return 0 if the file is closed successfully.

Computer Studies Page 20


St. Joseph's College Notes for Programming Language C

FILE *myfile;
main( )
{
....
if (!fclose(myfile)) // file closed successfully
printf(“file processing is ended”);
}
- int feof(FILE *stream)
feof is used for checking the file pointer reached the file end or not.
feof return 0 if not at end
return 1 if at end of file
For example,
if (!feof(myfile))
printf(“not end of file”);
- int fscanf(FILE *stream,char *format
- int getc(FILE *stream)
getc returns the character read from the input stream.
char c;
FILE *myfile;
c=getc(myfile);
printf(“%s”, getc(myfile));
- int putc(int ch,FILE *stream)
putc returns ch and put the ch into the output stream.
char c=‘f’;
FILE *myfile;
putc(c,myfile);
- int fputs(char *string, FILE *stream)
fputs returns the last character of the string.
Otherwise, EOF is returned.
char s[10]={‘a’,’b’,’c’};
FILE *myfile;
if (fputs(s,myfile)=‘c’)
printf(“put string success”);
- char *fgets(char *string, int n, FILE *stream)
fgets returns the argument string if success.
Otherwise return EOF error.
char s[10]={‘a’,’b’,’c’};
FILE *myfile;
if (fgets(s,myfile)=“abc”)
printf(“it is a success”);
- long ftell(FILE *stream)
ftell returns the current file pointer located in stream.
The offset is measured in bytes from beginning of file.
long offsetfrom;
FILE *myfile;
offset=ftell(myfile);
- int fseek(FILE *stream, long offset, int fromwhere)
fseek return 0 if successfully moved or non-zero for failure.
fromwhere should be 0, 1 or 2. The symbols below represent these values:
fromwhere File location
SEEK_SET(0) file beginning
SEEK_CUR(1) current file pointer position
SEEK_END(2) end-of-file
long offsetbytes=10;
FILE *myfile;
if (!fseek(myfile,offsetbytes,SEEK_SET))
printf(“seek is successful from start”);
VI.2 Structures

Computer Studies Page 21


St. Joseph's College Notes for Programming Language C

- Structures resemble records.


- Structures group a set of attributes for describing an object.
- Each attribute belong to a data type.
- Declaration of structure
struct is a reserved word for declaring structure.
struct birthday {
int mon;
int day;
int year;
};
- Nested structure
Within a structure, it can have other structure.
For example,
struct man {
struct birthday manbirth;
char name[30];
};
- Each attribute in a record can be access through the dot notation.
For example,
man.name=“James”;
man.manbirth.year=1994;
- Union
* Union is quite like structure.
* All member fields resided in the same memory location.
* Only one field of the member will be used
For example,
union number {
int intnum;
float flnum;
double dnum;
};
The type of number can be only one of the form: intnum, flnum, dnum. They are all
overlapped in the same memory location.

Computer Studies Page 22

You might also like