You are on page 1of 59

C Language Programming

Page

INTRODUCTION
C is a general-purpose programming language, which features economy of
expression, modern control flow and data structures and a rich set of operations. It
has been called as system programming language because it is useful for writing
compilers and operating systems.

BRIEF HISTORY
1.
2.
3.

4.

5.

6.

OF

ALGOL (Algorithmic Language) - 1960


CPL (Combined Programming Language) - 1963
BCPL (Basic Combined Programming Language) - 1967

developed by Martin Richards

this language in turn strongly influenced the development of the next


language
B.
B - 1970
written and developed by Ken Thompson for the first UNIX system on the DEC
PDP-7. Both BCPL and B are type less languages.
C - 1972

an expansion of B.
a programming language designed by Dennis Ritchie in 1972 at AT and T Bell
Laboratories.
C was originally designed for and implemented on the UNIX operating system
on the DEC PDP II.

the new C added something that B do not have: data types


Turbo C 1987
a particular version of C developed by Borland International Corporation.
This version is designed to run on various microcomputer systems, namely
those which use the operating system MS-DOS, the operating system for the
IBM Personal Computers and Compatibles.

DEFINITION

OF TERMS

Interpreters reads the source code of your program one line at a time and performs
the specific instructions contained in that line.
Compilers reads the entire program and converts it into object code, which is a
translation of the program source code into a form that can be directly executed by
the computer.
Compile Time refers to the events that occur during the compilation process.
Object Code is also referred to as binary or machine code
a translation of the source code of a program into machine code, which
the computer can read and execute directly.
Object code is the input to the linker
Source Code the text of a program that a user can read, commonly thought of as
program.
The source code is the input into the C compiler.
Run Time refers to the events that occur while the program is actually executing.
Library collection of pre-written.
Syntax errors that are detected during compiled time.
Semantic/ Run-time errors that are detected during execution time.

Prepared by: Ms. Elsa V. Isip

Technological Institute of the Philippines

C Language Programming

Page

THE PROGRAMMING PROCESS


( implemented using C Language)

Make/Edit the
source code

Source code
Pre - processing
Compiler
(compilation)

Object Code

Close to a code that can


be understood by the
machine

Linker
(Linking)

Executable
Code

COMPONENTS

OF TURBO

Turbo C is more than just a version of the C language. Rather, it includes a complete
environment in which to create, test, and run program. This programming environment
consists of a number of components:
1. Editor used to create program source code.
2. Extended C Language this version o C is significantly extended from the base bones
language of Ritchies specifications. The extension includes enhancement which
make the Turbo C compatible with the new proposed and ANSI Standard.
3. Compiler used to convert source code into machine code or binary code.
4. Debugger used for testing program and locating programming errors.
5. Run-Time Environment the capability for running programs within the Turbo C system.

Prepared by: Ms. Elsa V. Isip

Technological Institute of the Philippines

C Language Programming

Page

6. User Interface the various of Turbo C are integrated into a single program which allows
you to smoothly from source code entry to compilation to debugging to running
without ever leaving the Turbo C environment.

FEATURES

AND

CHARACTERISTICS

OF

1.

Middle Level Language

combines elements of high-level language with the functionalism of


assembly language

2.

Portable Program
it is possible to adapt software written for one type of computer for use on
another
Ex. Program written for an Apple II+ can be easily moved to an IBM PC.

3.

C allows almost all meaningful type conversions.


Ex. Char and integer types may be freely intermixed in most expressions.

4.

Turbo C has 43 keywords ( 32 as defined by the ANSI standard and 11 added by


BORLAND to allow you to make better use of some special aspects of the PC
environment), which are the commands that make-up the Turbo C language

5.

C allows manipulation of bit, bytes and addresses (basic elements which the
computer functions). Can manipulate data using arrays and pointers.

6.

It has its own standard library.

USES

OF

C was used for systems programming. A system program is part of a large class of
programs that form a portion of the operating system of the computer or its support
utilities. For example the following are commonly called systems programs
Operating System
Interpreters
Editors

Assemblers
Compilers
Database Managers

C PROGRAM STRUCTURE
_____________________________________________________________________
<preprocessor directive>
<declaration section>
main( )
{
/* refers to the beginning of the program */
statement;
...
statement;
}
/* refers to the end of the program */
______________________________________________________________________

Prepared by: Ms. Elsa V. Isip

Technological Institute of the Philippines

C Language Programming

Page

1.

/* ... */ Comment

2.

Preprocessor Directive
Contains information needed by the program to ensure the correct operation of
Turbo Cs standard library functions.
a. #include directive (commonly know as macro include) is a
preprocessing directive that causes a copy of the file to included at this
point in the file when compilation occurs.
a #include line can occur anywhere in a file, though it is typically at the
head of the file. The quotes surrounding the name of the file are
necessary.
an include file, is also called header file, can contain # define lines and
other lines. By convention, the names of header files end in .h.
Examples:
#include
#include
#include
#include

stdio.h
<stdio.h>
<string.h>
<math.h>

The C system provides a number of standard header files. These files


contain the declarations of functions in the standard library, macros, structure
templates and other programming elements that are commonly used.
b. #define directive line can occur anywhere in a program. It affects only
the lines in the file that come after it.
Normally, all # define line are placed at the beginning of the file. By
convention, all identifiers that are to be changed by the preprocessor are
written in capital letters.
Examples:
#define LIMIT 100
#define PI 3.1416
Explanation:
If the above lines occur in a file that is being compiled, the
preprocessor first changes all occurrences of the identifier LIMIT to 100 all
occurrences of PI to 3.14159. The identifier LIMIT and PI are called symbolic
constants. The use of symbolic constants in a program make it more
readable. More importantly, if a constant has been define symbolically by
means of #define facility and used throughout a program, it is easy to change
later, if necessary.
3.

Declaration Section
syntax: <data type> <identifier>
ex. int x, y, z;
float f=5.67;
char g;
char name[10];
int x=10;
A. Data Types
a. int contain integral values only, that is values that do not contain
decimal places.

Prepared by: Ms. Elsa V. Isip

Technological Institute of the Philippines

C Language Programming

Page

variables of type int, can hold integer quantities that do not require a
fractional component. Variables of this type are often used for controlling
loops and conditional statements.
a whole number consisting of an optional sign (+ or -) followed by a
sequence of digit.
occupies two bytes in the address.
can contain no decimal point or fractional part.
cannot contain commas.
ranges from 32768 to +32767
Types of int
short int identical with int
ranges from 32768 to +32767
occupies two bytes
2. long int takes up more space and can store large number
ranges from 2147483648 to +2147483647
occupies 4 bytes
3. unsigned int cannot be negative from 0 to 65536
4. unsigned long int
1.

b.

float consists of an optional sign (+ or -), followed by one or more


digits , a decimal point, and one or more further digits.
occupies 4 bytes.
it can include an optional exponent ranging from 3.4 E 38 to 3.4 E +38

c.

double is a special float which can store more significant digits and
have longer exponent.
occupies 8 bytes in the memory
ranges from 1.7E-308 to 1.7E+308 with 15 digits accuracy.

d. char can be used to contain a single letter, digit, punctuation mark or


control symbol recognized by the computer. Written enclosed within
single quotation marks, but literals strings are enclosed in double
quotation marks.
a character may be assigned an integer value between 128 and +127.
unsigned char data type may be assigned an integer value from 0 to
255.

e.

Ex.: char
char
char
char

c;
B = *;
a[30];
a = apple;

void

valueless
Three uses of void:

1.
2.
3.

to declare explicitly a function as returning no value;


to declare explicitly a function having no parameters;
to create generic pointers.

B. Identifiers

The names that are used to reference variables, functions, labels and
various other user-defined objects.

Sequence of letters, digits, and the special characters, which is called an


underscore

Prepared by: Ms. Elsa V. Isip

Technological Institute of the Philippines

C Language Programming

Page

An identifier in C can vary from one to several characters


The first character must be a letter or an underscore with subsequent
characters being letters, numbers or underscore.

In Turbo C, the first 32 characters of an identifier name are significant

In C, upper and lower case are treated as different and distinct from one
another.
Ex.: studname, Studname, StudName are three separate identifiers.
An identifier may not be the same as a Turbo C keyword, and it should not
have the same name as a function.

Correct
count
test123
4.

Incorrect
1count
hi!there

The Body of the Program


The body of the program starts with the reserved word main( ) and is enclosed with
{ and }.
block of code
is logically connected group of program statements that is treated as a
unit.
is created by placing a sequence of statements between opening and
closing curly braces.

NOTES:
All C keywords must be lowercase. It may not be used for any other purpose in a C
program.

All program statements in C must be terminated by a semicolon


(;).

Comments may be placed anywhere in a program and are


enclosed between two markers. The starting comment marker is /* and the ending
comment marker is */.

KEYWORDS/RESERVED WORDS

Words that have a special meaning in C and cannot be used for other purposes.
All upper in lowercase.

auto
break
case
char
const
continue
default
do

double
else
enum
extern
float
for
goto
if

int
long
register
return
short
signed
sizeof
static

struct
switch
typedef
union
unsigned
void
volatile
while

The Turbo C Extended Keywords


asm
_ss
pascal

interrupt
_cs
_es

Prepared by: Ms. Elsa V. Isip

cdecl
near
huge

_ds
far

Technological Institute of the Philippines

C Language Programming

Page

VARIABLES

are identifiers which can be assigned a value within a program


32 characters are valid like letters, digits, and underscore.
Declaring Variables:
Syntax:
Data type variable list;
Example:
int a, b, c;
char x, y;
double p;
float average;
char name[30];

list of variables separated by commas

Variable initialization the process of assigning starting values to the variables.


Several Ways to Initialize a Variables:
1. By using an assignment statement maybe used to assign to variables of any type.
Syntax:
Example:

variable-name = expression
x = -10;
ch = A;

The symbol = Cs assignment operator

2. By using function; (scanf)


Example:

scanf(%d, &x);
scanf(%lf, &y);

3. By assigning value during declaration


Example:

int x = 13;
char y = a;
double a, b = 120.00;

Global and Local Variables


Global Variables are initialized only at the start of the program. All global variables are
initialized to zero if no other initializer is specified.
Local Variables are initialized each time the function in which they are declared is entered.

CONSTANTS

refers to fixed values that may not be altered by the program.

Prepared by: Ms. Elsa V. Isip

Technological Institute of the Philippines

C Language Programming

Page

Syntax: type variable_name = constant;


Example:

char ch = a;
int num = 0;
float bal = 123.3;

Turbo C constant can be of any of the basic data types:


1.

character constants are enclosed between single quotes.


Example:
b, %%

2.

integer constants are specified as number without fractional components.


Example:
90, -600

3.

floating-point constant are required the use of decimal point followed by the numbers
fractional components.
Example:
12.134

4.

string constant consists of a phrase contained/enclosed within double quotes. String


constants are used in printf statements to introduce text messages into a program.
Examples:

char
int
float
double
string

a
10.1
123.23
123.23
Elsa

9
123
12323333

Declared Constants constants which are assigned a name declared constant are
defined using a # defined declaration at the beginning of the program. This
declaration is introduced by the word # define followed by a constant name and its
value.
Examples:

#
#
#
#
#

define
define
define
define
define

total amount
grapes
titik
m
salita

1000
90.00
E
14
good day

Access Modifiers
C has two type of modifiers that are used to control the way in which variables may be
accessed or modified.
1. const variables declared under this modifier cannot be changed during program
execution. However, you may give an initial value before the start of the
program.
Syntax:
const datatype variable = value;
Example:
const float
version = 3.20;
Interpretation:
This creates a float variable called version that may not be modified by your
program. A constant variable will receive its value either from an explicit
initialization or by some means dependent on the hardware.
2. using # define

the # define declaration is used at the beginning of a


program. Like const, #define is also used in declaring constants.

Prepared by: Ms. Elsa V. Isip

Technological Institute of the Philippines

C Language Programming

Page

Syntax:
# define variable
value
Example:
# define amount 56.89

Note: it is necessary to tell a computer the type of a declared constant. C determined


the data type from the assigned value. Remember that although, const and # define
defines constant, the two modifiers have different syntax.

Type Modifiers
A modifier is used to alter the meaning of the base type to more precisely fit the needs
of various situation. With the exception of type void, the basic data type may have
various modifiers preceding them.
Example:

signed
long
unsigned
short

Possible Combinations of Cs Basic Types and Modifiers


Type
char
unsigned char
signed char

Bit Width
8
8
8

Range
to
to
to

-128
0
-128

127
255
127

int
unsigned int
signed int
short int
unsigned short int
signed short int
long int
signed long int

16
16
16
16
16
16
32
32

-32768
0
-32768
-32768
0
-32768
-2147483648
-2147483648

to
to
to
to
to
to
to
to

32767
65535
32767
32767
65535
32767
2147483649
2147483649

float
double
long double

64
64
80

3.4E 38
1.7E 308
3.4E-4932

to
to
to

3.4E+38
1.7E+308
1.1E+4932

Assignment Statement

Is the process of assigning a value to a variable. In C, we use the equal sign (=)
as the assignment operator.
A = C + r * (9 / p);
Expression
Assignment Operator
Variable

Prepared by: Ms. Elsa V. Isip

Technological Institute of the Philippines

C Language Programming

Page

10

How to Assign Values to Variables


1. The variable must be on the left side of the equal sign.
Values must be on the right side of the equal sign.
2. Any expression can be assigned on the variable.
3. Expressions are not allowed on the left side of the assignment operator.

OPERATORS

OPERATORS

a.

is a symbol that tells the compiler to perform specific mathematical, relational


or logical manipulations.
a symbol which represents an operation to be performed.

Arithmetic Operators
Symbols
+
*
/
%
-++

Functions
subtraction
addition
multiplication
division
modulus
decrementing
incrementing

x-- same as x=x-1


x++ same as x=x+1

Important Notes:
1.
2.

3.

4.

The operators +, -, *, and / all work the same way in C as they do in most computer
languages.
When / is applied to an integer or character, any remainder will be truncated.
Example:
13/6 = 2
3/4 = 0
10/3 = 3
11/2 = 5
The modulus division operator, % yields the remainder of an integer division. % cannot be
float on type or double.
Example:
13 % 2 = 1
-25 % 2 = -1
5%3=2
6%2=0
When an increment or decrement operator precedes its operand, C performs the increment
or decrement operation prior to using the operands value. If the operator follows its
operand, C uses the operands value before incrementing or decrementing it.
Example:
X = 12;
Y = ++X;
X is 13; Y is 13
X = 12;
Y = X++

X is 13; Y is 12

Increment and Decrement Operators

Prepared by: Ms. Elsa V. Isip

Technological Institute of the Philippines

C Language Programming

Page

11

Increment to add exactly one to the value of a variable


Decrement to subtract exactly one from the value of a variable.
++ increment operator
--

decrement operator

X++ post increment


--X
pre increment

Example:
1. X = X + 1 or X+=1 is the same with X++
2. X = 5, Y = 12
W = Y + X++
W = Y + X;
17
X = X + 1;
6
W = Y + ++ X
X =X + 1;
6
W= Y+ X;
18
W = Y + X--

W = Y + X;
X = X - 1;

17
4

W = Y + -- X

X =X - 1;
W= Y+ X;

4
16

Precedence of Arithmetic Operators


highest
++ - - (unary)
*/%
lowest
+b.

Relational Operators used to determine the relationship of one quantity to another.


refers to the relationship values can have with one another.

Symbols
>
>=
<
<=
==
!=
c.

Functions
greater than
greater than or equal to
less than
less than or equal to
equal
not equal

Examples
x>y
num >= 100
x<y
num <= 100
x == y
x != 10

Logical Operators refers to the ways the relationships can be connected together using the
rules of formal logic.
Symbols
&&
||
!

Functions
and
or
not

d.

Assignment Operator ( = ) equal sign

e.

Combined Operators
+=
*=
-=

ex. a+=b
ex. a*=b
ex. a-=b

Prepared by: Ms. Elsa V. Isip

a=a+b
a=a*b
a=a-b

Technological Institute of the Philippines

C Language Programming

/=
%=
f.

ex.
ex.

Page

a/=b
a%=b

12

a=a/b
a=a%b

Other Operators

1.

?: Ternary Operator (Question mark colon) because it requires three operands and takes
the general form
Syntax:

Exp1 ? exp2 : exp3


or
condition ? statementT : statementF;
result = condition ? statementT : statementF;

Example:
x = 10;
y = x>9 ? 100: 200;

x=10
x>9 ? printf(Yes): printf(No);
max = (a>b) ? a : b;
Interpretation:

x = 10;
if (x>9)
Y = 100;
else
Y = 200;

Exp1, epx2 and exp3 are expressions; exp1 is evaluated, if true then
exp2 is evaluated and its value becomes the value of the expression.
The value of a ? expression is determined this way: Exp1 is evaluated.
If it is true, then Exp2 is evaluated and becomes the value of the
entire ? expression. If Exp1 is false, then Exp3 is evaluated and its
value becomes the value of the expression.

2. , the comma operator is used to string together several expressions.

Example:

Finally

It is used to string together several expressions.


The left side of the comma operator will always be evaluated as void. This
means that the expression on the right side will become the value of the
total comma separated expression.
Y = ( X=4, X++, X *3);
X=4
X=5
X = 15
Y = 15

x = (y=3, y+1);

The value of x is 4

y = 20;
x = (y=y-5, 30/y);The value of x is 2

Prepared by: Ms. Elsa V. Isip

Technological Institute of the Philippines

C Language Programming

HIERARCHY

OF

Page

13

C OPERATORS

()
! ++ - - (type)
* / %
+ < <= > >=
== !=
&&
||
?
= *= /= %= +=
,

highest

lowest

EXPRESSION
Operators, constant and variables are the constituents of expressions

Are combinations of operators, constants and variables.

Expression Evaluation:
1.
2.
3.
4.

v = (6 / 2 * 3) >= ((6/2 % 3) + 6 * 2)
v = (5 == (3 + 1)) || (( 6 % 3) >= (5 /2)) && (5 !=6)
A = 1; B=2; C=3;
X = !((A > C) && (B >=3)) || (C < 4) && ((6 <= 6) || (7 < B))
v = !((3 * 2) < (1 * 3)) || !(2== 2)

CASTS
It is possible to force an expression to be of a specific type by using a construct called a
cast.
Syntax:
(type) expression

where:
type is one of the standard C data types.
Sample Program No. 1
#include "stdio.h"
main()
{

int i;
clrscr();
for(i=1;i<=5;++i)
printf("%d / 2 is: %.2f\n", i, (float)i/2);
getche();

Prepared by: Ms. Elsa V. Isip

Technological Institute of the Philippines

C Language Programming

Page

14

INPUT AND OUTPUT STATES


A. FORMATTED INPUT/OUTPUT FUNCTIONS
1.

IN

printf( ) CHAR/STRING/NUMERIC OUTPUT


is a function in a C system that simple prints or display prints its argument at the
terminal or on the CRT screen.
Syntax:
Where:

Example:

printf (%format specifier, variable);


control string is a string and may contain format specification or conversion
specification
Format specification begins with a percent character (%) and ends with a
format specifier
X = 12345;
printf(%d, X);

COMMONLY USED FORMAT SPECIFIERS


Format
Specifier
%c
%d
%i
%f
%lf
%s
%o
%x
%e
%g
%%

How the Corresponding argument is printed


As character
As a decimal integer
As a decimal
As a floating point
As a double
As a string
As an octal
As a hexadecimal
As a floating point number in scientific notation
In the e-format or f-format is shorter
Prints a percent sign

Limiting Float Numbers (for printf())


%.3f --- means 3 places after the decimal point
x = 89.832211
printf(%.3f,x);
output = 89.832
%8.3f -- _ _ _ _ _ _ _ . _ _ _ (8 with decimal point and 3 decimal places)
Examples:
1.
2.
3.
4.

printf
printf
printf
printf

(%c, a);
(%d, b);
(%f, c);
(%s, name);

When an argument is printed, the place where it is printed is called field and the number
of characters in its field is called its field width. The filed width can be specified in a
format as an integer occurring between the percent character (%) and the format specifier.
Example:
printf (%c%3c%5c\n, X,Y,Z);

Prepared by: Ms. Elsa V. Isip

Technological Institute of the Philippines

C Language Programming

Page

15

will print:
X_ _ _ Y_ _ _ _ _Z

Examples:
#include "stdio.h"
main()
{
clrscr();
printf("programming is fun \n");
printf("programming in C is even more fun\n");
getche();
}
Output:
programming is fun
programming in C is even more fun

#include <stdio.h>
main()
{

clrscr();
printf("Testing...\n..1\n...2\n....3\n");
getche();

Output:
Testing...
..1
...2
....3

#include "stdio.h"
main()
{

int sum;
clrscr();
sum=50+25;
printf("The sum of 50 and 25 is %d\n", sum);
getche();

Output:
The sum of 50 and 25 is 75

#include <stdio.h>

Prepared by: Ms. Elsa V. Isip

Technological Institute of the Philippines

C Language Programming

Page

16

main()
{

int v1, v2=25, sum;


clrscr();
v1=50;
sum=v1+v2;
printf("The sum of %d and %d is %d\n", v1, v2, sum);
getche();

}
Output:
The sum of 50 and 25 is 75

2.

scanf( ) CHAR/STRING/NUMERIC OUTPUT


is analogous to the function printf() but is used for input rather than output.
used to read virtually any type of data entered at the keyboard.
its first argument is a control string having formats that corresponds to the various
ways the characters in the input stream are to be interpreted. The other arguments
are argument list or addresses.
Syntax :
where:

scanf(control string, argument list);


control string ( includes all the text labels, escape character and
conversion specifies(format code) required for the desired
output/input.
argument list ( includes all the variables to be printed in the order they are
to be printed.

Example:
1.
2.
3.
4.

scanf(%d, &numero);
scanf(%c, &letra);
scanf(%s, ngalan);
scanf(%lf, doble);

BACKSLASH CODES / ESCAPE SEQUENCE


Code
\n
\b
\f
\t
\v
\
\\
\
\a
\xhh

Prepared by: Ms. Elsa V. Isip

Meaning
Newline
Backspace
Formfeed
Horizontal tab
Vertical tab
Insert Single quote
Backslash
Insert Double quote
Sound the bell
Insert char hh where is hexadecimal number

Technological Institute of the Philippines

C Language Programming

Page

17

Example:
#include <stdio.h>
main()
{

char my_char;
clrscr();
printf("Please type a character : ");
scanf("%c", &my_char);
printf("Thank You. That character was %c\n", my_char);
getche();

Sample Program using printf() and scanf()


#include stdio.h>
/* this is a simple program */
main(0
{
char b1, b2, b3;
int a;
float x;
double z;
printf(\n %s \n %s, Input three characters, an int, a float, and a double:);
scanf(%c%c%c%d%f%lf, &b1,&b2,%b3,&a,&x,&z);
printf(Here is the data that you types in:\n);
printf(%3c%3c%3c%5d%12f%12lf, b1,b2,b3,a,x,z);
return 0;
}

UNFORMATTED I/O FUNCTIONS


1.
2.
3.

4.
5.

6.

IN

getch( )
reads a character without echo. Does not wait for carriage return ENTER key.
getche() reads a character with echo. Does not wait for carriage return or ENTER key.
gets( )
this function takes the name of the string as an argument and reads characters from
the keyboard until ENTER key is pressed. ENTER key is not stored but is replaces be
the null terminator.
getchar() reads a single individual character from the keyboard and waits for the carriage
return or ENTER key.
puts( )
write a string to the screen, followed by a newline. It can only output a string of
characters. It cannot output numbers or do format conversion. It takes up less space
and run faster.
putchar( ) writes a string (character) to the screen.

Prepared by: Ms. Elsa V. Isip

Technological Institute of the Philippines

C Language Programming

Page

18

CONTROL STRUCTURES
CONTROL STRUCTURES

Control the flow of execution in a program or function


A combination of individual instruction into a single logical unit with one entry point and one exit
point.

3 KINDS

OF

CONTROL STRUCTURES

1. Sequential Control Structure


Sequential execution of statements
Executing statements one after the other in order in which they are written.
2 types of statements:
1. single statement an expression followed by a semi-colon.
2. compound statement a group of statements bracketed by { and } that are
executed sequentially.
2. Selection Control Structure
Chooses among alternative program statements

Uses conditions to select a course of action.


Condition an expression that is either false (0) or true (usually represented by 1)
5 types:
1. simple if
2. if-else
3. if-else-if
4. nested if-else
5. switch
these are also called conditional branching constructs
3. Iteration / Repetition Control Structure

Prepared by: Ms. Elsa V. Isip

Technological Institute of the Philippines

C Language Programming

Page

19

Uses loops repeats a group of steps in a program


repetition of action is one reason we rely on computers. When there are
large amount of data, it is very convenient to have control mechanism that
repeatedly execute specific statements.
Loop body contains the statements to be repeated in the loop.
3 types:
1. for
2. while
3. do-while
these are also called looping constructs.

SELECTION CONTROL STRUCTURE


SIMPLE IF STATEMENT
The general form of the if statement is
Syntax :

if (condition)
statementT;

Example:

if (grade >=75)
printf(Passed);

Interpretation:

If condition evaluates to true, then statementT is executed; otherwise statement


is skipped and control passes to the next statement.

Note:

Usually, the condition in an if statement is a relational, logical, equality expression, a


condition from any domain is permissible.
Where appropriate, compound statement should be used to group of statements under the
control of a single if condition. The code be written to be more efficient and more
understandable by using a single if statement with a compound statement for its body.

IF ELSE STATEMENT
The general form of the if - else statement is
Syntax :

if (condition)
statementT;
else
statementT;

Example:

if (grade >= 75)


printf(Passed);
else
printf(Failed);

Interpretation: If condition evaluates to true, then statementT is executed; otherwise it is


skipped and statementF is executed. In both cases, control passes to the next statement.
Note:

Block of statements in C is surrounded by curly braces { } else is optional

Prepared by: Ms. Elsa V. Isip

Technological Institute of the Philippines

C Language Programming

Page

20

IF ELSE IF STATEMENTS

A common programming constructs is the if else if statement. It look like this:


Syntax :

if (condition)
Statement1;
else if (condition)
statement2;
else if (condition)
statementn;
:
else statemente;

Example:

if (x > 0)
printf(x is positive);
else if (x < 0)
printf(x is negative);
else printf(x is zero);

Interpretation:

The conditions here are evaluated in sequence until a true condition is reached. If
a condition is true, the statement following it is executed, and the rest is skipped.
If a condition is false, the statement following it is skipped, and the next condition
is tested. If all conditions are false, then the statement e following the final else is
executed.

Note:

The last else is optional.

NESTED IF ELSE STATEMENTS

A common programming constructs is the nested if else statement. It look like this:
Syntax :

Example:

if (condition)
if (condition)
statement2;
else
statementn;
else
statemente;
if (x == 50)
if (y >= 120)
{ sum = x+y;
printf(the sum of x and y is %d, sum);
}
else
{ diff = x - y;
printf(the difference of x and y is %d, diff);
}
else

printf(x is zero);
printf(Next time);

Sample Program No. 1


/* Program to determine if a number is positive or negative*/
#include "stdio.h"
main()

Prepared by: Ms. Elsa V. Isip

Technological Institute of the Philippines

C Language Programming

Page

21

int num;
clrscr();
printf("Enter an integer ");
scanf("%d",&num);
if (num > 0)
printf("%d is a positive integer",num);
else
printf("%d is a negative integer",num);
getch();

}
Sample Program No. 2
/* Program to determine if a number is odd or even*/
#include "stdio.h"
main()
{
int num,rem;
clrscr();
printf("Enter a number ");
scanf("%d",&num);
rem = num % 2;
if (rem == 0)
printf("%d is an even number",num);
else if (rem != 0)
printf("%d is an odd number",num);
getch();
}
Sample Program No. 3
/* Program Arithmetic Operations */
#include "stdio.h"
main()
{
int f,s, total=0;
char optr;
clrscr();
printf("Enter 1st number : "); scanf("%i", &f);
printf("Enter the operator : "); scanf("%s", &optr);
printf("Enter 1st number : "); scanf("%i", &s);
if (optr=='+')
total=f+s;
if (optr=='-')
total=f-s;
if (optr=='*')
total=f*s;
if (optr=='/')
total=f/s;
if (optr=='+' || optr=='-' || optr=='*' || optr=='/')
printf("%d %c %d = %d", f, optr, s, total);
else
printf("Operator not valid!!!");
}

getch();

SWITCH STATEMENT

Prepared by: Ms. Elsa V. Isip

Technological Institute of the Philippines

C Language Programming

Page

22

is a multiway conditional statement generalizing the if-else statement.


is a built-in multiple branch decision statement. A variable is successively tested against
a list of integer or character constants. When a match is found, a statement or block of
statement is executed.

Syntax:

switch(variable/ expression)
{
case constant1 : statement;
break;
case constant2 : statement;
break;
case constant3 : statement;
break;
:
default
: statement;
}

Example:

switch(QUIZ)
{
case 10 :
case 9 : printfA);
break;
case 8 : printfB);
break;
case 7 : printfC);
break;
case 6 : printfD);
break;
case 5 :
case 4 :
case 3 :
case 2 :
case 1 :
case 0 : printfF);
break;
default : printf(Input out of Range);
}

Interpretation:
The switch expression maybe any expression which evaluates to an int,
conditional, char.
The case list must consists of constants whose matches that of the switch
expression.
After the statements for a case, a keyword break maybe used.

The break keyword means that at that point, execution should jump to the
end of the switch statement.
The switch statement is terminated by curly bracket (}).
This switch constant can be used to specify an action to be taken if the
value of the switch expression does not match any of the listed values.
Note:

The case list cannot include variables or expressions.


The optional switch constant default.
The statements following a case label may be one or more C statements, so
you do not need to make multiple statements into a single compound
statement using braces.

Prepared by: Ms. Elsa V. Isip

Technological Institute of the Philippines

C Language Programming

Page

23

If no case label value matches the expression, the entire switch statement
body is skipped unless it contains a default label. If so, the statements
following the default label are executed.

There are 3 important things to know about switch statement:


1. Switch differ from the if in that switch can only test for equality, where as the if, can
evaluate relational or logical expression.
2. No two case constant in the same switch can have identical values. A switch statement
enclosed by an outer switch may have case constants that are the same.
3. If char constant are used in the switch, they are automatically converted to their integer
values.
Switch statement is often used to process keyboard commands, such as menu selection.
Sample Program No. 1
/* Program Simulation */
#include "stdio.h"
int x;
main()
{
clrscr();
puts("Enter a number: ");
scanf("%d",&x);
switch(x)
{ case 1: puts("now, there\'s"); break;
case 2: puts("only but a few");
case 3: puts("good men...");
puts("it\'s true!!!");break;
default: puts("no good men at all...");
}
getch();
}
Sample Program No.2
/* Program Simulation */
#include "stdio.h"
int x;
main()
{
clrscr();
puts("Enter a number: ");
scanf("%d",&x);
switch(x)
{
case 1:
case 2:
case 3: printf("%d Indian", x);
break;
case 4:
case 5:
case 6: printf("4 little 5 little 6 little Indian");
break;
}
getch();
}
Sample Program No. 3
switch(optr)

Prepared by: Ms. Elsa V. Isip

Technological Institute of the Philippines

C Language Programming

Page

24

case + : total = f + s; break;


case - : total = f - s; break;
case * : total = f * s; break;
case / : total = f / s; break;
default : printf(operator not valid);

ITERATION / REPETITION CONTROL STRUCTURES


LOOPS

Allow a set of instructions to be repeated until a certain condition is reached.

FOR LOOP

The for loop will continue to execute as long as the condition is true. Once the condition
becomes false, program execution will resume at the statement following the for.

Syntax:

for(initialization expression; loop repetition condition; update expression)


statement;
where: (the for statement allows many variants, but there are three main parts)
initialization expression is an assignment statement that is used to set the
loop-control variable.

Loop repetition condition is a relational expression that determines when the


loop will exit by testing the loop-control variable against some value.
Update expression defines how the loop-control variable will change each time
the loop is repeated.

Example:

for (x= 100; x!=65;x-=5)


{
z=sqrt(x);
printf(The square root of %d is %f,x,z);
}

Interpretation:
First, the initialization expression is executed.
Then, the loop repetition condition is tested.
If it is true, the statement is executed, and the update expression is evaluated. The
loop repetition condition is re-tested.
If the loop repetition condition is found to be false, the for loop is exited.
Note / Programming style:
These three major sections must be separated by semicolons.
You may place all three expressions in the for heading in a single line, specially if all
three expressions are very short.]
The body of a for loop may be a compound statement.

Sample Program No. 1

Prepared by: Ms. Elsa V. Isip

Technological Institute of the Philippines

C Language Programming

/* Program on Factorial */
#include <stdio.h>
main()
{
int f,x,ans;
clrscr();
printf("Enter a number : "); scanf("%d",&f);
ans=1;
for(x=f;x>=1;x--)
ans=x*ans;
printf("The factorial of %d is %d",f, ans);
getche();
}

Page

25

Enter a number : 5
The factorial of 5 is 120

Sample Program No. 2


/* Program Exponential */
#include <stdio.h>
main()
{
int b,e,x;
double ans;
char sagot;
clrscr();
printf("Enter Base : "); scanf("%d",&b);
printf("Enter Exponent: "); scanf("%d",&e);
ans=1;
for(x=1;x<=e;x++)
ans=b*ans;
printf("The answer is %.2f",ans);
getche();
}

Enter Base : 2
Enter Exponent: 3
The answer is 8.00

Sample Program No. 3


/* Displays the triangular number of a number */
what triangular number do you want?
#include<stdio.h>
5
main()
Triangular number 5 is 15
{
int n,m,t_num;
clrscr();
printf("what triangular number do you want? \n");
scanf("%d",&m);
t_num=0;
for(n=1;n<=m;n++)
t_num=t_num+n;
printf("Triangular number %d is %d\n",m,t_num);
getche();
}
Sample Program No. 4
/* Program Simulation */
#include <stdio.h>

Prepared by: Ms. Elsa V. Isip

10
22
39
4 26
5 58
6 110 Institute of the Philippines
Technological
7 187
294 142 40

C Language Programming

Page

26

#define r 7
int k, k2, x, y, z;
main()
{
clrscr();
k=x=0; y=2; z=5; k=1;
for (;k<=r;k++)
{
k2=x;
x+=y;
y+=z;
z+=5;
printf("%d %d \n", k, k2);
}
printf("%d %d %d", x, y, z);
getch();
}
Sample Program No. 5
/*Program Simulation*/
#include "stdio.h"
int x, y;
main()
{
clrscr();
x=7; y=3;
x=x%y;
if(x==0)
printf("FINISH");
else
for(x=10;x>=2;x-=2)
for(y=x;y>=1;y-=2)
printf("%d ", y);
printf("\n");
getche();
}
Sample Program No. 6
/* Program Simulation */
#include "stdio.h"
#define p printf
#define c case

10 8 6 4 2 8 6 4 2 6 4 2 4 2 2

_JACK**_AND_JILL_

int x, ctr, num;


main()
{
clrscr();
x=5;
for (ctr=5;ctr<=35;ctr*=2)
{
switch(ctr%x)
{
c 3 : p("T");
c 7 : p("C");
c 8 : p("I");break;
c2:
c 0 : p("_J");p("A");
c 11: break;

Prepared by: Ms. Elsa V. Isip

Technological Institute of the Philippines

C Language Programming

Page

27

c 1 : p("J");break;
c 4 : p("C");
c 15: p("K");
c 16: p("**");
c 10: p("_AND_");
c 13: p("J");break;
default : p("I");p("L");p("L");p("_");
}
x++;

}
getch();

WHILE LOOP

continues to execute as long as the condition which can be any expressions remains true.

Syntax:

while (loop repetition condition)


statement;

Example:

while (num != 0)
{ scanf(%d, &num);
sum += num;
}
printf(the sum of all number is %d, sum);

Interpretation:
First, the loop repetition condition is tested or evaluated.
If it is true, the statement is executed and the loop repetition condition is retested.
The loop body, namely statement is repeated as long as the loop repetition
condition is true.
Once it is found to be false, the while loop is exited and the next program
statement after the while statement is executed.
Note:

It is possible to inadvertently specify an expression that never become false, and


unless other means of escaping the while loop are introduced, the program is
stuck in an infinite loop. Care should be taken to avoid this difficulty.

Sample Program No. 1


/* Program Simulation */
#include "stdio.h"
main()
{

int count=1;
clrscr();
while (count<=5)
{
printf("%d\n", count);
++count;
}
getche();

Prepared by: Ms. Elsa V. Isip

1
2
3
4
5

Technological Institute of the Philippines

C Language Programming

Page

28

Sample Program No. 2


/* This program finds the Greatest Common Divisor of two nonnegative integer values */
Please type in two nonnegative integers :
#include<stdio.h>
48
main()
Their Greatest Common Divisor is 4
{
int num1, num2, temp;
clrscr();
printf("Please type in two nonnegative integers : \n");
scanf("%d %d", &num1, &num2);
while (num2 != 0)
{
temp = num1 % num2;
num1 = num2;
num2 = temp;
}
printf("Their Greatest Common Divisor is %d \n",num1);
getch();
}
Sample Program No. 3
/* Program to reverse the digits of a number */
#include<stdio.h>
main()
{ int num, rightdigit;
clrscr();
printf("Enter a number \n");
scanf("%d", &num);
while (num != 0)
{
rightdigit = num % 10;
printf("%d", rightdigit);
num = num / 10;
} printf("\n");
getch();
}

Enter a number
12345
54321

DO WHILE LOOP
Syntax:

do

Example:

do {

statement;
while (loop repetition condition);

scanf(%d,&num);
sum += num;
} while (num > 100);
printf(the sum is %d, sum);

Interpretation:

The program statement is executed first.

Next, the loop repetition condition inside the parenthesis is evaluated.

If the result of the loop repetition condition is TRUE, then the loop continues and
program statements is once again executed.

As long as evaluation of expression continues to be TRUE, program statement will


be repetitively executed. When evaluation of expression proves FALSE, the loop will be

Prepared by: Ms. Elsa V. Isip

Technological Institute of the Philippines

C Language Programming

Page

29

terminated and next statement in the program will be executed in the normal sequential
manner.
Sample Program No. 1
/* Program to reverse the digits of a number */
#include<stdio.h>
main()
{ int num, rightdigit;
clrscr();
printf("Enter a number \n");
scanf("%d", &num);
do
{
rightdigit = num % 10;
printf("%d", rightdigit);
num = num / 10;
}
while (num != 0);
printf("\n");
getch();
}

Enter a number
12345
54321

Sample Program No. 2


/* Fibonacci Sequence */
#include <stdio.h>
main()
{
int a=0,b=1,c;
clrscr();
printf("%i ",a);
printf("%i ",b);
do {
c=a+b;
printf("%i ",c);
a=b;
b=c;
}
while(c<100);
getch();
}
Sample Program No. 3

0 1 1 2 3 5 8 13 21 34 55 89 144

/* Accepts valid Student Number */


#include "stdio.h"
main()

Student Name : Elsa V. Isip


Student No.: 9406625

{
char name[20], stno;
int ctr;
clrscr();
printf("Student Name : "); gets(name);
gotoxy(5,4);printf("Student No.:
Q");
ctr=1;
do
{
do
{
gotoxy(18+ctr,4);

Prepared by: Ms. Elsa V. Isip

Technological Institute of the Philippines

C Language Programming

Page

30

stno=getch();
gotoxy(184+ctr,4); printf("%c",stno);
}
while(!((stno>='0') && (stno<='9')));
ctr=ctr+1;

}
while (ctr <=7);
getche();
}

BREAK

AND

CONTINUE STATEMENT

break Statement

This statement is encountered inside the loop, the loop is immediately terminated and
program control resumes at the next statement following the loop.

Two Uses of Break Statement


1. To terminate a case in the switch statement.
2. To force immediate termination of a loop, bypassing the normal loop conditional
test.
Sample Declaration:
while(1) {
scanf(%lf,&x);
if (x< 0.0)
break;
printf(%f\n,sqrt(x));
}

Example:
#include <stdio.h>
main()
{ int t;
clrscr();
for(t=0; t<100; t++)
{ printf("%d ",t);
if (t==10)
break;
}
getch();
}

0 1 2 3 4 5 6 7 8 9 10

continue Statement

Prepared by: Ms. Elsa V. Isip

Technological Institute of the Philippines

C Language Programming

Page

31

Works in a somewhat similar way to the break statement, instead of forcing termination,
continue forces the next iteration of the loop to take place, skipping any code in between.
The continue statement causes the current iteration of the loop to stop and causes the next
iteration of the loop to begin immediately. The continue statement may only occur inside for,
while, and do loops.
Sample Declaration:
do {
scanf(%d, &num);
if (x < 0)
continue;
printf(%d, x);
} while (x != 100);

Example:
#include <stdio.h>
main()
{ int t;
clrscr();
for(t=0; t<10; t++)
{ if (t%2)
continue;
printf("%d ",t);
}
getch();
}

02468

goto Statement

Is included in the C language because sometimes it is the only way out of a certain condition.
Used to alter the normal sequence of a program execution statements by transferring control to
some other part of the program.

Syntax:
goto label;
label:
statement;
where:
label is an identifier
the target statement must be labeled (unique label)

Prepared by: Ms. Elsa V. Isip

Technological Institute of the Philippines

C Language Programming

Page

32

Example:
void main( )
{
int counter = 0;
try_again:
if (counter < 100) goto stop;
printf(%d\n, counter);
++counter;
goto try_again;
stop:

FUNCTIONS
FUNCTIONS

is a subroutine that contains one or more statements and performs one or more tasks
is a section of a program which perform a specific task. The task assigned to a function is
performed whenever C encounters the function name.
Is actually a subprogram that is, a function perform a task within a program and is
written in a form similar to C main program.
Advantages of Using a Function:
1. fits naturally in top-down approach
2. can be divided for many programmers as subtasks
3. can easily be tested, each function can be tested individually.

Prepared by: Ms. Elsa V. Isip

Technological Institute of the Philippines

C Language Programming

Page

33

Why use function subprograms?

Top-down design : easier and simpler

Subprograms make it easier to divide programming tasks

Reuse of Code
Functions can be executed more than once
Easier to alter code

Procedural Abstraction
Procedures functions in C
A programming technique in which we use function subprograms to allow us to
remove from the main function, the code that provides detailed solution to a subproblem.

Protection of data
Centers around concept of local data data available only to the function wherein
it is declared and only when the function is executing. When the function is done,
the data are gone.

Syntax:

type_specifier function_name(parameter_list)
{
body of function
}

where:
type_specifier / return_type
( specifies the type of value that the function returns using the return statement.
0parameter_list / function_argument
( comma separated list of variables that receive the values of the arguments when the
function is called.
( a function maybe without parameters in which case the parameter list contains only
the keyword void.
Uses of return Statement:
1. it causes an immediate exit from the function it is in. That is, it causes program execution
to return to the calling code.
2.1 it can be used to return a value.
Sample Program No. 1
/* Program that uses a function without a parameter */
#include <stdio.h>
void star(void)
*****C*****
{
printf("*****");
}
main()
{
clrscr();
star();
printf("C");
star();

Prepared by: Ms. Elsa V. Isip

Technological Institute of the Philippines

C Language Programming

Page

34

getch();

Sample Program No. 2


/* Program that increments a number by one */
#include<stdio.h>
int f(int x)
{
return(x+1);
}
main()
{ clrscr();
printf("%d",f(2));
getche();
}
Sample Program No. 3
/* Display the cube of a number */
#include <stdio.h>
int cube(int x)
{
int ans;
ans = x * x * x;
return(ans);
}

Enter a number : 3
The cube of 3 is 27

main()
{
int y;
clrscr();
printf("Enter a number : ");
scanf("%d",&y);
printf("The cube of %d is %d",y, cube(y));
getche();
}

Sample Program No. 4


/* Program that increments a number by one using function with parameter. */
#include "stdio.h"
int inc(int x)
{
The value of y now is 6
int ans;
x++;
ans=x;
return(ans);
}
main()
{ int y=5;
clrscr();
printf("The value of y now is %d", inc(y));

Prepared by: Ms. Elsa V. Isip

Technological Institute of the Philippines

C Language Programming

Page

35

getche();

Global variables
known throughout the entire program and may be used by any piece of code. It is declared
outside any function.
Local variables
variables that are declared inside a function. It can be referenced only by a statements that
are inside the block in which the variables are declared.
Formal variables
variables that accept the values of the arguments of a function.

PASSING DATA

IN

FUNCTIONS

Two Ways of Passing Arguments


1.

Call by value
this method copies the value of an argument into the formal parameter of the subroutine.
changes made to the parameters of the subroutine have no effect on the variables used to
call it.
2. Call by reference
the address of an argument is copied into the parameter. Inside the subroutine, the address
is used to access the actual argument used in the call.
changes made to the parameter affect the variable used to call the routine.

Sample Program No. 5


/* Program that increments a number by 3 */
#include "stdio.h"
int inc(int x, int y)
{ int ans;
x+=y;
ans=x;
return(ans);
}
main()
{
int y=5;
clrscr();
printf("The value of y now is %d", inc(y,3));
getche();
}
Sample Program No. 6
/*Program Simulation*/
#include"stdio.h"
void trick(int w, int x, int y, int z)
{
printf("\n%d %d %d %d", w,x,y,z);
}
main()
{
int w=10, x=12, y=14, z=16;

Prepared by: Ms. Elsa V. Isip

The value of y now is 8

10
12
14
12
12
12
12

12
14
10
12
14
16
14

14
10
16
10
14
16
10

16
16
12
16
10
10
16

Technological Institute of the Philippines

C Language Programming

Page

36

clrscr();
trick(w,x,y,z);
trick(x,y,w,z);
trick(y,w,z,x);
trick(x,x,w,z);
trick(x,y,y,w);
trick(x,z,z,w);
trick(x,y,w,z);
getch();

Sample Program No. 7


/*Program Simulation */
#include<stdio.h>
print(int *w, int x, int y, int *z)
{
*w+=2;
x-=1;
y+=3;
*z-=1;
printf("%d %d %d %d\n", *w,x,y,*z);
}

5 8 13 18
7 7 16 17
8 13 7 17
15 6 20 7
17 7 15 7
19 16 10 14
7 7 14 19

main()
{
int w=5, x=8, y =13, z=18;
clrscr();
printf("%d %d %d %d\n",w,x,y,z);
print(&w,x,y,&z);
printf("%d %d %d %d\n",x,y,w,z);
print(&y,w,z,&x);
printf("%d %d %d %d\n",z,w,y,x);
print(&z,z,w,&y);
printf("%d %d %d %d\n",x,w,y,z);
getch();
}

Sample Program No. 8


/*Program Simulation */
#include"stdio.h"
void trick(int w, int *x, int y, int *z)
{
printf("\n%d %d %d %d", w,*x, y,*z);
++*x; --*z;
}

10
13
15
12
13
13
13

12
14
10
12
15
13
16

14 16
10 15
14 13
11 14
15 11
13 10
9 149 13 17 13

main()

Prepared by: Ms. Elsa V. Isip

Technological Institute of the Philippines

C Language Programming

Page

37

int w=10, x=12, y=14, z=16;


clrscr();
trick(w, &x, y, &z);
trick(x, &y, w, &z);
trick(y, &w, z, &x);
trick(x, &x, w, &z);
trick(x, &y, y, &w);
trick(x, &z, z, &w);
trick(x, &y, w, &z);
printf("%d %d %d %d", w,x,y,z);
getch();

Sample Program No. 9


/*Program Simulation */
#include"stdio.h"
void trick(int w, int *x, int y, int *z)
{
printf("\n%d %d %d %d", w,*x, y,*z);
++*x; --*z;
}

8 10 12 14
11 12 12 8
11 13 7 13
11 11 7 12
14 7 11 12
11 11 11 8
11 14 7 127 11 15 11

main()
{
int w=8, x=10, y=12, z=14;
clrscr();
trick(w, &x, y, &z);
trick(x, &y, y, &w);
trick(x, &y, w, &z);
trick(x, &x, w, &z);
trick(y, &w, z, &x);
trick(x, &z, z, &w);
trick(x, &y, w, &z);
printf("%d %d %d %d", w,x,y,z);
getch();
}

Sample Program No. 10


/*Program Simulation */
#include <stdio.h>
swap(int *x, int *y)
{
int temp;
temp = *x;
*x = *y;
*y= temp;

Prepared by: Ms. Elsa V. Isip

5 15
15 5
12 5
5 12
5 15

12
12
15
15
12

Technological Institute of the Philippines

C Language Programming

Page

38

}
main()
{
int x=5, y=12, z=15;
clrscr();
swap(&z,&y); printf("%d %d %d\n", x,y,z);
swap(&y,&x); printf("%d %d %d\n", x,y,z);
swap(&z,&x); printf("%d %d %d\n", x,y,z);
swap(&x,&y); printf("%d %d %d\n", x,y,z);
swap(&y,&z); printf("%d %d %d\n", x,y,z);
getch();
}
Sample Program No. 11
/*Program Simulation */
#include <stdio.h>
swap(int *x, int *y)
{
int temp;
temp = *x;
*x = *y;
*y= temp;
}

6 10
10 6
10 4
10 6
6 10

4
4
6
4
4

main()
{
int x=4, y=10, z=6;
clrscr();
swap(&z,&x); printf("%d %d %d\n", x,y,z);
swap(&y,&x); printf("%d %d %d\n", x,y,z);
swap(&z,&y); printf("%d %d %d\n", x,y,z);
swap(&y,&z); printf("%d %d %d\n", x,y,z);
swap(&x,&y); printf("%d %d %d\n", x,y,z);
getch();
}

Sample Program No. 12


/*Program Simulation */
#include"stdio.h"
balik(int *a, int b, int *c)
{
int d;
d=2;
b=*a+d;
d=b+*c;

Prepared by: Ms. Elsa V. Isip

240
644

Technological Institute of the Philippines

C Language Programming

Page

39

*a=d;
*c=b+d;
}
main()
{
int x, y, z;
clrscr();
x=y=z=0;
balik(&x,5,&y);
printf("%d %d %d\n",x,y,z);
balik(&z,y,&x);
printf("%d %d %d\n",x,y,z);
getch();
}

STRINGS
ARRAYS

OF CHAR AND

STRINGS

A character string is a sequence of characters which is to be considered as a single data item. The
characters of a string are displayed enclosed within double quotes. A string may include letters, digits,
symbols and control characters. Strings are used in application programs to store and process text data.

Prepared by: Ms. Elsa V. Isip

Technological Institute of the Philippines

C Language Programming

Page

40

Examples:
Input Error
123456
$890.99

STRING FUNCTIONS
header files : string.h

Copy
1.

strcpy() copy the contents of str2 to str1


syntax:
example:

strcpy(str1,str2)
char str1[8], str2[8];
strcpy(str1,hello);
strcpy(str2,there);
strcpy(str1,str2);
strcpystr2,str1);
printf(%s, str2);

output:

there

strncpy() used to copy to count characters from the string source_str2 into the
string target_str1, target_srt1 and source_str2 overlap, the behavior of this is
undefined; if string pointed by source_str2 has fewer count characters, nulls are
appended.

2.2

syntax:

strncpy(target_str1,source_str2,count);

example:
strcpy(str1,Hello);
strncpy(str1,str1,4);
output:
Hell
3. strxfrm() used to copy to count characters from the string source_str2 into the
string target_str1. It returns the length of the string source_str2. This function is
the same with the strncpy.
syntax:

strncpy(target_str1,source_str2,count);

Concatenate
1.

strcat() concatenates the value of str2 to str1


returns str1
contents of str2 is unchanged
syntax:

strcat(str1,str2);

Prepared by: Ms. Elsa V. Isip

Technological Institute of the Philippines

C Language Programming

example:

Page

41

char str1[15], str2[8];


strcpy(str1,Hello);
strcpy(str2,Folks!);
strcat(str1,there);
strcat(str1,str2);
printf(%s %s, str2,str1);

output:
Folks! HellothereFolks
2. strncat() concatenates no more than count characters of str2 to str1 and assigns this
to str1; str2 is untouched by the operation
syntax:

strcat(str1,str2,count);

Compares
1. strcmp() compares the two strings until unequal characters are found or until the end
of a strings is reached. It returns an integer to indicate the results of the compare
based on the following:
Value

Meaning

< 0

str1 is less than str2

str1 is equal to str2

>0

str1 is greater than str2

syntax: strcmp(str1,str2);
example:
char s[10];
printf(Enter password: );
gets(s);
if (((strcmp(s,pass)) ==0))
printf(Welcome);
else
printf(Intruder!!!);
2.

stricmp()/ strcmpi()
compares two strings while ignoring cases; strcmpi() is a
macro that translates to a strcimp() call
syntax:

strcmpi(str1,str2); / stcricmp(str1, str2);


Value

Meaning

< 0

str1 is less than str2

str1 is equal to str2

>0

str1 is greater than str2

3. strucmp() / strncmp() / strncmpi() compares no more than count characters for the
two strings; strncmpi() and strnicmp() ignore cases.
syntax:

strucmp(str1,str2,count); / stcrncmp(str1, str2,count); stcrncmpi(str1,


str2,count);

Case

Prepared by: Ms. Elsa V. Isip

Technological Institute of the Philippines

C Language Programming

Page

42

1. strlwr() converts the string pointed to by str in lowercase.


syntax:

strlwr(str);

example:
char s[20];
strcpy(s,A TEST);
strlwr(s);
printf(%s,s);
2.

strupr() converts the string pointed to by str in uppercase.


syntax:

Set

1.

strset() sets all characters in str to the value of chr.


syntax:
example

output:
2.

strset(str,chr);
strcpy(str,HELLO);
strset(str,E);
EEEEE

strnset() sets the first count character in the str to the value of chr.
syntax: strnset(str,chr,count)
example

output:

strupr(str);

Others
1.

strcpy(str1,HELLO);
strnset(str1,A,3);
AAALO

strlen() returns the length of the string.


syntax:

2.

strlen(str);

example:
char s[20];
int x;
gets(s);
x=strlen(s);
printf(The length is %d, x);
strrev() reverses all the characters in the string pointed to by str.
syntax:

strrev(str);

example:

Prepared by: Ms. Elsa V. Isip

Technological Institute of the Philippines

C Language Programming

Page

43

char s[10];
gets(s);
strrev(s);
printf(%s, s);

CHARACTER FUNCTIONS
header files : ctype.h
1. isalnum() a function that returns non-zero if its argument is either a letter of the alphabet
or a digit.
syntax:
int isalnum(int char);
2. isalpha() a function that returns non-zero if char is a letter of the alphabet otherwise zero
is returned.
syntax:
int isalpha(int char);
3. isdigit() a function that return non-zero if char is a digit, that is 0-9; otherwise zero is
returned.
syntax:
int isdigit(int char);
4. islower() a function that returns non-zero if char is a lowercase letter (a-z); otherwise zero
is returned.
syntax:
int islower(int char);
5. ispunct() a function that returns non-zero if char is a punctuation character, excluding the
space; otherwise zero is returned.
syntax:
int ispunct(int char);
6. isspace() a function that returns non-zero if char is one of the following: a space, tab,
vertical tab, form feed, carriage return, newline; otherwise zero is returned.
syntax:
int isspace(int char);
7. tolower() returns the lowercase equivalent of the character pointed to by char, if char is in
lowercase it is unchanged.
syntax:
int tolower(int char);
example:
char ans;
scanf(%c, &ans);
if (tolower(ans)==y)
printf(bye);
else
printf(again?);
8. toupper() returns the uppercase equivalent of the character pointed to by char, if char is in
uppercase it is unchanged.
syntax: touppper(char);

Prepared by: Ms. Elsa V. Isip

Technological Institute of the Philippines

C Language Programming

Page

44

MATHEMATICAL FUNCTIONS
header file : math.h
1. abs() a function that returns the absolute value of integer number.
syntax:
int abs(int num);
2. ceil() a function smallest integer represented as double not less than num.
syntax:
double ceil(double num);
3. fabs() a function that return the absolute value of num.
syntax: double fabs(double num);
4. floor() a function that returns the largest integer, represented as double not greater than
num.
syntax:
double floor(double num);
5. fmod() a function that returns the remainder of x / y.
syntax:
double fmod(double x, double y);
6. pow() a function that returns based to the exp power (base exp.)
syntax:
double pow(double base, double exp);
7. pow10() returns 10 raised to the power n. Overflow and undeflow are the only possible
errors.
syntax:
double pow10(int n);
8. sqrt() returns the square root of num. If called with a negative argument domain error will
occur.
syntax: double sqrt(double num);

CONVENTIONAL FUNCTIONS
header file : math.h
1. atof() a function that converts the string pointed to be str into a double value.
syntax:
double atof(const char *str);
2. atoi() a function that converts the string pointed to by str into an int value. The string must
contain valid into value, if not zero is returned.
syntax:
int atoi(const char *str);
3. atol() a function that that converts the string pointed to by str into a long int value. The
string must contain valid long int value.
syntax: int atol( const char *str);

Prepared by: Ms. Elsa V. Isip

Technological Institute of the Philippines

C Language Programming

Page

45

a function that converts the integer number into string equivalent and places the
result in the string pointed to be str. The base of the output string is determined by radix
which can be in the range of 2-36. this function returns a pointed to str. There is no error
return value. Be sure to call itoa() with string of sufficient length to hold the converted
result. The maximum length needed is 17 bytes.
syntax:
char *itoa(int num, char *str, int radix);

4. itoa()

Prepared by: Ms. Elsa V. Isip

Technological Institute of the Philippines

C Language Programming

Page

46

ARRAYS
ARRAY

collection of variables of the same type that are referenced by a common name. A
specific element in an array is accessed by an index. The lowest address corresponds to
the first element and the highest address corresponds to the last element. All arrays
have 0 as the index of their first element.
Is a fixed-size, sequenced collection of elements of the same data type.

Sample Representation:
Assuming we have a problem that requires 30 integers to be processed. We need to read,
processed and print them. We must also keep these 30 integers in memory for the duration of the
program. We can declare and define 30 variables, each with a different name, as shown in the
illustration below.

Num0
Num1
Num2

Num29

Explanation:
This will involved thirty variables but having 30 different names creates another
problem. How can we read 30 integers from the keyboard and store them? To read 30 integers
from the keyboard, we need thirty references, each to one variable. Another thing, once we
have them in memory, how can we print them? To print them, we need another thirty
references.
But in this situation, 30 integers may be acceptable but it definitely not acceptable
for 500 or 3,000 or 30,000 integers. To process such large amount of data, we need a powerful
data structure, such as array.

USING ARRAYS

IN

The advantages of the array would be limited if we didnt also have programming constructs that
would allow us to process the data more conveniently. Fortunately, there is a powerful set of
programming constructs using loops that makes array processing easy.

Prepared by: Ms. Elsa V. Isip

Technological Institute of the Philippines

C Language Programming

Page

47

We will first show how to declare and define arrays. Afterwards, we will look at several typical
applications using arrays including reading values into arrays, accessing and exchanging elements in
arrays and printing arrays.

How to declare and define arrays?

An array must be declared and defined first before it can be used. Through declaring and defining
arrays will tell the compiler the name of the array, the type of each element, and the size or number of
elements in the array. The size of the array is a constant and must have a value at compilation time.
Syntax:
element_type array_name[array_size];
where:
element_type type of each elements
array_name name of the array
array_size
number of elements the array will hold
Example Declaration:
int scores [9];

type of
each
element

[0] [1]

[2]

[3]

[4]

[5]

[6]

[7]

[8]

scores

char name [10];


[0] [1]

[2]

name of
the array

[3]

[4]

[5]

[6]

[7]

[8]

[9]

name

float gwa [40];


[0]

number of
elements

[1]

[2]

. . .

[37] [38]

[39]

gwa

Sample Program:
#include <stdio.h>
#include <conio.h>
int score[30], x,sum=0;

array
void main
declaration
{
clrscr();
printf("Please enter 30 scores:\n ");
for (x=0;x<30;x++)
{
scanf("%d",&core[x];

Prepared by: Ms. Elsa V. Isip

Technological Institute of the Philippines

C Language Programming

Page

48

sum = sum + scorex[x];


}
getch();

Accessing Elements in Arrays


C uses an index (or subscript) to access individual elements in an array. The index must be an
integral value or an expression that evaluates to an integral value. The simplest form for accessing an
element is a numeric constant.

Syntax:
array_name[index]
Example:
Given an array score[30], we could access the first element as score[0].
Storing Values in Arrays
Declaration and definition only reserve for the elements in the array. No values will be stored. If we
want to store in the array, we must either initialize the elements, read values from the keyboard, or
assign values to each individual element.

Initialization
Initialization of all elements in an array can be done at the time of declaration and
definition, just as with declaration of variables. For each element in the array, provide a value
and these should be enclosed in curly braces, { }. And if there are more than one, separated by
commas. It is a compile error to specify more values than there are elements in the array.

Examples of array Initialization:


int numbers[5] = {2,5,10,22,44};

10

22

44

this is just a simple array declaration of five


integers. It is typically the way array initialization
is coded.

int numbers[ ] = { 2,5,10,22,44};


when the array is completely initialized, it is not

10

22

44

int numbers[5]; = {2,5};

necessary to specify the size of the array

if the number of values provided is less than

the number of elements in the array, the


unassigned elements are filled with zeros. We
can use this rule to easily initialize an array to
all zeros by supplying just the first zero value
of the first element.

the rest are


filled with
0s
Prepared by: Ms. Elsa V. Isip

Technological Institute of the Philippines

C Language Programming

Page

49

int lotsOfNum[1000] = {0};

all filled
with 0s

Inputting Values
Another way to fill the array is to read the values from the keyboard or a file. This can be
done using a loop. When the array is going to be completely filled, the most appropriate
loop is the for loop because the number of elements are fixed and known.

Example:
int score[5];
.
.
for (x = 0; x < 5; x++)
scanf(%d, &score[x]);
Interpretation:
Several concepts need to be studied in this simple statement. First, we begin the index
, x at zero. Since there are five elements in the array, we must load the values from index
locations zero through 4. the limit test, therefore, is set at x < 5, which conveniently is the
number of elements in the array. Then, even though we are dealing with array elements,
the address operator (&) is still necessary in the scanf call.
Finally, when there is a possibility that all the elements are not going to filled, then
one of the event-controlled loops should be used. Which you use would depend on the
application.

Assigning Values

Individual elements can be assigned values using the assignment operator. Any value
that reduces to the proper type can be assigned to an individual array element.

Example:
double x[8];

array x

x[0]

x[1]

x[2]

x[3] x[4]

16.0

12.0

6.0

25.0

8.0

x[5]

x[6]

11.0

14.0

x[7]
24.0

Statement that manipulate Array X


Statement
printf (%.lf, x[0]);
x[3] = 25.0;

Prepared by: Ms. Elsa V. Isip

Explanation
Displays the value of x[0], which is 16.0.
Stores the value 25.0 in x[3].

Technological Institute of the Philippines

C Language Programming

Page

50

sum = x[0] + x[1];

Stores the sum of x[0] and x[1], which


is 28.0 in the variable sum.
sum += x[2];
Adds x[2] to sum. The new sum 34.0.
x[3] += 1.0;
Adds 1.0 to x[3]. The new x[3] is 26.0.
x[2] = x[0] + x[1];
Stores the sum of x[0] and x[1] in x[2].
The new x[2] is 28.0.
An array cannot be assigned to another array, even if they match fully in type and size.
To copy whole arrays, copy at the individual element level.
Example:
To copy an array of 20 integers to a second array of 20 integers, you could
use a loop as shown below:
for ( x = 0; x < 20; x++)
second[x] = first[x];

Sample Program No. 1


/* Prints the reverse of the entered string */
#include <stdio.h>
main()
{
char s[10];
int x, ctr;
clrscr();
printf("Enter A String : ");
gets(s);
x=strlen(s)-1;
for (ctr=x;ctr>=0;ctr--)
printf("%c",s[ctr]);
getch();
}

Enter a String:
Elsa
aslE

Sample Program No. 2


/* Program that determines the highest number and average of 5 numbers*/
#include <stdio.h>
main()
{
int num[5],sum=0, ave, ctr, hn, x;
Enter 5 numbers :
clrscr();
22334
printf("Enter 5 numbers :\n");
The highest noumber is 4
for (ctr=0;ctr<=4;ctr++)
The average is 2
scanf("%d",&num[ctr]);
hn=0;
for (ctr=1;ctr<=4;ctr++)
if (num[ctr] > hn)
hn=num[ctr];
for (ctr=0;ctr<=4;ctr++)
sum=sum+num[ctr];
ave=sum/5;
printf("The highest noumber is %d", hn);
printf("\nThe average is %d", ave);
getch();

Prepared by: Ms. Elsa V. Isip

Technological Institute of the Philippines

C Language Programming

Page

51

Sample Program No. 3


/* Arrange the number in ascending order */
#include <stdio.h>
main()
{
int num[5], ctr1, ctr2, temp;
clrscr();
printf("Enter 5 numbers :\n");
for (ctr1=0;ctr1<=4;ctr1++)
scanf("%d",&num[ctr1]);
for (ctr1=0;ctr1<=3;ctr1++)
for (ctr2=ctr1+1;ctr2<=4;ctr2++)
if (num[ctr1] > num[ctr2])
{ temp = num[ctr1];
num[ctr1] = num[ctr2];
num[ctr2] = temp;
}
printf("The numbers in ascending order \n");
for (ctr1=0;ctr1<=4;ctr1++)
printf("%d ",num[ctr1]);
getch();
}

Enter 5 numbers :
14352
The numbers in ascending
order
12345

Sample Program No. 4


/* Display the number of times a number appeared */
#include <stdio.h>
main()
{
Enter 5 numbers :
int num[5], ctr, x, y;
13231
clrscr();
The numbers are :
printf("Enter 5 numbers :\n");
1 appears 2 time(s)
for (ctr=0;ctr<=4;ctr++)
3 appears 2 time(s)
scanf("%d",&num[ctr]);
2 appears 1 time(s)
printf("The numbers are : \n");
for (x=0;x<=4;x++)
{ ctr=1;
if ((x==4)&&(num[x]>=0))
printf("%d appears %d time(s)\n", num[x], ctr);
else if (num[x]>=0)
{
for (y=x+1;y<=4;y++)
if (num[x] == num[y])
{
num[y]=-1;
ctr+=1;
}
printf("%d appears %d time(s)\n", num[x], ctr);

Prepared by: Ms. Elsa V. Isip

Technological Institute of the Philippines

C Language Programming

Page

52

}
}
getch();

MULTIDIMENSIONAL ARRAY(TWO DIMENSIONAL ARRAY)


Syntax:
type arr_name[2dim][1dim];
column
row

Sample Program No. 1


/* Program Simulation */
#include <stdio.h>
int t, n, num[3][3];
main()
{ clrscr();
for (t=0;t<=2;t++)
for (n=0;n<=2;n++)
num[t][n]=(2*4)+n;
for (t=0;t<=2;t++)
{
for (n=0;n<=2;n++)
printf("%d",num[t][n]);
printf("\n");
}
getch();
}

8910
8910
8910

Sample Program No. 2


/* Multiplication Table using ARRAY */
#include <stdio.h>
int num[5][5],ctr, ctr2, x, y;
main()
{
clrscr();
x=y=0;
for (ctr=1;ctr<=5;ctr++)
{
for (ctr2=1;ctr2<=5;ctr2++)
{
num[x][y]=ctr*ctr2;
y++;
}
x++;
y=0;
}
for (ctr=0;ctr<=4;ctr++)

Prepared by: Ms. Elsa V. Isip

12345
246810
3691215
48121620
510152025

Technological Institute of the Philippines

C Language Programming

Page

53

for (ctr2=0;ctr2<=4;ctr2++)
printf("%d",num[ctr][ctr2]);
printf("\n");

}
getch();
}

Sample Program No. 3


/* Sum of each row and column */
#include <stdio.h>
int num[3][3],a_col[3], a_row[3], x, y;
int cols, rows;
main()
{

clrscr();
printf("Enter Number in 3 x 3 matrix :");
cols=5; rows=2;
for (x=0;x<=2;x++)
{
for (y=0;y<=2;y++)
{
gotoxy(cols,rows);
scanf("%d",&num[x][y]);
cols+=3;
}
cols=5;rows++;
}

Enter Number in 3 x 3 matrix :


123
121
123
6 4 6
3 6 7

for (y=0;y<=2;y++)
for (x=0;x<=2;x++)
{
a_row[y]=a_row[y] + num[y][x];
a_col[x]=a_col[x] + num[y][x];
}
cols=5;
for(x=0;x<=2;x++)
{
gotoxy(cols,7); printf("%d",a_row[x]);
gotoxy(cols,8); printf("%d",a_col[x]);
cols+=3;
}
getch();
}

Prepared by: Ms. Elsa V. Isip

Technological Institute of the Philippines

C Language Programming

Page

54

STREAM AND FILES


STREAM
a series of bytes associated with a file.

Types of Streams:

Text Stream is a sequence of characters that does not have a one-to-one relationship
between the characters that are written or read and those on the external device.
Binary Stream is a sequence of bytes that have a one-to-one correspondence to those found
on the external device. The number of bytes written or read will be the same as the number
found on the external device.

1.
2.

FILE
a collection of data stored in the memory.
Files reside in the secondary memory

Text file
Binary file

Text File contains characters which are encoded in ASCII format.


it contents can be viewed by using any text editor.
Examples:
autoexec.bat
config.sys files
C source code
Binary File a file that contains data which are encoded in binary format (ex. Combination of 0 and
1).
its format shoulf be known in advance to be able to read and decode its contents properly.
Examples:

MS Word Documents

Excel Spreadsheets

Database files

Steps in Processing a File


1.
2.
3.
4.

Declare a file pointer that will be associated to a specific file.


Open the file.
Read / write from/to a file .
Close the file.

Prepared by: Ms. Elsa V. Isip

Technological Institute of the Philippines

C Language Programming

Page

55

Operations in a File
1.
2.
3.
4.

Open a file.
Close a file.
Read the contents of a file.
Write to a file.

File Handling Concepts


1. Establish a stream betweern the file and the program.
2. Perform the needed read / write operation to the file.
3. Close the file to detach the program from the file.
The ANSIC File System
The ANSI C file system is composed of several interrelated functions. The most common are shown
below:
Commonly Used Functiond in ANSI C File Handling Operations:
fopen() establishes a stream between a program and a file. It is used to open files.
fscanf(), fgetc(), fgets() used for input data from files. Counterparts of functions scanf(),
getchar() and gets().
fprintf(), fputc(), fgets() - used for output of data to a file. Counterparts of functions printf(),
putchar() and puts().
feof() - to check for end-of-file marker during input operation.
fclose() to close a file or detach a file from the program.

The File Pointer


File Pointer is a pointer to information that defines various things about the file, including its name,
status, and current position.
it identifies a specific disk file and is used by the stream associated with it to tell each of the
bufferred I/O operations where to perform operations.
is a pointer variable of type FILE, which is defined in stdio.h.
Syntax:
FILE *fileVariable;

Opening Files
fopen() function - opens a stream for use, links a file with that stream, and then returns a FILE pointer
to that stream. Most often, the file is a disk file.
Syntax:
InternalFileName = fopen (ExternalFileName, OpenMode);
where:
InternalFileName is a variable which represents the file in the program.
ExterbalFileName is the actual namr of the file that is being opened.
OpenMode is the mode pointing to a string containing the desired status.

Prepared by: Ms. Elsa V. Isip

Technological Institute of the Philippines

C Language Programming

Page

56

The Legal Values for OpenMode

Open
Mode
r
w
a
rb
wb
ab
r+
w+
a+

Meaning

Open
Mode

Meaning

Open a text file for reading


Create a text file for writing

r+b
w+b

Open a binary file for read / write


Create a binary file for read / write

Append to a text file


Open a binary file for reading
Create a binary file for reading
Append to binary file
Open a text file for read/write
Create a text file for read/write
Open or create a text file for read /
write

a+b
rt
wt
at
r+t
w+t
a+t

Open or create a binary file for read / write


Open a text file for reading
Create a text file for writing
Append to a text file
Open a text file for read / write
Create a text file for read / write
Open or create a text file for read / write

If you wish to open a file for writing with the name TIPQC.TXT, write
fp = fopen (TIPQC.TXT,w);

Note:

where: fp is a variable of type FILE

TIPQC.TEXT is not case sensitive and can be


written in uppercase or lowercase letters.

However, it is best written in this manner


if ((fp =fopen (TIPQC.TXT,w)) == NULL)
{
puts( Cannot open file);
exit(1);
}
This method detects any error in opening file, such as a write-protect or full disk, before attempting
to write it. NULL is a macro defined in stdio.h.

Writing Data to Text Files


fprintf() writes formatted output to a stream.
the same as the printf() command but instead of writing the output to the screen, the output
is written to a file.
Syntax:
fprintf(InternalFileName, FormatControlString, WriteList);
Example:
fprintf(fp,%s\n, TIPQC);

Writes the text TIPQC to the specified


by the file fp.
Output:

TIPQC

fputc() writes a character to a stream.


Syntax:
fputc(CharacterExpression,InternalFileName);
Example:
fputc(H, fp);
fputc(e, fp);

Writes Hello to the specified by the


file fp.
Output:

Prepared by: Ms. Elsa V. Isip

Hello

Technological Institute of the Philippines

C Language Programming

Page

57

fputc(l, fp);
fputc(l, fp);
fputc(o, fp);
fputs() writes a string to a stream.
Syntax:
fputs(StringExpression,InternalFileName);

Output:
Technological Institute of the Philippines
CS/IT/IM Department

Example:
fputs(Technological Institute of the Philippines\n,fp);
fputs(CS/IT/IM Department, fp);

Example:
Assume that we declare the variable outdata as
And open it in the output mode

FILE *outdada:
outdata = fopen (A:\OUT.TXT, w);

Let us assume that we have the following declarations:


int value1 = 10, value2 = 20;
double value3 = 15.75;
char value4 = x, value5 = y;
char value6[ ] = C Language Programming;

Statement

Output

fprintf(outdata, %d\n, value1);


fprintf(outdata, %d%d\n, value1, value2);

10
1020

fprintf(outdata, %f\n, value3);


fprintf(outdata, %c%c\n, value4, value5);
fputc(value4, outdata);
fputc(value5, outdata);
fputc(\n, outdata);
fputs(value6, outdata);
fputs(\n, outdata);
fprintf(outdata,%d %d %f %c %c %s\n,
value1, valu2, value3, value4, value5,
value6);

15.750000
xy
xy
C Language Programming
10 20 15.750000 x

C Language Programming

Reading Data from Text Files


fscanf() scans and formats input from a stream.
scans a series of input fields, one character at a time, reading from a stream. Then each field
is formatted according to a format specification passed to fscanf().
Syntax:
fscanf(InternalFileName, FormatControlString, InputList);
Example:
1. fscanf(fp,%c, &var);

Prepared by: Ms. Elsa V. Isip

retrieves the character pointed by the file pointer at the


stream and stores the character in the variable var.

Technological Institute of the Philippines

C Language Programming

Page

58

2. fscanf(fp,%s, &svar);

retrieves a string pointed by the file pointer at the stream and


stores the string in the variable svar.

3. while (!feof(fp)) {
fscanf(fp, %c, &a);
printf(%c, a);
}

retrieves the contents of the file pointed by the file pointer one
at a time and displays them on the screen.

fgetc() gets a character from the stream.


Syntax:
variable = fgetc(InternalFileName);
Example:
1. var = fgetc(fp);

retrieves the character pointed by the file pointer at the


stream and stores the character in the variable var.

2. while (!feof(fp)) {
a = fgetc(fp);
printf(%c, a);
}

retrieves the contents of the file pointed by the file pointer one
at a time and displays them on the screen.

fgets() gets a string from a stream.


Syntax:
fgets(StringVariable, CharacterCount, InternalFileName);
Example:
Assume that the content of the file DUMMY.FIL is
TIP QUEZON CITY
A.The
ADDING
TEXT TO A TEXT FILE
command

B. READING TEXT FROM A TEXT FILE

/* --------ADDING
TEXT
TO FILE------*/
/* --------READING TEXT FROM A FILE-----*/
fgets(p,3,
fp);
/*-------------ADDTXT.C---------------*/
/*-------------READTXT.C---------------*/
printf(%s, p);
displays TIP
to the screen.
#include <stdio.h>
main()

#include <stdio.h>
main()

{
FILE *fp;
char str[80];

FILE *fp;
char a;

clrscr();
printf(Enter String:);
gets(str);

clrscr();
if((fp=fopen)TIPQC.TXT,r))==NULL)
{

if((fp=fopen)TIPQC.TXT,w))==NULL)
{
puts(Cannot Write File!);
exit(0));
}
fprintf(fp, %s\n,str);
fclose(fp);
}

Prepared by: Ms. Elsa V. Isip

puts(Cannot Write File!);


exit(0));

while (! Feof(fp))
{
a = fgetc(fp);
printf(%c, a);
}
fclose(fp);
getch();Technological Institute of the Philippines
}

C Language Programming

Page

59

In the example, the first program will ask the user to input a string. The string will then be saved in
the file TIPQC.TXT. the second program will retrieve the contents of the file and display them on the
screen. Note that the open mode used in the first program is w. This means that a new file will be
created every time the first program is executed. The previous contents of the file are replaced by the
new string entered.
You can use the open mode a to enable the file to append entries so that previous contents are not
lost and that new entries are added to the file.
feof() checks for end-of-file status during input.
Syntax:
feof(InternalFileName);
Example:

gotoxy(22,20); printf(Save this entry to your file(Y/N)?);


ans
= getche();
Text
File Saving
Using
Structures
fclose()
to close
a file
or detach a file from the
program.
gotoxy(22,20); clrcol();
if(toupper(ans)==Y)
#include
<stdio.h>
Syntax:
{
#include <ctype.h>
fclose(InternalFileName);
if((fp = fopen (FACTS.BIO,a)) == NULL)
{
struct facts {
gotoxy(27,20); printf(Cannot create file1);
char name[25];
exit(0);
char addr[30];
}
char bday[20];
char age[2];
fprintf(p, NAME
:%s\n,x[a].name);
char telno[10];
fprintf(p, ADDRESS :%s\n,x[a].addr);
};
fprintf(p, BIRTHDAY :%s\n,x[a].bday);
fprintf(p, AGE
:%s\n,x[a].age);
main()
fprintf(p, TEL. NO.
:%s\n,x[a].telno);
{
fprintf(p, \n);
FILE *p;
fclose(p);
struct facts x[100];
}
int a=0, b;
char ans, ans2;
clrscr();
gotoxy(33,3); printf(FACTS ABOUT ME);
gotoxy(15,5); printf(NAME:);
gotoxy(15,7); printf(ADDRESS:);
gotoxy(15,9); printf(BIRTHDAY:);
gotoxy(15,11); printf(AGE:);
gotoxy(15,13); printf(TEL. NO.:);
do{
gotoxy(30,5); gets(x[a].name);
gotoxy(36,7); gets(x[a].addr);
Prepared by: Ms. Elsa V. Isip
gotoxy(30,9); gets(x[a].bday);
gotoxy(30,11); gets(x[a].age);
gotoxy(30,13); gets(x[a].telno );

gotoxy(27,20); printf(Add Another Entry(Y/N)?);


ans2 = getche();
if(toupper(ans2)==Y)
{
gotoxy(30,5); clrcol();
gotoxy(30,7); clrcol();
gotoxy(30,9); clrcol();
gotoxy(30,11); clrcol();
gotoxy(30,13); clrcol();
}
Technological
Institute
the Philippines
} while((toupperans2_
==
Y) && of
(a<100));

You might also like