Sie sind auf Seite 1von 70

Structured Programming in C

Diploma in Information Technology

Structured Programming in C

Semester - 3

Cyryx College

Page 1 of 70

Structured Programming in C

Structured Programming in C
What is C?

C is a programming language developed at AT&Ts Bell laboratories of USA in 1972 by


Dennis Ritchie.
C is so popular, because it is reliable and easy to use.

Historical development of C:By 1960 computer language had come to existence, almost each for a specific purpose.
E.g.:

COBOL
-> used for commercial applications.
FORTRAN -> used for Engineering & Scientific applications.

At this stage people started thinking that learning and using so many languages. Each for a
different purpose. So international committee setup to develop a language called ALGOL
60. But it was not popular, because that was too abstract and too general.
To reduce this abstractness and generality, a new language called CPL (Combined
Programming Language) by Cambridge University. But it was also not popular, because it
was so big and hard to learn (So many features)
BCPL (Basic Combined Programming Language) by Martin Richard at Cambridge
University aimed to solve the problems. But it was too less powerful and too specific.
At the same time Ken Thompson at AT&T Bell lab introduced a language called B But
B also turned out to be very specific.
Ritchie, B&BCPL, added some of his own and developed C
RITCHIES main achievement is the restoration of the lost generality in BCPL and B and
still keeping it powerful.
C is a one-man language.

Various Stages in evolution of C language:


Year
Language
Developed by

International
Committee
Cambridge
University
Martin Richard at
Cambridge

1960

ALGOL

1963

CPL

1967

BCPL

1970

Ken Thompson

1972

Dennis Ritchie

Cyryx College

Remarks
(i) Too general.
(ii) Too abstract.
Hard to learn
Could deal only with
specific problem.
Could deal with only
specific Problem
Lost generality of

Page 2 of 70

Structured Programming in C
BCPL and B
restored.

Where C Stands:

All programs are divided into two categories.


1.
Problem Oriented Language
(Or)
High Level language (Helps to design to give better programming
efficiency,(i.e.) faster program development.)
E.G. FORTRAN, BASIC, PASCAL
2.

Machine Oriented Language


(Or)
Low Level Language (Design to better machine efficiency).
E.G. Assembly language & Machine Language

C is having these two categories. Both


Machine Oriented
&
Problem Oriented Language.
So C is a MIDDLE LEVEL LANGUAGE.

Steps to learn C
Alphabets
Digits
Special Symbols

Constants
Variables
Keywords

Instructions

Program

Alphabets: - A, B, CZ
A, b, c z
Digits:-

0,1,2,.9

Special
Symbols:-

~!@#%^&*()_-+=|\{}[]:;<>,.?/

Constants: a=20 (here 20 is the constant value for a)


Type of Constant

Primary Constant

Integer Constant
Real Constant
Character Constant
Cyryx College

Secondary Constant

Array, Pointer
Structure, UNION,
Etc.
Page 3 of 70

Structured Programming in C

Rules for Integer Constant:

At least one digit


Must have a decimal point
Either positive or negative, default is +ve
No commas, blanks.
Range is 32768 to +32767.
E.G.

426
+ 782
- 800
- 7605

Rules for Real Constants/Floating Points

At least one digit.


Must have a decimal point.
Either positive or negative, default is +ve.
No Commas, Blanks.
Eg:

+325.34
426.0
-32.76
-48.5798.

Rules for Character Constant

Single Alphabet or a single special symbol enclosed within single inverted


commas.
Maximum length can be 1 character.

Declaration of the character constants

Char x;
Char x, y, z;
The char stands for the character data for declaring the character constants. The declaration
format of character data type is same as that of the declaration of integer, floating or string
constants.
We use the backslash \ to denote nor-graphic characters and other special characters for
specific operations. The following characters are used as a non-graphic character:
\n
\n
\b
\r
\f

Cyryx College

new line (line feed)


horizontal tab
backspace
carriage return
form feed

Page 4 of 70

Structured Programming in C
\\
back slashes
\
single quote
\0
null character (an important special case of this is null character \0 to be
distinguished from 0.(Zero, not the alphabetic letter o)

C Variables:-

A quantity which may vary during program execution is called a variable.

Rules:

1 to 8 alphabets, digits or underscores.


1st character must be a character
No commas, blanks within a variable name
No special symbol, other than _ (underscore).
E.G:

st_int
m_hrs
pop_e_sqt.

Keywords /Reserved Words


Whose meaning has already been explained to a compiler
The keywords are also identifiers but cannot be user defined since they are reserved words.
The following words are reserved for use as keywords. We must not choose them as
variables or identifiers.
The Following words are keywords:auto
break
case
char
const
continue
default
do

double
else
enum
extern
float
far
for
goto

if
int
long
near
register
return
short
signed

static
struct
switch
typedef
union
unsigned
void
while

Some compilers also regard asm and fortran as keywords. These above said reserved
words have already been declared in the c compiler as standard words to perform predefined
operations. For example, goto is a keyword and it cannot be used as an ordinary variable.
C Operators:The following sections explain he different types of C operators and their usage. In c,
there are some unusual operators used to perform the tasks of logical decision making unlike
other higher level languages.

Cyryx College

Page 5 of 70

Structured Programming in C

C- Operators
Arithmetic operators
Assignment operators
Comparison & logical
operators

Relational

Bitwise logical
operators

Equality

Special operators

Logical
Unary Operators
Ternary Operators
Comma Operator

Other operators

Arithmetic Operators
Arithmetic operators are the basic and common operations in a computer programming
language. Normally these operators are considered as basic operators known as binary
operator since they require two variables to be evaluated. For example, if we want to
multiply any two numbers, one has to enter or feed the multiplicand and multiplier. That is
why it is considered as a binary operator. In C the arithmetic operators are as follows:
Operator
+
*
/
%

Meaning
Addition
Subtraction
Multiplication
Division
modulo (remainder of integer division)

The operator /(slash) for division deserves a special attention. If we divide an integer by
another integer, we obtain an integer value.

Cyryx College

Page 6 of 70

Structured Programming in C
39/5=7
In the x/y at least one of the operands x and y has floating point type, if the result will be
floating point type. Incidentally, this also applies to addition, subtraction and multiplication.
For the latter operations the type of operands does not seriously affect the value of the
result.
Assignment Operators
An assignment operator is used to assign a value to a variable.
Operator
=

Meaning
Assign right hand (RH) value to the left hand (LH) side

the symbol = is used as an assignment operator, and it is evaluated last. Remember that
equal to(=) is an operator and not an equation marker, so it can appear anywhere in place of
another operator. The following are legal C Statements.
a=b =c+4;
c=3*(d=12.0/x);
for Example,
x+=y is equal to
x-=y is equal to

x=x+y;
x=x-y;

Comparison and logical operators


For program flow, the comparison operators as well as logical operators are required. The
comparison and logical operators can be grouped into three. There are relational operators,
equality operators and logical operators.
Operator
<
>
<=
>=
==
!=
&&
||
!

meaning
Less than
Greater than
less than or equal to
Greater than or equal to
equal to
not equal to
Logical AND
Logical OR
Not

Relational operators

Relational operators compare the values to see if they are equal or if one of them is greater
than the other and so on. For program flow, the comparators and the logical operators are
essential.
Relational operators in C produce only a one or a zero result. These are often specified of as
true or false respectively, since there are only two values possible. The following
operators are used to perform the relational operations of the two variables or expressions.

Cyryx College

Page 7 of 70

Structured Programming in C

Operator
<
>
<=
>=

Meaning
Less than
Greater than
Less than or equal to
Greater than or equal to

The relational operators are represented in the following syntax


expression

relational operator

expression 2

The expression 1 will be compared with expression 2 and depending upon the relation like
greater than, greater than equal to and so on, the result will be either true or false.
For example,
Expression
3>4
6<=2
10>-32
(23*7)>=(-67+89)

result
false
false
true
true

Equality operators

The following operators are used to check the equality of the given expression or a
statement. These operators are normally represented by using the two keys like equal to will
be the operator == and not equal to will be != and note that the single equal to sign is
considered as an assignment operator in C. Proper care must be taken while using these
operators.
Operator
==
!=

Meaning
Equal to
Not equal to

Like the relational operators, the equality operators also produce the result of either true or
false, depending upon the condition used in a program. The following examples show the
equality operators usages
For example, a=4, b=6, and c=8
Expression
a==b
(a*b) !=c
s==y

Logical operators

result
false
true
false

The logical operators && and || are lower in precedence than the relational operators < and
> which are lower than + and -. The operator && is higher than the operator ||. Some

Cyryx College

Page 8 of 70

Structured Programming in C
other languages place the logical operators higher than the relational operators, which
require parenthesis.
Operator
&&
||
!

Meaning
Logical and
Logical or
Logical Not.

Logical AND

The compound expression is true when two conditions (expressions) are true. To write both
conditions, use the operator && in this manner.
expression 1 && expression 2
The two expressions must be integer data types. The char data are converted to integer and
are thus allowed in the expression.
Example,
a=4, b=5, and c=6
(a<b) && (b<c)
(4<5)&& (5<6)
true && true
true

Logical OR

Similar to the Logical AND is the Logical OR, which has the form.,
expression1 || expression2
and evaluates to true if either expression 1 or expression 2 is true.
Example,
a=4, b=5, and c=6
(a>b) || (b>c)
(4<5) || (5>6)
true || (5>6)
true
In the logical OR operator, if one of the expression is true, then it yields true.

Special operators
There are special operators used in the C language to perform some particular type of
operations. The following operators are the unary operators in the C language.
a)Unary Operators
The unary operators require only single expressions to produce a line. Unary operators
usually precede their single operands. Sometimes some unary operators may be followed the

Cyryx College

Page 9 of 70

Structured Programming in C
operands such as incrementer and decrementer. The most common unary operation is unary
minus. Where a minus sign precedes a numerical constant, a variable or an expression. The
following operators are the unary operators in C.
Operators
+
&
!
++
-type
sizeof

Meaning
Contents of the storage field to which a pointer is pointing
Address of a variable
Negative value (minus sign)
Negation (0, if value #0, and 1, if value =0)
Incrementer
Decrementer
forced tyoe of conversion
Size of the subsequent data type or type in byte.

Pointer Operator(*)

The pointer operator is used to get the content of the address operator pointing to the
particular memory element or cell.

Address operator (&)

The address operator & is used to get the address of the other variable in an indirect
manner.

Sizeof operator

The sizeof operator is used to give the direction to the C compiler to reserve the memory
size or block to the particular data type which is defined in the structure type of data in the
linked list.

Incrementer and decrementer

In the C language there are two special operators used : incrementer decrementer. These
operators are used to control the loops in an effective method.
Incrementer
The ++ symbol or notation is used for incrementing by 1.
For Example,
++i; equal to
i=i+1;
i++; equal to
i=i+1;
There are two types of incrementers: prefix incrementer (++i), postfix incrementer (i++).
In prefix incrementer, first increment and do the operation . On the other hand in the post
fix incrementer first do the operation and then increment but the result of the incremented
value will be the same for both cases.
For example,
i=7;
x=++i;
x=i++;
After execution, the value of x will be set to 8.

Cyryx College

Page 10 of 70

Structured Programming in C
Decrementer
The decrementer is also similar to the incrementer. The symbol or notation is used for
decrementing by 1.
For example,
- -i
i- -

equal to
equal to

i=i-1;
i=i-1;

Here also there are two types of decrementer :


prefix decrementer (- -i), post decrementer (i- -).

WRITING A PROGRAM IN C
Variable declaration
All variables must be declared before it can be used as an executable statement in our
program. A declaration is a process of naming of the variables and their corresponding data
type in C. Usually the declaration part will be placed after the begin statement and sometime
some of the global variables are defined or declared outside of the program.
A declaration consists of a data type, followed by one or more variable names, ending with a
semicolon. A variable is an object that may take on values of the specified type. Variable
must be declared by specifying the data type and the identifier.
The general format of the variable declaration is
data_type identifiers 1,2.n;
For example,
1.
char ch;
Where ch is a character data type
2.
short int x,y;
Where x,y are short integer data type and it holds the data size of 1 bits.
Long.
3.

long int x1;


Where x1 is a long integer data type whose maximum size is 32 bits long.

Statements
A statement is a computer program is to carry out some action. There are three types of
statements used in C, and they are expression statement, compound statement, and control
statement.

Cyryx College

Page 11 of 70

Structured Programming in C

Expression statement

An expression statement consists of any valid C expression and followed by a semicolon.


The expression statement is used to evaluate the group expressions.
For example,
x=y;
a=x+y

/* the value of y is copies to variable x */


/* the value of x is added with the value of y and then assigned to the
variable a */

Compound Statement:

A group of valid C expressions placed within a { and } statement is called a compound


statement. The individual statement may be of expression statement, compound statement
or even a control statement. Note that the compound statement is not completed with a
semicolon.
For example
{
a=b+c;
x=x*x;
y=a+x;
}

Control Statement

The control statement is used for the programming flow and to check the conditions of the
given expression or a variable or a constant. The keywords of the control statements are
normally predefined or a reserved word and the programmer may not use as a ordinary
variable.
For example,
1.

if (a>b)
else

2.

while (condition is becoming true)

SIMPLE C PROGRAM
Suppose we would like to display the message Welcome to CYRYX on the display
monitor.
main ( ) /* program heading */
{
/* begin */
printf(Welcome to CYRYX);
}
/* end */
the function main( ) must be placed before the begin statement. It invokes other functions
to perform its job. The {symbol or notation is used as the begin statement. The declaration

Cyryx College

Page 12 of 70

Structured Programming in C
of variables and the type of operations are placed after the begin statement. The end
statement is denoted by the symbol }. In C, the semicolon (;) serves the purpose of a
statement terminator rather that a separator.
The remarks are specified in the following way. Any statement or function is not executable.
They are ignored by the compiler.
The declaration for the remark statement:
/* this is test */
type any alphanumeric character or any statements or functions inside the backslash
followed by the symbol * (multiple operator) and should be repeated for termination.
/*

this is a test
program by
Cyryx Computers
*/
The above said alpha numeric characters will be ignored by the compiler and this is treated
as a comment line or remark statement.
/* main( )
{
printf(this is a simple test\n); ;
}
*/
Any executable statements will also be treated as a remark statement if these statements are
followed by /* and terminated by the characters */
There are two advantages of using the remark statement one is easy to understand the
variable which is used in the source program, the second is easy to debug the variables or
tracing the variables by other users.
The following illustration is the skeleton of a C program structure.
program heading
begin
type of variable declaration
statement of operation
results
end
The symbol backslash(\) followed by the lower case n is used for line feed or new line. In C,
it is considered as a single character.
\n
New line or line feed
We will modify the above program to display the message in two lines.
The display should be like this.
Welcome to CYRYX
The Republic of Maldives

Cyryx College

Page 13 of 70

Structured Programming in C

Modified version of program


main( )
{
printf(Welcome to CYRYX);
printf(\n);
printf( The Republic of Maldives);
}

Simple Input Statement

In order to write an interactive C program, we require certain input and output functions or
routines. scanf and printf are two functions used for this purpose.
SCANF:
The scanf( ) function is used to read the formatted data items from the keyboard. The
format is a user defined data items. It can be read or written as defined by a programmer.
The general form of the scanf() function is
scanf(control string,argument list);
The control string is a specified format code to be read from the keyboard and the argument
list is a user defined variable list. Usually, the argument list of the user defined variable must
include the address operator (&) as a prefix to the variable.
For Example,
1.
int x,y;
scanf(%d %d,&x,&y);
2.

float a,b,c;
scanf(%f %f %f,&a,&b,&c);

3.

char c, i;
scanf(%c %c,&c,&i)

The complete format code used the scanf( ) function for the various data variables is shown
below
Code
%c
%d
%i
%e
%f
%s
Cyryx College

Meaning
read a single character
read a integer
read a integer
read a floating point number
read a floating point number
read a string
Page 14 of 70

Structured Programming in C

All the variables used to receive values through scanf( ) must be passed by their addresses.
This means that all arguments must be pointed to the variables used as arguments.
scanf(%d,&count);
Strings are read into character arrays, and the array name without any index is the address of
the first element of the array. So to read a string into a character array address, use
scanf(%s ,address)
In this case, address is already a pointer and need not be preceded by the & operator.
The input data items must be separated by spaces, tabs, or nextlines. Punctuations such as
comma, semicolon and the like, do not count as separators. This means that
scanf(%d %d,&a,&b);
can accept 10 20 as input, but fails with 10,20.

Simple Output Statment


printf( )

The printf( ) function is one of the most important useful function to display the formatted
output data items on the standard output device.
The general form of printf( ) function is as,
printf(control strings, argument list)
Where the control strings are the user defined format code and the argument list is a set of
data items to be displayed in a proper format as defined by the control strings.
The complete format code used in the printf( ) function for the various data variables is
shown below.
Code
%c
%d
%f
%s
%%

Format
a single character
integer value
floating point value
string of characters
print a percent sign.

For example
printf(%10.4f\n,value)
Which displays a number atleast ten character wide with four decimal places.
The number following the period specifies the maximum field length
Cyryx College

Page 15 of 70

Structured Programming in C
printf(%5.7s\n,name);
which displays a string that will be atleast five characters long and does not exceed seven
characters, If the string is longer the maximum field width, the characters are truncated off
the end.
A program to demonstrate the printf( ) function.
/* using printf function */
main ( )
{
char lett;
int num;
lett=a;
num=1234;
printf(the letter =%c, the number is %d\n,lett,num);
}
Output of the above program
The letter =a, the number =1234
A program to demonstrate the assignment of variables.
main( )
{
int x,y,z;
x=10;
y=20;
z=x+y;

/* x,y,z are integer type of data */


/* assigning the value 10 to the variable x */
/* assigning the value 20 to the variable y */
/* ontents of x will be added to y and assigned to z */

printf(sum of %d and %d is = %d,x,y,z);


}
A program to demonstrate the preincrementer and postincrementer operation inc
main ( )
{
int i,j;
int x,y;
j=I=6;
printf(Initial value i=%d\n,i);
x=i++;
printf(x=i++,value of x=%d, and value of i=%d\n,x,i);
i=j;
y=++i;
printf(initial value I=%d\n,j);
printf(y=++I, value of y=%d, and value of i=%d\n,y,i);
}
output of the above program
Cyryx College

Page 16 of 70

Structured Programming in C
initial value i
x++, value of x
initial value i
y=++i, value of y

getchar( )

=6
=6, and value of i=7
=6
=7, and value of i=7

the getchar ( ) is a function to use as an input statement to read any alphanumeric character
from the standard input device usually by the keyboard. Normally C reads character as
integers and to accept a character as a value for a variable of type int.
Syntax:

#include <stdio.h>
main( )
{
int ch;
________
________
ch=getchar( );
________
________
}

putchar( )

The putchar( ) is a complementary function of the getchar ( ). It is used to display any


alphanumeric character on the standard output device normally on the screen. Normally, a
character argument should be placed inside the putchar function. The usual format of the
putchar function is shown below.
The syntax are:
#include <stdio.h>
main( )
{
int ch;
__________
__________
putchar (ch);
__________
__________
}
A program to read a character from the keyboard and display it on the video screen.
#include <stdio.h>
main ( )
{
int ch;
printf(Enter a character);
ch=getchar( );
printf(typed character is =);
putchar(ch);
Cyryx College

Page 17 of 70

Structured Programming in C
}

CONTROL STATEMENTS
Conditional expressions

The conditional expressions are mainly used for decision making purpose. In the subsequent
sections, the various structure of the control statements and the expressions are explained.
The following statements are used to perform the task of the conditional operations.
1.
2.
3.

if statement
if-else statement
switch-case statement

if Statement

The if statement is used to express the conditional expressions. If the given condition is true
then it will execute the statements otherwise it will execute the optional statements. The
braces { and } are used to group declaration and statements together into a compound
statement or block. These compound statements or blocks are always considered as a single
statement. The basic simple structure of the IF statement is shown below:
If (expression)
{
statement1;
statement ;
________
________
}
the expression is evaluated and if it is true the statement following the if is executed. In
case the given expression is false, the statement is skipped and execution continues with the
next statement. The expression in c, is any valid expression which is examined to a numeric
value.
For example,
a=20;
b=10;
if (a>b)
printf(largest value = %d,a);
if the given condition is satisfied, then the computer will print the message largest value =
20 and if not, it will simply skip this statement.
If-Else Statement
However, If structure is more commonly used with the following format.
if(expression)
statement1
else
statement2
where the else part is optional.

Cyryx College

Page 18 of 70

Structured Programming in C
In this case either of the two statements are executed depending upon the value of the
expression. Statement 1 is executed if the expression returns a true, else statement 2 is
executed.
The else part is optional in the if-else structure it sometimes leads to confusion especially
when an else is omitted from a nested if-else sequence
For example
if (i>j) /* wrong */
if(a>b)
temp =a;
else
temp=b;
Note that the else statement without braces, leads to confusion like whether it belongs to the
inner if statement or outer if. To avoid this ambiguity, always the braces are used to
represent the compound statements.
if (i>j) /* right */
{
if(a>b)
temp =a;
}
else
temp=b;
Normally the braces must be used to clearly indicate the proper association.
A program to read any two numbers from the keyboard and to display the largest value of
these two numbers.
main( )
{
int x,y;
printf(Enter any two numbers \n);
scanf(%d %d,&x, &y);
if (x>y)
printf(largest Value is =%d,a);
else
printf(largest Value is =%d,b);
}

Switch statement

The switch statement is a special multiway decision maker that tests whether an expression
matches one of the number of constant values, and braces accordingly. The syntax of the
suitable statement is as follows.

Cyryx College

Page 19 of 70

Structured Programming in C
switch (expression)
case constant1:
statement;
case constant2:
statement;
___________
___________
___________
___________
case constant n;
statement;
default:
statement;
Execution of the switch constant in c follows a different logic. No statements are executed
until a case has been matched or the default case has been encountered. However. It
continues to execute all statements once a case has been matched: irrespective of the fact
whether those statements belong to the case that has been matched or not.
As an example consider some program segment written in C.
switch (input_ch)
case R:
printf(Red\n);
case W:
printf(White\n);
case B:
printf(Blue\n);
Due to the fall through effect when input_ch is R the Red, white and Blue will be printed,
when choice is W, then the white and blue will be printed and when choice is B only Blue
will be printed.
C offers a method of overcoming this side effect with the help of the BREAK statement.
The break statement causes and immediate exit from the switch construct. Because the
default case include a break statement there. However in general it is advisable to use the
break statement explicitly whenever exclusion of case statements is required. Thus, the
general format of the mutually exclusive switch constant.
switch (expression)
case constant 1:
{
statement1
________
________
}
break;

Cyryx College

Page 20 of 70

Structured Programming in C
case constant 2:
{
statement1
_________
_________
}
break;
case constant n;
statement 1
_________
_________
}
break;
A program to display the name of the day, depending upon the number entered from the
keyboard using swich-case loop.
main( )
{
int day ;
printf(Enter a number between 1 to 3\n);
scanf(%d,&day);
switch(day)
{
case 1:
printf (Monday\n);
case 2:
printf(Tuesday\n);
case 3:
printf(Wednesday\n);
default:
printf(Enter the number between 1 to 3\n);
}
}

Loop Statements

The loop statements are essential to construct systematic block styled programming. In C,
there are multiple ways one may use the control structures using the different types of loop
operations.
Sometimes the other high level languages may not support all the features of the C control
structures. The following loop structures are Supported by C,
1. for loop
2. while loop
3. do-while loop

Cyryx College

Page 21 of 70

Structured Programming in C
For Loop
The for loop is most commonly used statement in c. This loop consists of three expressions.
The first expression is used to initialize the index value, the second expression is used to
check whether or not the loop is to be continued again and the third expression is used to
change the index value for further iteration.
The Syntax of the for loop:
for (expression1;expression2;expression3)
Statement;
In other words
for (initial condition;test condition;incrementer or decrementer)
{
statement1
statement2
-------------------------}
Where expression 1 is the initialization of the expression or the condition, expression 2 is the
condition checked as long as the given expression is true the loop statement will be repeated
and expression 3 is the incrementer or decrementer to change the index value of the for loop
variable.
Thus consider a simple example shown below
sum=0;
for (i=1;i<=100;i++)
sum =sum+ i ;
The loop variable in this case is i. During the first pass this variable is initialized with the
value 1. In subsequent passes this step will not be carried out. After initialization is done the
second expression is evaluated and the loop is entered only if the value is true. The loop
statements are executed and then the third expression is evaluated. The result is the
incrementing of I by 1.
Examples:
A Program to display number from 0 to 10 using for loop.
main( )
{

Cyryx College

int i;
for (i=0;i<=10;i++)
{
printf(%d,i);
}

Page 22 of 70

Structured Programming in C
While Loop
The second type of loop, the while loop, is used when we are not certain that the loop will
be executed. After checking whether the initial condition is true or false and finding it to be
true. Then only while loop will enter into the loop operations.
The general for of the while loop is
For a single statement
While (condition)
Statement;
For a block of statements
While (condition)
{
statement1;
statement2;
------------------------}
Example
A Program to find the sum of the first 100 natural numbers
main( )
{
int sum,digit;
sum=0;
digit=1;
while(digit<=100)
{
sum+=digit;
digit++;
}
}
In the above program the initial condition is assigned to 0 and the test condition is used to
check whether the digit value has become 100. If not, it will repeat the loop, the final
statement of the program digit++ will increment by one in each execution for changing the
initial index value.
Do While Loop
The do-while loop is another repetitive loop used in C Program. Whenever, one is sure
about the test condition, then he may use the do-while loop because it enters into the loop at
least once and then checks whether the given condition is true or false. As long as the
condition is true, the loop operations or statements will be repeated again and again. Like a
while loop, here also three expressions are used to construct this loop. The expression 1 is
used to initialize the index value and normally it will appear out of the loop. The Expression
2 is used to change the index value and the expression 3 is used to check whether or not the
loop is to be repeated again.

Cyryx College

Page 23 of 70

Structured Programming in C

The syntax of the do loop:


do {
statement 1;
statement 2;
---------------;
--------------;
}
while (expression);
Example:
A program to display the numbers from 1 to 100 in steps of 3 by using the do loop.
main ( )
{
int x;
printf(Numbers between 1 to 100 steps of 3 \n);
x=1;
do
{
printf(%d\t,x);
x=x+3;
}
while (x<=100);
}
BREAKING CONTROL STATEMENTS
1. Break statement
2. continue statement
3. goto statement
BREAK STATEMENT
The break statement is used to terminate the control, from the loop statement of the switchcase structure. The break statement is normally used in the switch case loop and in each case
condition, the break statement must be used if not the control will be transferred to the
subsequent case condition also.
The general format of the break statement is
Break;
The break is a keyword in the C program and the semicolon must be inserted after the
break statement.
Break statement used with switch case structure
switch (day){
case 1:
printf(Monday);
Cyryx College

Page 24 of 70

Structured Programming in C
break;
case 2:

printf(Tuesday);
break;
default :
------------------------------}
Break statement using in the for loop
for (i=0;i<=10;i++);
{
printf(Enter a number \n);
scanf(%d,&value);
if (value<=0)
{
printf(Zero or Negative value found\n);
break;
}
}
Continue Statement
The Continue statement is used to repeat the same operations once again even if checks the
error. The general syntax of the continue statement is as follows:
Continue;
The continue is a keyword and followed by the semicolon. The continues is used for the
inverse operation of the break statement.
The following program segments show the usage of the continue statement operation.
main( )
{
int i, value;
i=o;
while(i<=10)
{
printf(Enter the number \n);
scanf(%d,&value);
if (value <=0)
{
printf(Zero or negative value found\n);
continue;
}
i++;
}
}
/* end of main*/
Cyryx College

Page 25 of 70

Structured Programming in C

THE GOTO STATEMENT

The goto statement is used to alter the program execution sequence by transfer of control to
some other part of the program.
The Normal syntax for the goto statement is
Goto label;
Where label is a valid C identifier used to label the destination such that control could be
transferred.
Two ways of using the goto statements in the program are conditional goto anf
unconditional goro.

Unconditional goto

The unconditional goto statement is used just to transfer the control from one part of the
program to the other part of without checking any conditions. Normally a good programmer
wiil not prefer to use the unconditional goto statements in his program because sometimes it
may lead to very complicated problems like never ending process.
main( )
{
200;
printf(Unconditional goto\n);
goto 200;
}

Conditional goto

The conditional goto is used to transfer the control of execution from one part of the
program to the other oart under certain conditional cases.
The following sample program explains the usage of conditional goto statements.
main( )
{
int a,b;
if (a>b)
else

goto output2;

goto output 2;
output1:
printf(largest value =%d\n,a)
goto end;
output2:
printf(largest value =%d\n,b);
end:
}

Cyryx College

Page 26 of 70

Structured Programming in C

The goto statement used in for loop

The following program segment shows the use of goto statement in the for loop.
for (I=0;I<=10;I++)
{
printf(Enter any number\n);
scanf(%d,&value);
if (value <=0)
{
printf(Error:);
printf(Zero or negative value found\n);
goto error;
}
}
error:
------------------------------The above program segment checks the possibility of the negative or zero values and
whenever the input data is nonzero and positive, it will continue for the for loop.

FUNCTIONS AND PROGRAM STRUCTURES

The complex problem may be decomposed into small or easily manageable parts. Each small
module is called a function. The function are very useful to read, write, debug, modify and
are easy to use in the main program. In C, the main( ) itself is a function, that means the
main function is invoking the other functions to perform the task.
The main advantages of using a function are

Simple to write correctly a small function


Easy to read, write and debug a function
Easier to maintain or modify such a function
Small functions tend to be self documenting and highly readable.
A function may be called any number of times in any place with different
parameters.
Most languages diferenciate between a main program and subordinate routines. In C, all
modules are called functions and they all have the same structure.
Defining a function
A function definition as a name and a prarnthesis pair containing zero or more parameters
and a body. For each paramenter, there should be a corresponding declaration that occurs
before the body. Any parameter not declared is taken to be an int by default. It is good
programming practice to declare all paramenters.

Cyryx College

Page 27 of 70

Structured Programming in C

The general format of the function definition is given below.


functiontype functionname(argument1, argument2,..argument n)
Datatype argument1, argument2;
Datatype argument n;
{
body of function
---------------------------------------return something
}

Declaring the type of function

The function refers to the type of value that the function will return to the calling portion of
the program. Any of the basic data types such as int, float, char etc. may appear in the
function declaration.
In many compilers, when a function is not to rturn any value it may be declared as type void,
which tells C not to save any temporaty space for a value to be sent back to the calling
program.
For example,
void functionname(.)
int functionname(.)
float functionname(.)
char functionname(.)
functionname()

Function name

The function name can be anything and the syntax rules to form a function name is same as
the rules of the variables. Normally a function is named to be relevant of the operation, as it
is easy to us to keep track of function whenever a transfer of similar functions is used in the
main program.
For example,
counter( );
square( );
display_value( );
output( );
Formal arguments
Any variable declared in the body of a function are said to be local to that function. Other
variables not declared either as arguments or in the function body are considered global to
the function and must be defined externally. The storage classes or scope of variables are
discussed subsequently in this chapter.
For Example,
void square(a,b)
int a,b; /* a,b are formal arguments */
{
_____________
_____________
}

Cyryx College

Page 28 of 70

Structured Programming in C

A program to display a message Welcome to CYRYX using a function


main ( )
{
message( );
}
void message( ) /*function*/
{
printf(Welcome to CYRYX);
}
the main function invokes the message( ) function, In C, each function is almost like a
separate program. So th formal declaration such as type, begin and end must be used in the
function also. The controls will be transferred from the main function to the called function
after it has executed all the statements in the function and the control will be back to the
calling portion of the program.

RETURN STATEMENT

The keyword return is used to terminate function and return value to its caller. The return
statement also be used to exit a function without returning a value. The return statement
may or may not include an expression.
The general syntax of the return statement are as follows;
return;
return(expression);
Return is a full-fledged C statement that can appear anywhere within a function body. A
function can also have more than one return although it is generally considered better style
for a function to have a single entrance and a single exit.
The following are the valid return statements.
return;
return (54);
return(x+y);
return(++y);
return(++i);
return ++j; /* correct but not good style*/
The return statement terminates the execution of the function and passed control back to
the calling environment.
For example, the following function declarations are valid.
1.
sum(x,y)
int x,y;
{
return(x+y);
}
2
maximum(a,b)
float a,b;
{
Cyryx College

Page 29 of 70

Structured Programming in C

if (a>b)
return (a);
else
return (b);

Types of functions

The user defined functions may be classified into three ways based on the passing of the
formal arguments and the usage of the return statement.
A function is called without taking any formal arguments from calling portion of a
program and also there is no return statement from the called function.
A function is called with passing of some formal arguments to the function from
calling portion of the program but the function does not return back any values to
the calling portion.
A function is called with passing of some formal arguments to the function from
calling a portion of a program and returned back some values to the calling
environment.

Type 1

It is the simplest way of writing a user defined function in C. There is no data


communication between a calling portion of a program and a called function block. The
function is invoked by a calling environment by not feeding any formal arguments and the
function also does not return back anything to the caller.
For example,
main ( )
{
int x,y;
----------------------------message(); /* function is invoked */
}
message( )
{
/* body of the function */
}
Type 2
The second type of writing a user defined function is passing some formal arguments to a
function but the function does not return back any value to the caller. It is a one way data
communication between a calling portion of the program and the function block.
For example,
main ( )
{
int x,y;
power(x,y);
/* function declaration */

Cyryx College

Page 30 of 70

Structured Programming in C
----------------------}
power (x,y)
int x,y;
{
/* body of the function */
/* no values will be transferred back to the caller*/
}
A program to find the square of its number using a function declaration without using the
return statement.
/* passing formal arguments and no return statement */
# include <stdio.h>
main()
{
int i,max;
printf(enter a value for n?\n);
scanf(%d,&max);
printf(Number
Square\n)
printf(--------------- -------------\n);
for (i=1; i<=max; i++)
square(i);
}
square(n)
int n;
{
temp;
temp=n*n;
printf(%d\t\t%d\n,n,temp);
}
Type 3
The third type of writing a user defined function is passing some formal arguments to a
function from calling the portion of the program and the computed values, if any, is
transferred back to the caller. Data are communicated between calling the portion and a
function block.
For Example,
main ( )
{
int x,y,temp;
char ch;
------------------Cyryx College

Page 31 of 70

Structured Programming in C
temp=output(x,y,ch);
}
output(a,b,s)
int a,b;
char s;
{
int value;
/* body of the function */
return (something);
}
A program to find the square of its number us aing a function declaration using the return
statement.
/* passing formal argument and return statement */
#include <stdio.h>
main( )
{
int i,max,temp;
printf(enter a value for n?\n);
scanf(%d,&max);
printf(Number
Square \n);
printf(------------------------);
for (i=1 ;i<=max; i++)
{
temp=square(i);
printf(%d\t\t%d\n,i.temp);
}
}
square(n)
int n;
{
int n;
{
int value;
value =n*n;
return (value);
}

Cyryx College

Page 32 of 70

Structured Programming in C

ARRAYS
Array Notation
Array is a collection of identical data objects which are stored in consecutive memory
locations in a common heading or a variable name. In other words, an array is a group or
table of values referred to by the same variable name. The individual values in an array
are called elements. Array elements are variables also.
Arrays are sets of values of the same type, which have a single name followed by an
index, in C, square brackets appear around the index right after the name, with the first
element referred to by the number. Whenever an array name with an index appears in an
expression, the C compiler assumes that element is an array type.
Array declaration
Declaring the name and type of an array and setting the number of elements in the array
is known as dimensional array.
The array must be declared before one uses it in a C program like other variables. The
array declaration is defining the type of the array, name of the array, number of
subscripts in the array and the total number of memory locations to be allocated.
In general, one dimensional array may be expressed as
storage_class data_type, array _name[expression]
Where storage_class referes to the scope of the array variable such as external, static, or
an automatic and data_type is used to declare the nature of the data elements stord in
the array like character type, integer and floating point. Array_name is the name of the
array, and expression is used to declare the size of the memory locations to be required
for further processing in the program.
The storage class is optional, default value are automatic for arrays defined within a
function or a block, and extended for arrays defined outside the function.
Some valid one dimensional array declaration are shown below:
int marks[300];
char line[90];
float coordinate[400];
The first one has been declared as a mark of 300 integers, the second is a line of 90
characters, the third is a floating point where numbers of 400 is stores in the array of
coordinate.
Array initialization
Automatic arrays cannot be initialized, unlike a automatic variable. However, the external
and a static array can be initialized if desired. The initial values must appear in the order
in which they will be assigned to the individual array elements, enclosed in braces and
separated by commas.

Cyryx College

Page 33 of 70

Structured Programming in C

The general format of the array initialization is shown below:


Storage_class data_type array_name [expression]={element1, element2,
element n};
Where the storage class is used to declare the scope of the array like static, automctic or
external data, data_type is a nature o the data elements such as integer, floating, or character
etc. the array_name is used to declare the name of the array, and the elements are placed one
after another within the braces and finally ends with the semicolon.
For example,
int values[7]={10,11,12,13,14,15,16};
float coordinate[5]={0,0.45,-4.0,5.0};
char se[2]={M ,F};
char name[6] ={S, T, A, L, I, N};
The results of each array elements are as follows
values [0] =10
values [1] =11
values [2] =12
values [3] =13
values [4] =14
values [5] =15
values [6] =16
coordinate[0]=0
coordinate[1]=0.45
coordinate[2]=-0.50
coordinate[3]=-4.0
coordinate[4]= 5.0
sex[0]=M
sex[1]=F
name[0]=S
name[1]=T
name[2]=A
name[3]=L
name[4]=I
name[5]=N
Note that in C, first element is always placed in 0th place, it means that the array index starts
from 0 to n-1, where n is the maximum size of the array declared by the programmer.
Some un usual way of initializing the array elements are discussed below.
For example, if the array elements are not assigned explicitly, initial values will automatically
be set Zero. Consider the following array declaration.
Cyryx College

Page 34 of 70

Structured Programming in C

int number[5]={1,2,3};
The following way the elements will be assigned to the array.
number[0] =1
number[1] =2
number[2] =3
number[3] =0
number[4] =0
A program to initialize a set of numbers in the array and displays onto the standard output
device.
main ( )
{
int a[7]={ 11,12,13,14,15,16,17}
int i;
printf(Contents of the array \n);
for ( i=0; i<=6;++i)
{
printf(%d\t|,a[ i ]);
}
}

Output of the above program is


11

12

13

14

15

16

17

A program to read n numbers from the keyboard, when n is defined by the programmer and
to store it into one dimensional array and to display the contents of that array onto the
screen.
main ( )
{
int a[100];
int i,n;
printf(How many numbers are in the array?\n);
scanf(%d,&n);
printf(Enter the elements \n);
for (i=0; i<=n-1;++i);
{
scanf(%d,&a[ i ]);
}
printf(Contents of the array \n);
for (i=0; i<=n-1;++i);
{
printf(%d\t,a[ i ]);
}
}

Output of the above program

How many numbers in the array?


5
Enter the elements
Cyryx College

Page 35 of 70

Structured Programming in C
11
12
1
3
5
Contents of the array
11 12 1
3
5
Multidimensional arrays
Multidimensional arrays are defined in much the same manner as one dimensional arrays,
except that a separate pair of square brackets is required for each subscript. Thus a two
dimensional array will require two pairs of square brackets. Three dimensional arrays will
require three pairs of square brackets and so on.
The general format of the multidimensional array is as follows
storage_class data_type arrayname [expression1[expression2].[expression n];
Fo example,
float coordinate x[10][10];
int value[ 10 ] [5];
The first line defines coordinates as a floating point array having 10 rows and 10 columns
and totally it is having 10 x 10 =100 elements. The second one is a value of 2 dimensional
integer arrays whose maximum size is 10 x 5 =50 elements.
Multidimensional array initialization
Similar to the one dimensional array, the multi dimensional array also can be initialized, if
one intends to assign some values to these elements. It should be noted that only external or
static arrays can be initialized.
Consider the following two dimensional array declaration.
For example
int x[2][2]={1,2,3,4};
where x is two dimensional array of integers whose maximum size is 4 and these assignments
would be
x[0][0] =1;
x[0][1] =2;
x[1][0] =3;
x[1][1] =4;
the natural order in which the initial values are assigned can be altered by forcing groups of
initial values enclosed within braces ie{.}
For example, the following two dimensional array may be declared

Cyryx College

Page 36 of 70

Structured Programming in C
int A[3][3] ={
{1,2,3),
{4,5,6},
{7,8,9}
};
The three values in the first inner pair of braces are assigned to the array elements in the first
row, the values in the second pair of braces are assigned to the array element in the the
second row, and so on.
The elements of the above A array will be assigned as follows.
A[0][0]=1 A[0][1]=2
A[1][0]=4 A[1][1]=5
A[2][0]=7 A[2][1]=8

A[0][2]=3
A[1][2]=6
A[2][2]=9

A program to initialize a set of numbers into a two dimensional array and to display the
contents of the array onto the screen.
#define r 3
#define c 4
main ( )
{
int i , j;
int a[ r] [c] ={

{1,2,3,4},
{5,6,7,8},
{9,10,11,12}

};
printf(Contents of the array \n);
for (i=0; i<=r-1; i++)
{
for (j=0; j<=c-1; j++)
printf(%d\t, a[ i ][ j ]);
printf(\n);
}
}

Output of the above program


1
5
9

2
6
10

3
7
11

4
8
12

Character array
The procedure of declaring character array is almost like other data type such as integer or
floating point. One may declare the character array by means alphanumeric characters.
The general format of the array is as follows
Cyryx College

Page 37 of 70

Structured Programming in C

storage_class character data_type array_name [expression];


The array name is any valid c identifier, and the expression is a positive integer constant.
For example,
char page[40]
char sentence[300];
The basic structure of the character array

\0

Each element of the array is placed in the definite memory space and each element can be
accessed separately. The array element should end with the NULL character as a reference
for termination of a character array.
Initializing the character array
Like integer or floating point array, the character array also can be initialized
For example,
char colour[3]=RED;
The following way the elements would be assigned to each of the character array position.
colour[0]=R;
colour[1]=E;
colour[2]=D;
The character arrays always terminate with the NULL character that is a back slash followed
by a letter zero (not lettero or O) and the computer will treat as a single character.
The null character will be added automatically by the C compiler provided that enough room
should be there to accommodate this character
For example,
char name[5]=CYRYX; /* wrong*/
The following assignment would be for each cell
name[0]=C;
name[1]=Y;
name[2]=R;
name[3]=Y;
name[4]=X;

Cyryx College

Page 38 of 70

Structured Programming in C
The above declaration is wrong because there is no space to keep the null character to the
array as a terminate character and it can be corrected by redefining the above said array like
char name[6]=CYRYX; /* right*/
The following assignment would be for each cell
name[0]=C;
name[1]=Y;
name[2]=R;
name[3]=Y;
name[4]=X;
name[5]=\0;

A program to initialize a set of characters in the one dimensional character array and to
display the contents of the given array.
#include <stidio.h>
main( )
{
int i;
char names[6]={C, Y, R, Y, X};
clrscr( );
printf(contents of the array\n);
for (i=0; i<=5; i++)
{
printf(names[%d]=%c\n,i,names[i]
}
getch( );
}
A program to read a set of lines from the keyboard ant to store it onto the one dimensional
array and to display the contents of the array onto the screen.
#define max 1000
#include<stdio.h>
main( )
{
char s[max]
int i;
char ch;
clrscr( );
printf(Enter a set of lines and terminate with @\n);
i=0;
while ( (ch=getchar()) !=@);
{
s[i++]=ch;
Cyryx College

Page 39 of 70

Structured Programming in C
}
s[i++] =\0;
printf(output from the array\n);
for (i=o; s[i] !=\0; i++)
{
putchar(s[ i]);
}
getch( );
}

POINTERS

Pointer declaration
A pointer is a variable which holds the memory address of an another variable. Sometimes,
only with the pointer the complex data type can be declared and accessed in an easy way.
The pointer has the following advantages.
-

Provides functions which can modify their calling arguments


Supports dynamic allocation routines
Improves the efficiency of certain routines

A pointer contains a memory address. Most commonly, this address is the location of
another variable where it has been stored in memory. If one variable contains the address of
another variable, then the first variable is said to point to the second.
Sometimes, the pointer is the only technique to represent and to access the complex data
structures in an easy way. In C, the pointers are distinct such as integer pointer, floating
point number pointer, character pointer etc. The pointer variable consists of two parts such
as the pointer operator and the address operator.
Pointer operator
A pointer operator can be represented by the combination of * (asterisk) with a variable. For
example, if the variable is an integer type and also declared * (asterisk) with variable that
means the variable is of type pointer to integer . In other words it will be used in the
program indirectly to access the value of one or more integer variables.
For example,
int *ptr;
Where ptr is a pointer variable which holds the address of an integer data type.
The general format of the pointer declaration
data_type *pointer variable;
Where data_type is a type of pointer variable such as integer, character and floating point
number variable etc. the pointer variables are any valid C identifiers and the astrisk must be
preceded by the pointer variable.
The following declarations are all valid

Cyryx College

Page 40 of 70

Structured Programming in C
float * fpointer;
double *dpoint;
char *mpoint1;
The base type of the pointer defines which type of variables the pointer is pointing to.
Technically, any type of pointer can point anywhere in memory. All pointer arithmetic is
done relative to its base type. So it is important to declare the pointers correctly. For
example, a character data items may require to store only a byte(8 bits), and integer may
require to store a two bytes(16 bits) , a floating point number may require to store four bytes
(32 bits), a double precision number may require eight byte(64 bits). The number of bytes to
be required to store particular data items will vary from machine to machine.

Address Operator

An address operator can be represented by the combination of & (Ampersand) with a


pointer variable. For example, if the pointer variable is an integer type and also declared &
with pointer variable that means the variable is of type address of. In other words, it will
be used in the program to indirectly access the value of one or more integer variables. The &
is a unary operator that returns the memory address of its operand. A unary operator only
requires one operand.
For example,
m=&ptr;
Note that the pointer operator & as on operator that returns the address of the variable
following it. Therefore, the preceding assignment statement could be verbalized as m
receives the address of ptr.

Pointer Expressions

A pointer is a variable data type, so the general rule to assign its value to pointer is same as
any other variable data type. For example,
int x,y;
int *ptr1, *ptr2;
1. ptr1=&x;
The memory address of variable x is assigned to a pointer variable ptr1.
2. y= *ptr1;
The contents of the pointer variable ptr1 is assigned to the variable y, not the memory
address.
3. ptr1=&x;
ptr2=ptr1; /*address of ptr1 is assigned to ptr2*/
The address of the ptr1 is assigned to the pointer variable ptr2. The contents of both
ptr1 and ptr2 will be same because these two pointer variables hold the same address.

Some invalid pointer declaration

int x;
int x_pointer;
x_pointer=&x;
Error: pointer declaration must have the prefix of *(unary operator)

Cyryx College

Page 41 of 70

Structured Programming in C

A program to display the contents of the pointer.


main( )
{
int x;
int *ptr;
x=10;
ptr=&x;
printf(x=%d and ptr =%x\n,x,ptr);
printf(x=%d and ptr=%d\n,x,ptr);
}
In the above program, x is an integer variable and the ptr is declared as the pointer to an
integer. Initially, value 10 is assigned to the integer variable x. the address of the variable x is
assigned to the ptr.
ptr=&x /* address of x is assigned to the variable pointer */
ptr =&x / value of x is assigned to the ptr */
A program to assign a character variable to the pointer and to display the contents of the
pointer.
main( )
{
char x,y;
char *pointer;
x=c; /*assign character */
pointer &x;
y=*pointer;
printf(Value of x=%c\n,x);
printf(pointer value=%c\n,y);
}
Output of the above program
Value of x=c
Pointer value =c
A program to display the address and the contents of a pointer variable.
#include <stdio.h>
main( )
{
int x;
int *ptr;
x=10;
ptr=&x;
printf(Value of x=%d\n,x);
printf(Contents of ptr=%d\n,*ptr);
printf(Address of ptr=%d\n,ptr);
}
Cyryx College

Page 42 of 70

Structured Programming in C

Output of the above program


Value of x=10
Contents of ptr =10
Address of ptr =65488

Header files

MORE ON FUNCTIONS

A header file contains the definition, global variable declarations and initialization by all the
file in a program. Header files are not compiled separately. The header file can be included in
the C program using the macro definition #include command. The header file can be
declared as a first line of any c program. For example, the standard input/output (stdio.h)
header file contains the macro definitions and the functions needed by the program
input/output statements. The header file can be declared in one of the following ways
#include <stdio.h>
or
#include stdio.h
Many C compilers mostly support the following header files.
Header file name
conio.h
ctype.h
dir.h
float.h
math.h
stdio.h
string.h
time.h

Purpose
console (keyboard and screen) input and output
character testing
user in working with directories
floating point type characteristics
math functions
standard i/o macros and functions
string functions
data and time utilities

Standard functions
The standard libraries are used to perform some predefined operations on characters, strings
libraries are called in many different names such as library functions, built in function or
predefined functions. As the term library function indicates, there are a great many of them,
and actually they are not a part of the language. Many facilities that are used in C programs
are not part of the c language. Most of the C compilers support the following standard
library facilities.
-

operations on characters
operations on strings
mathematical operations
storage allocations procedures
input/output operations

Cyryx College

Page 43 of 70

Structured Programming in C
only selected libraries such as character processing, string processing and mathematical
operations are discussed in this book. These selected libraries are widely available and
particularly useful.

abs()
The abs( ) function is used to get the absolute of its arguments. The arguments and the result
are both type int. more precisely, if the argument is nonnegative, then the argument itself is
returned. The abs( ) function cannot be used to get the absolute of long integer data type
and its argument must be of type int.
# include <math.h>
int abs(x)
int x;
/* using abs(x) */
#include <stdio.h>
#include <math.h>
main( )
{
int i,n,ai;
n=10;
printf(Number and its absolute value \n);
for (i=0;i<=n;i++)
{
ai=-1*i;
printf(%d\t %d\t %d\n,I,ai,abs(ai);
}
}

strlen( )
The strlen( ) function is used to find the number of characters in a given string preceding the
terminating null. The length of an empty string is zero.
#include <string.h>
char *strlen(source)
char *souorce;
/* using strlen( )
main( )
{

*/

char ine1[20];
int nch;
printf(Enter a line \n);
gets(line1);
nch=strlen(line1);
printf(contents of line1 :\n);

Cyryx College

Page 44 of 70

Structured Programming in C
puts (line1);
printf(Length of the string =%d\n,nch);
isalpha( )
The isalpha( ) function is used to check whether a given character belongs to an alphabetic
character, if it is true, it returns non zero otherwise the returned value is zero.
The alphabetic character : that is, one of the following.
A.Z
az
the declaration of the isalpha( ) function is as follows
#include <ctype.h>
int isalpha(ch)
char ch;
/* using isalpha( ) */
#include <stdio.h>
#include <ctype.h>
main( )
{
char ch;
printf(Enter a character \n);
ch=getchar();
if (isalpha(ch)>0
printf(it is an alphabetic character \n);
else
printf(it is a special character \n);
}
islower( )
The islower( ) function is used to check whether a given character belongs to a lowercase
alphabetic character or not. If it is true, it returns nonzero otherwise the returned value is
zero.
/* using islower */
#include <stdio.h>
#include <ctype.h>
main( )
{
char ch;
printf(Enter a character \n);
ch=getchar( );
if (islower (ch>0)
printf(it is a lowercase alphabetic character\n)
else
Cyryx College

Page 45 of 70

Structured Programming in C
printf(It is not a lowercase alphabetic character \n);
}
_tolower ( )
The _tolower function is used to convert a given uppercase letter into corresponding
lowercase letter. The result of _tolower ( ) function is undefined for all other arguments. The
_tolower ( ) function is much faster if the programmer can guarantee that the given character
is in fact an uppercase letter.
The declaration of the _tolower ( ) function is as follows
#include <ctype.h>
int _tolower(ch)
char ch;
/* using _tolower ( )*/
#include <stdio.h>
#include <ctype.h>
main( )
{
char ch;
printf(enter a character \n);
ch=getchar( );
ch-_tolower(ch);
putchar(ch);
}

Cyryx College

Page 46 of 70

Structured Programming in C

STRUCTURES AND UNIONS


The declaration of Structure

In C, collection of heterogeneous (different) types of data can be grouped to form a


structure. When this is done, the entire collection can be referred to by a structure name. In
addition, the individual components which are called fields or members can be accessed and
processed separately.
The structure can be represented graphically as follows
Structure
name

member 1
member 2
member 3

member n
There are two important distinction between arrays and structures. To start with, the
elements of an array must all have the same type. In a structure, the components or fields
may have different data types, Next, a component of an array is referred to by its position in
the array whereas each component of a structure has a unique name. Structures and arrays
are similar in that both must be defined with a finite number of components.
The symbolic representation of the structure is as follows:
struct user_defined_name
{
member 1;
member 2;
------------------------member n;
};

Cyryx College

Page 47 of 70

Structured Programming in C
A Structure definition is specified by the keyword struct. This is followed by a user defined
name surrounded by braces, which describes the members of the structure. A member of a
structure is
The general format of a structure declaration is
storage_class struct user_defined_name
{
data_type member1;
data_type member 2;
________________
________________
data_type member n;
};
The storage class is an optional. The keyword struct and the braces are required. The user
defined name is usually used, but there are situations in which it is not required. The data
typw and members are any valid C data objects such as short integer, float, char. Once the
structure has been declared, it may be used.
For example, todays data can be arranged in the following form
int day;
int month;
int year;
The date is a structure consisting of three members and all the members are of same data
type.
struct date {
int day;
int month;
int year;
};
the structure can be represented symbolically as follows:
struct
date

day
month
year

Cyryx College

Page 48 of 70

Structured Programming in C

The students particulars can be placed like this Roll no, age,sex,height and weight the
structure declaration can be done as follows
struct student
{
int rollno;
int age;
int sex;
int height;
int weight;
};
Each member of a structure variable is specified by the following variable name with a
period and the member name. The period is structure member operator, which we shall
hereafter to simply as the period operator. For example, the date is a structure and consists
of three members and it would be referred to in a program as
struct date
{
int day ;
int month ;
int year;
};
struct date today;
today.day;
today.month;
today.year;
Assigning values to the member of the structure
The todays date may be assigned as follows
today.day=20;
today.month=10;
today.year=2002;
When a structure member is named using the period operator, the variable name and
member name are still separate identifiers. For example,
The variable today.year exceeds more than eight characters but in the structure, each one is a
separate identifier so the truncation will not take place for both.
The C compiler will not read or write an entire structure as a single command like this
scanf(%s,today); /* wrong */
printf(%s,today); /* wrong */

Cyryx College

Page 49 of 70

Structured Programming in C
It will read or write the members of a structure separately as follows
/* reading a structure */
scanf(%d, &today.day);
scanf(%d, &today.month);
scanf(%d, &today.year);
/*displaying on the screen */
printf(%d,today.day);
printf(%d,today.month);
printf(%d,today.year);
A program to assign some values to the member of a structure and to display the structure
on the screen.
#include <stdio.h>
main ( )
{
struct sample
{
int x;
float y;
};
struct sample a;
a.x=10;
a.y=20.20;
printf(Contents of X and Y \n);
printf(%d\t %0.2f\n,a.x,a.y);
}

The structure tag

It is possible to define a structure variable name in the structure type declaration itself.
The general format of the structure tag declaration is
storage_class struct user_defined_name
{
data_type member 1;
data_type member 2;
______________
______________
data_type member n;

Cyryx College

Page 50 of 70

Structured Programming in C
For example, the following structure declaration of a,b could be written as
struct student
{
int rollno;
int age;
char sex;
float height;
float weight;
} a,b;
Now a, b are the two structure variables to be of a type struct student.
A program to assign some values to the member of a structure and to display the structure
on to the screen the structure tag.
# include <stdio.h>
main( )
{
struct sample
{
int x;
float y;
} a;
a.x=10;
a.y=20.20;
printf (Contents of X and ya \n);
printf(%d\t %0.2f\t,a.x,a.y);
}

Initializing a Structure

A structure can be initialized as the way of another data type in C. In keeping with the array
analogy, a structure must be either static or external.
For example,
Students particulars
rollno,
age
aex
height
weight
student ={91001,25,M,180.67,50.30};
The C compiler will assign the following ways to each of the fields
roll no = 91001
age
= 25
sex
=M
height =180.67
weight =20.30

Cyryx College

Page 51 of 70

Structured Programming in C
A program to initialize the member of a structure and to display the contents of the structure
on to a screen.
#include <stdio.h>
main ( )
{
struct student{
int rollno;
int age;
char sex;
float height;
float weight;
};
static struct student class={9100,24,M,167.8,40.0};
printf(Contents of structure \n);
printf(Rollno:%d\n,class.rollno);
printf(Age :%d\n,class.age);
printf(Sex:%c\n,class.sex);
printf(Height:0.2f\n,class.height);
printf(weight:0.2f\n,class.weight);
}

Other declaration

A field or member of a structure is a unique name fot the particulars structure. The same
field or member name may be given particular structures with different data types. The c
compiler will treat each structure member as a separate variable reserves the memory space
according to their data type of the member.
For example, the following declaration is valid
struct first
{
int a;
float b;
char c;
};
stctuc second
{
char a;
int b;
float c;
};
In the above two structures, namely, the first and second have three members and all three
have different data types. But as the names of the members are same, it is advisable to use
different structures so that no confusion arises while using them in the program. Here, it is
explained the different usages and declaration of the C compiler. In a practical situation, the
names of members should be distinct.
Cyryx College

Page 52 of 70

Structured Programming in C

A program to declare the same for the different data types in the two structures and to
assign some values into the corresponding fields and to display the contents of the
structures.
#include<stdio.h>
main ( )
{
struct first
{
int a;
float b;
float c;
};
struct second
{
char a;
int b;
float c;
};
struct first one;
struct second two;
one.a=23;
one.b=11.89;
one.c=F;
two.a=M
two.b=5;
two.c=-45.78;
printf(First structure\n);
printf(%d\t %0.2f\t%2c\n,one.a,one.b,one.c);
printf(Second structure \n);
printf(%2c\t %d\t %0.2f\n,two.a,two.b,two.c);
}
Output of the above program
First structure
23
11.89 F
Second structure
M
5
-45.78

Cyryx College

Page 53 of 70

Structured Programming in C

Unions
It is well known that a structure is a heterogeneous data type, which allows to pack together
different types of data values as a single unit. Union is also similar to a structure data type
but the way the data are stored and retrieved is different.
Union stores values of different types in a single location. A union may contain one of many
values (as long as only one is stored at a time). The declaration and the usage of the union is
the same as its structures. The union only holds a value for one data type. If a new
assignment is made, the previous value is forgotten.
The symbolic representation of a union declaration is as follows:
union user_defined_name
{
member 1;
member 2;
________;
________;
member n:
};
The keyword union is used to declare the union data type. This is followed by a user-defined
name surrounded by braces which describes the member of the union.
The general format of the union is :
storage_class union user_defined_name
{
data type member 1;
data type member 2;
_______________;
_______________;
data type member n;
};
The storage class is an optional. The keyword union and the braces are required. The data
type and members are any valid C data objects such as short integer, float, char.
A union may be a member of structure, and the structure may be a member of a union.
Moreover structures and unions may be freely mixed with arrays.

The union tag

It is permissible in C to define a union data type without declaring a variable. This is called as
a union tag. The general format of the union tag declaration is a sfollows.

Cyryx College

Page 54 of 70

Structured Programming in C
union user_defined_name
{
data_type member 1;
data_type member 2;
_________________
_________________
data_type member n;
} variable1, variable2,. Variable n;
For example,
union sample {
int first;
float second;
char third;
} one, two;
Where one and two are the union variables similar data size of the sample.
Processing with union
The period operator is used to in between the union variable name and the field name. Once
we have declared a union type, one can declare variables with that type.
union value
{
int c;
double d;
};
union value x;
As with structures we use the dot operator to access a unions individual fields. To assign to
the integer field of x we use
x.c;
y.d;
For example, the individual fields of a union can be assigned as follows.
x.c=12;
y.d=-123.456;
A program to initialize the member of a union and to display the contents of the uion.
#include<stdio.h>
main( )
{
union value{
int i;
float f;
};
union value x;
x.i=10;
x.f=-1456.45;
printf(First member %d\n,x.i);
printf(Second member %0.2f \n,x.f);
}
Cyryx College

Page 55 of 70

Structured Programming in C

Output of the above program


First member 3686
Second member 1456.45

In the above program, the union is declared to consist two members such as an int and a
float. Only the float values are stored and displayed correctly and the integer values are
displayed wrongly. The union only holds a value for one data type of the larger storage of
their members.
A program to declare a member of a union as a structure data type and to display the
contents of the union.
#include <stdio.h>
main( )
{
struct date{
int day;
int month;
int year;
};
union value{
int i;
float f;
struct date bdate;
};
union value x;
x.i=10;
x.f=-1456.45
x.bdate .day =12;
x.bdate.month=7;
x.bdate.year=2002;
printf(First Member %d\n,x.i);
printf(Second member %0.2f\n,x.f);
printf(structure\n);
printf(%d /%d /%d\n,x.bdate.day,x.bdate.month,x.bdate.year);
}

Output of the above program


First member 12
Second member 0.00
Structure:
12/07/2002

Cyryx College

Page 56 of 70

Structured Programming in C

DATA FILE OPERATIONS


File is a collection of data or set of characters may be a text or program. Basically there ate
two types of files used in the C languages; sequential file and random access file. The
sequential files are very easy to create then random access files. The data or text will be
stored or read back sequentially. In the random access file, the data can be accessed and
processed randomly.
REVIEW OF INPUT/OUTPUT FUNCTIONS
The C language supports very good portable features through it does not have many
internally built input/output facilities because the standard library gives all the salient
features such as character I/O, string I/, and file I/O. The features of the standard
functions may differ from one C compiler version to the other.

Character I/O
getchar( )
putchar( )
getch( )
putch( )

getchar( )
The getchar ( ) is a function to use as an input statement to read any alphanumeric character
from the standard input device usually by the keyboard. Normally C reads character as
integer and to accept a character as a value for a variable of type integer.
putchar( )
The putchar( ) is a complementary function of the getchar( ). It is used to display any
alphanumeric character on the standard output device normally on the screen. Normally, a
character argument should be placed inside the puthar( ) function.
A Program to read a character from the keyboard and to display in on the screen.
/* using getchar() and putchar()*/
#include<stdio.h>
main( )
{
int ch;
printf(Enter a character);
ch=getchar( );
/* to get input character */
putchar(ch);
/* to display it on the standard output */
}
Whenever single characters are to be read or written in a C program, getchar( ) and putchar(
) are used most ofter. These functions actually dont exist on the library. Instead, calls to
getchar( ) and putchar( ) are replaced by calls to getc( ) from stdin and to putc( ) to stdout by
the preprocessor.

Cyryx College

Page 57 of 70

Structured Programming in C

getch( )
The getch( ) is a function stdio.h library to read any alphanumeric character from the
standard device. There are two important differences betweer getchar( ) and getch( ). First,
when getchar( ) is used, it continues to access the keyboard until the carriage return key is
pressed, even though only the first character typed is returned to the program while getch( )
stops accessing the keyboard as soon as any key is pressed. Second, getchar( ) echoes the
character typed on to the screen while getch( ) does not. These differences contribute to
making interactions using getch( ) much faster than those using getchar( ).
putch( )
The putch( ) is a function of stdio.h library to display any alphanumeric character on to the
standard device normally on the screen.
A program to read a character from the keyboard and to display it on to the screen using the
getchar( ), getch( ),putchar( ), putch().
/* using getch() and putch() */
main( )
{
int ch;
printf(Enter a character and press carriage return \n);
ch=getchar( );
printf(Typed character is : );
putchar(ch);
printf(\n Now type a character \n);
ch=getch( );
pintf(Typed character is :);
putch(ch);
printf(\n);
}
The above program illustrates character I/O using getchar( ), putchar( ), getch( ), and putch(
). The standard input/output <stdio.h> library must be included in the program whenever
one uses these input and output functions.

String I/O
gets( )
puts( )
sscanf( )
sprintf( )

In the above section, we discussed about the character input/output facilities of the stdio.h.
In this section, we will see the string handling features of the C language. It is easy to read or
write strings of characters with gets( ) and puts( ).

Cyryx College

Page 58 of 70

Structured Programming in C

gets( )
The gets( ) function is used to read a set of alphanumeric characters from stdin until a
carriage return key is pressed and places a NULL in memory and rturns.
The general format of the gets ( ) function is :
gets(variable name);
The following program segment illustrates the usage of gets( )
#include <stdio.h>
main( )
{
char name[20];
gets(name);
}
puts( )
The puts( ) function continues to send characters to the stdout from memory that is from
the array we declare until it run into the NULL when it sends a newline and returns. Each of
these functions require the address of a character array as an argument. When a character
array for a string is declared it must be having space to accommodate for the NULL
character.
The general format of the puts( ) function is:
puts(variable name);
The following program segment illustrates the usage of gets( )
# include <stdio.h>
main( )
{
char name[20];
gets(name);
puts(name);
}
sscanf( )
The sscanf( ) function is used to read the formatted data like scanf function and the only
difference is that instead of keyboard, it reads from memory that is from he array we declare.
The general format of the sscanf function is:
sscanf(memory name, control charaters, variable names);

Cyryx College

Page 59 of 70

Structured Programming in C

The following program illustrates the usage of the sscanf( ) function.


#include <stdio.h>
main( )
{
char name[80];
int i,j;
float a,b;
gets(name);
sscanf(name, %d %d %f %f\n,I,j,a,b);
}
sprintf( )
The sprintf( ) function is used to write the formatted data like printf( ) function and the
difference is that it writes to an array in memory instead of screen. Each of these functions
requires the address of a character array as an argument.
The general format of the sprintf function is:
sprintf(memory name, control characters, variable names);
The following program segment illustrates the usage of the sprintf( ) function.
#include <stdio.h>
{
char name[80];
int i.j;
float a,b;
gets(name);
sprintf(name, %d %d %f %f\n, i, j,a,b);
}
A program to illustrate the usage of gets( ),puts( ), sscanf( ) and sprintf( ) for string input and
output operations.
/* using gets, puts, sscanf, sprintf () */
# include <stdio.h>
main( )
{
int x;
float y;
char a[40], line1[40], line 2[40];
printf(Type an integer, floating point value \n);
printf(and a string\n);
gets(line 1);
printf(typed characters \n);
puts (line 1);
sscanf(line 2,%d %f %s,&x.&y,&a);
printf(reading from the array line 1 \n);
Cyryx College

Page 60 of 70

Structured Programming in C

printf(%d %6.2f %s \n,x,y,a);


sprintf(line2, typed:[%6d][%6.2f][%s]\n,x,y,a);
printf(Reading from the array line 2\n);
puts (line2);

Out put of the above program


type an integer, floating point value
and a string
12 44.667 cyryx
typed characters
12 44.667 cyryx
reading from the array line 1
12 44.67 cyryx
reading from the array line 2
typed :[12] [44.67] [cyryx]
The above program performs sting i/o using several functions. First a string is read and
written using gets( ) and puts( ), after which the string is scanned for input using sscanf( )
and results are output another string using sprintf( ), finally, the output string is printed using
puts( ).

Opening and closing files


fopen( )
fclose( )
fopen( )
The fopen( ) function is used to open a specified file on the diskette. It has two string
arguments, which represent the name of the file and the type of I/O to be performed. There
are three- read, write and append represented by the strings r, w, and a respectively.
Some C compilers may include rb and wb types of I/O where the normal way of reading
and writing characters in ASCII rather than binary. The rb means read binary file and
wb means write into the binary file.
The general format of the file open command is as follows
fptr=fopen (filename,mode);
Where fptr is a pointer to a type FILE, filename is the system file name and is a
character string and mode is the type of operations to be performed.
The mode can be one of the types shown in the following.

Cyryx College

Page 61 of 70

Structured Programming in C

File names
Mode
w

Description
means write to the file, if the file name exists already on the diskette, then it
deleted and a new fill will be created.

means read from a file. If the file does not exist, error is returned,.ie. NULL
is returned as the value of fopen.

means append a file. New data are added to the end of the file.

r+

means open an existing file for updating

w+

means create new file for reading and writing

a+

means open for append, create if does not already exists.

fclose ( )
The fclose( ) function is used to close the file for re usage and the file pointer will be unliked
from the system name. Note that the argument for fclose is a file pointer not a file name.
fclose (fptr);
The fclose( ) function returns 0 if the close operation is successful, otherwise, it returns 1. it
is good practice to check for successful close operation because portion of a file can be lost
if it is not closed properly.
SIMPLE FILE OPERATIONS
File I/O
1.
2.
3.
4.

Character I/O
String I/O
Word I/O
Formatted I/O

Character I/O
Similar to ordinary way of character I/O handling in C, the file also can access to read and
write a character data type. The data elements such as characters are stored in Ascii format.
Sometimes, it is called the stream file processing; for the data elements are stored in
sequential format and the characters are sent, while reading one by one. The following
functions are used to handle the character I/O data types.
getch( fptr)
putc(ch,fptr)
fgetc(fptr)
fputc(ch,fptr)

Cyryx College

Page 62 of 70

Structured Programming in C
getc( )
The getc( ) function is used to read a single character from a given file, and returns the value
of the end of file (EOF) or an error is encountered.
The general format of the getc( ) function is as follows
ch=getc(fptr)
where fptr is a file pointer of the file, and ch is a variable receive the character.
The getc() function is normally in conditional loops to read a set of character from a file.
The following program segment continues to read a set of characters until an end of file
characters or an error is encountered.
#include <stdio.h>
main( )
{
FILE *in_file;
char name[20];
int ch;
printf(file name?\n);
scanf(%s,name);
in_file =open(s,r);
while ((ch-getch(in_file)) !=EOF)
___________________
___________________
A program to read a file and display the contents of the file on to the screen using getc( )
function
# include <stdio.h>
main ( )
{
FILE *in_file;
char s[20];
int c;
printf(Enter the file name :\n);
scanf(%s,s);
if ((in_file =fopen (s,r))=NULL)
{
printf(No such a file exists\n);
exit( );
}
else
{
while ((c=getc(in_file))!=EOF)
{
purchar;
}
}
fclose (in_file)
}

Cyryx College

Page 63 of 70

Structured Programming in C

fgetc( )
The fgetc( ) is also used to read a single character from a given file and returns the value eof
the end of the file (EOF) or an error is encountered. The getc( ) is a macro while fgetc( ) is
true function in the stdio.h library. The operations are otherwise same.
The general format of the fgetc( ) function is as follows
ch=fgetc( fptr)
where fptr is a file pointer of the file, and ch is a variable receive the character.
A program to read a file and to display the contents of the file on to the screen using fgetc( )
function.
#include <stdio.h>
main( )
{
FILE *in_file;
char s[20];
int c;
printf(Enter the file name ?\n);
scanf(%s,s);
if ((in_file=fopen (s,r))==NULL)
{
printf(No such a file exists);
exit( );
}
else
{
while ((c-fgetc(in_file))!=EOF)
{
putchar ( c );
}
}
fclose (in_file);
}

Formatted I/O

The stdio.h library provides all types data handling features for the requirement of a
programmer. Sometimes one may be required to store and retrieve only formatted data. The
formatted that can also be processed with a file handling. The following functions are used
to access and process the formatted data.
fscanf( )
fprintf( )

Cyryx College

Page 64 of 70

Structured Programming in C
fscanf( )
The fscanf( ) function is used to read a formatted data from a specified file. The control
string to read a format data is same as the scanf( ) function. The scanf( ) function reads from
the keyboard while fscanf( ) reads from a given file.
The general syntax of the fscanf( ) function is as follows:
fscanf(fptr,controlstring,&list)
Where fptr is a file pointer to receive a formatted data, control string is a different
format commands such as %d %f etc and list is a variable parameter list to be read
from the specified file and normally the list is used along with address operator.
The following program segment illustrates the fscanf( ) function:
#include <stdio.h>
main( )
{
FILE *in_file;
int x,y;
in_file=fopen(name,r);
____________
____________
while ((fscanf(in_file, %d %d ,&x,&y))!=EOF)
{
____________
____________
}
fprintf( )
The fprintf( ) function is used to write a formatted data into a given file. The printf( )
function is used to write or display the formatted data on the screen while the fprintf( ) is
used to write a specified file. The control string is same for both printf and fprintf( )
functions.
The general format of the fprintf( ) is as follows:
fprintf(fptr,control string,list)
where fptr is a file pointer to write a formatted data, control string is a format
command such as %d, %c, %f etc and list is the variable list to be written on to the
file.

Cyryx College

Page 65 of 70

Structured Programming in C

The following program illustrates the usafe of fprintf( )


#include <stdio.h>
main( )
{
FILE *in_file;
int x,y;
in_file=fopen(name,w);
______________
______________
fprintf(in_file,%d %d\n,x,y);
______________
______________
fclose(in_file)
}
A program to store the number and its square from 0 to 10 on a given file and to read the
same file and to display the contents of the file on to the screen.
/* using fprintf( ) and fscanf( ) */
# include <stdio.h>
main( )
{
FILE *out_file;
int i,n;
int x,y;
char s[20];
printf(Enter a file name for writing \n);
scanf(%s,s);
if((out_file=fopen(name,w))==NULL)
{
printf(Error in writing\n);
exit( );
}
else
{
n=10;
i=0;
printf(number square \n);
printf(_____________\n);
while (i<=n)
{
printf(%d\t %d\n, i, i* i);
fprintf(out_file,%d \t %d\n,i,i*i);
i++;
}
floes (out_file);
}
Cyryx College

Page 66 of 70

Structured Programming in C
}
printf(Enter a file name for reading\n);
scanf(%s,s);
if((out_file=fopen(name,r))=NULL)
{
printf(No such a file exists\n);
exit( );
}
else
{
printf(Reading from the file \n);
printf(Number Square \n);
printf(__________________\n);
while ((fscanf(out_file,%d\t %d\n,&x,&y)) != EOF)
printf(%d \t %d \n,x,y);
fclose (out_file);
}
}
Structures and file operations
The fscanf( ) and fprintf( ) are used to read and write a structure to the file respectively.
The following program segment illustrates the oprations of structures and fprintf( )
#include <stdio.h>
main ( )
{
FILE *out_file;
struct database
{
char name[20];
int age;
};
struct database person;
------------------------------------------------fprintf(pit_file,%s\t,person.name);
fprintf(out_file,%d\n,person.age);
_______________
_______________
fclose (out_file);
}

Cyryx College

Page 67 of 70

Structured Programming in C
A program to read a set of structures elements from the keyboard and to store it on a
specified file and again to read the same file and to display the contents of the file.
/* strucurs and file operations */
#include <stdio.h>
FILE *in_file;
struct student{
char name[20];
int rollno;
float weight;
float height;
};
struct student a[20];
int n;
char s[20];
main( )
{
int ch;
menu( )
while ((ch=getchar( ))!=q)
{
menu( );
switch(ch)
{
case a;
appending( );
break;
case r
reading( );
break
case w
saving( );
break;
}
}
}
menu( )
{
printf(a-appending a record\n);
printf(r-reading from the file\n);
printf(w-writing to the file\n);
printf(q-quit\n);
}

Cyryx College

Page 68 of 70

Structured Programming in C
appending( )
{
int i;
printf(How many students?\n);
scanf(%d,&n);
for (i=0; i<=n-1; i++)
{
printf(Name:);
scanf(%s,&a[i].name);
printf(Roll No:);
scanf(%d,&a[i].rllno);
printf(Height:);
scanf(%f,&a[i].height);
printf(Weight:);
scanf(%f,&a[i].weight);
}
saving( );
}
saving( )
{
it i;
printf(File Nam:\n);
scanf(%s,s);
if((in_file=fopen(s,s))==NULL)
{
printf(No such a file exists\n);
exit( );
}
else
{
for (i=0; i<-n-1; i++)
{
fprintf(in_file, %s\t,a[i].name);
fprintf(in_file, %d\t,a[i].rollno;
fprintf(in_file, %0.2f\t,a[i].height);
fprintf(in_file, %0.2f\t,a[i].weight);
fprintf(in_file, \n);
}
fclose (in_file);
}
}

Cyryx College

Page 69 of 70

Structured Programming in C
reading( )
{
int i;
printf(File Name:\n);
scanf(%s,s);
if((in_file=fopen(s,r))==NULL)
{
printf(No such a file exists\n);
exit( );
}
else
{
i=0;
while (fscanf(in_file,%s %d %f %f\n,&a[i].name, &a[i].rollno,&a[i].height,&a[i].weight );
i++;
}
n=i;
printf(Reading from the file \n);
printf(Name Roll_No
Height Weight
\n);
printf(_____ _______
_____ ______
\n);
for (i=0; i<=n; i++)
{
printf(%s\t,a[i].name);
printf(%d\t,a[i].rollno);
printf(%0.2f\t,a[i].height);
printf(%0.2f\t,a[i].weight);
}
fclose(in_file);
}
}
**************

Cyryx College

Page 70 of 70

Das könnte Ihnen auch gefallen