C PROGRAMMING
INTRODUCTION TO C PROGRAMMING
C is a general-purpose computer programming language developed in 1972 by
Dennis Ritchie at the Bell
Telephone Laboratories for use with
the Unix operating system. C is a structured programming language,
which means that it allows you to develop programs using well-defined control
structures (you will learn about control structures in the articles
to come), and provides modularity (breaking the task into multiple sub
tasks that are simple enough to understand and to reuse). C is often called a
middle-level language because it combines the best elements of low-level or
machine language with high-level languages.
Where is C useful?
C’s ability to
communicate directly with hardware makes it a powerful choice for system
programmers. In fact, popular operating systems such as Unix and Linux are
written entirely in C. Additionally, even compilers and interpreters for other
languages such as FORTRAN, Pascal, and BASIC are written in C. However, C’s
scope is not just limited to developing system programs. It is also used to
develop any kind of application, including complex business ones. The following
is a partial list of areas where C language is used:
Ø
Embedded Systems
Ø
Systems Programming
Ø
Artificial Intelligence
Ø
Industrial Automation
Ø
Computer Graphics
Ø
Space Research
Why you should learn C?
You
should learn C because:
·
C is simple.
·
There are only 32 keywords so C is very
easy to master. Keywords are words that have special meaning in C language.
·
C programs run faster than programs written in
most other languages.
·
C enables easy communication with computer
hardware making it easy to write system programs such as compilers and interpreters.
WHY WE NEED DATA AND A PROGRAM:
Any
computer program has two entities to consider, the data, and the program. They
are highly dependent on one another and careful planning of both will lead to a
well planned and well written program. Unfortunately, it is not possible to
study either completely without a good working knowledge of the other. For that
reason, this tutorial will jump back and forth between teaching methods of
program writing and methods of data definition. Simply follow along and you
will have a good understanding of both. Keep in mind that, even though it seems
expedient to sometimes jump right into coding the program, time spent planning
the data structures will be well spent and the quality of the final program
will reflect the original planning
How to run a
simple c program
1. Copy
Turbo c/c++ in computer
2. Open
c:\tc\bin\tc.exe
3. A
window appears
4. Select
File->new to open a new file
5. Type
the following program on editor
#include
<stdio.h>
void
main()
{
printf(“hello”);
}
6. compile the program by pressing ALT+F9
7. Run the program by pressing CTRL +F9
Note:
1. C is case sensitive
2. Always terminate statements with semicolon.
3. A program starts with main()
Explanation of program
#include is known as compiler directive. A
compiler directive is a command to compiler to translate the program in a
certain way. These statement are not converted into machine language but only
perform some other task.
main() is a function which the staring point for
complier to start compilation. So a function must contain a main() function.
Detection and
Correction of Errors:
Syntactic
errors and execution errors usually result in the generation of error messages
when compiling or executing a program. Error of this type is usually quite easy
to find and correct. There are some logical errors that can be very difficult
to detect. Since the output resulting from a logically incorrect program may
appear to be error free. Logical errors are often hard to find, so in order to
find and correct errors of this type is known as logical debugging. To detect
errors test a new program with data that will give a known answer. If the
correct results are not obtained then the program obviously contains errors
even if the correct results are obtained.
Computer
Applications: However you cannot be sure that the program is error free, since
some errors cause incorrect result only under certain circumstances. Therefore
a new program should receive thorough testing before it is considered to be
debugged. Once it has been established that a program contains a logical error,
some ingenuity may be required to find the error. Error detection should always
begin with a thorough review of each logical group of statements within the
program. If the error cannot be found, it sometimes helps to set the program
aside for a while. If an error cannot be located simply by inspection, the
program should be modified to print out certain intermediate results and then
be rerun. This technique is referred to as tracing. The source of error will
often become evident once these intermediate calculations have been carefully
examined. The greater the amount of intermediate output, the more likely the
chances of pointing the source of errors. Sometimes an error simply cannot be
located. Some C compilers include a debugger, which is a special program that
facilitates the detection of errors in C programs. In particular a debugger
allows the execution of a source program to be suspended at designated places,
called break points, revealing the values assigned to the program variables and
array elements at the time execution stops. Some debuggers also allow a program
to execute continuously until some specified error condition has occurred. By
examining the values assigned to the variables at the break points, it is
easier to determine when and where an error originates.
Linear Programming
Linear
program is a method for straightforward programming in a sequential manner.
This type of programming does not involve any decision making. General model of
these linear programs is:
1.
Read a data value
2.
Computer an intermediate result
3.
Use the
intermediate result to computer the desired answer
4.
Print the answer
5.
Stop
Structured Programming
Structured
programming (sometimes known as modular programming) is a subset of
procedural programming that enforces a logical structure on the program being
written to make it more efficient and easier to understand and modify. Certain
languages such as Ada, Pascal, and dBASE are designed with
features that encourage or enforce a logical program structure.
Structured programming frequently
employs a top-down design model, in which developers map out the overall
program structure into separate subsections. A defined function or set of
similar functions is coded in a separate module or sub module, which means that
code can be loaded into memory more efficiently and that modules
can be reused in other programs. After a module has been tested individually,
it is then integrated with other modules into the overall program structure.
Advantages of Structured Programming
1.
Easy to write:
Modular design increases the programmer's productivity by allowing them to look at the big picture first and focus on details later.Several Programmers can work on a single, large program, each working on a different module. Studies show structured programs take less time to write than standard programs. Procedures written for one program can be reused in other programs requiring the same task. A procedure that can be used in many programs is said to be reusable.
Modular design increases the programmer's productivity by allowing them to look at the big picture first and focus on details later.Several Programmers can work on a single, large program, each working on a different module. Studies show structured programs take less time to write than standard programs. Procedures written for one program can be reused in other programs requiring the same task. A procedure that can be used in many programs is said to be reusable.
2. Easy
to debug:
Since each procedure is specialized to perform just one task, a procedure can be checked individually. Older unstructured programs consist of a sequence of instructions that are not grouped for specific tasks. The logic of such programs is cluttered with details and therefore difficult to follow.
Since each procedure is specialized to perform just one task, a procedure can be checked individually. Older unstructured programs consist of a sequence of instructions that are not grouped for specific tasks. The logic of such programs is cluttered with details and therefore difficult to follow.
3. Easy
to Understand:
The relationship between the procedures shows the modular design of the program. Meaningful procedure names and clear documentation identify the task performed by each module. Meaningful variable names help the programmer identify the purpose of each variable.
The relationship between the procedures shows the modular design of the program. Meaningful procedure names and clear documentation identify the task performed by each module. Meaningful variable names help the programmer identify the purpose of each variable.
4. Easy
to Change:
Since a correctly written structured program is self-documenting, it can be easily understood by another programmer.
Since a correctly written structured program is self-documenting, it can be easily understood by another programmer.
Structured
Programming Constructs
It uses only three constructs -
- Sequence (statements, blocks)
- Selection (if, switch)
- Iteration (loops like while and for)
Sequence
- Any valid expression terminated by a semicolon is a statement.
- Statements may be grouped together by surrounding them with a pair of curly braces.
- Such a group is syntactically equivalent to one statement and can be inserted where ever
- One statement is legal.
Selection
The selection constructs allow us to
follow different paths in different situations. We may also think of them as
enabling us to express decisions.
The
main selection construct is:
if (expression)
statement1
else
statement2
statement1 is executed if and
only if expression evaluates to some non-zero number. If expression evaluates
to 0, statement1 is not executed. In that case, statement2 is
executed.
If and else are independent
constructs, in that if can occur without else (but not the reverse).Any else is
paired with the most recent else-less if, unless curly braces enforce a
different scheme. Note that only curly braces, not parentheses, must be used to
enforce the pairing. Parentheses
Iteration
Looping is a way by which we can
execute any some set of statements more than one times continuously .In C there
are mainly three types of loops are used :
·
while Loop
·
do while Loop
·
For Loop
The
control structures are easy to use because of the following reasons:
1)
They
are easy to recognize
2)
They
are simple to deal with as they have just one entry and one exit point
3)
They
are free of the complications of any particular programming language
Modular
Design of Programs
One
of the key concepts in the application of programming is the design of a
program as a set of units referred to as blocks or modules. A style that breaks large computer programs into smaller elements called
modules. Each module performs a single task; often a task that needs to be
performed multiple times during the running of a program. Each module also stands
alone with defined input and output. Since modules are able to be reused they
can be designed to be used for multiple programs. By debugging each module and
only including it when it performs its defined task, larger programs are easier
to debug because large sections of the code have already been evaluated for
errors. That usually means errors will be in the logic that calls the various
modules.
Languages like Modula-2 were
designed for use with modular programming. Modular programming has generally evolved
into object-oriented programming.
Programs can be logically separated into the following functional
modules:
1)
Initialization
2)
Input
3)
Input Data Validation
4)
Processing
5)
Output
6)
Error Handling
7)
Closing procedure
Basic attributes of modular programming:
1)
Input
2)
Output
3)
Function
4)
Mechanism
5)
Internal data
Control Relationship between modules:
The
structure charts show the interrelationships of modules by arranging them at
different levels and connecting modules in those levels by arrows. An arrow
between two modules means the program control is passed from one module to the
other at execution time. The first module is said to call or invoke the lower
level modules.There are three rules for controlling the relationship between
modules.
1)
There is only one module at the top of the structure.
This is called the root or boss module.
2) The
root passes control down the structure chart to the lower level modules.
However, control is always returned to the invoking module and a finished
module should always terminate at the root.
3) There
can be more than one control relationship between two modules on the structure
chart, thus, if module A invokes module B, then B cannot invoke module A.
Communication between modules:
1)
Data: Shown
by an arrow with empty circle at its tail.
2)
Control : Shown
by a filled-in circle at the end of the tail of arrow
Module Design Requirements
A
hierarchical or module structure should prevent many advantages in management,
developing, testing and maintenance. However, such advantages will occur only
if modules fulfill the following requirements.
a) Coupling: In computer science,
coupling is considered to be the degree to which each program module relies on
other modules, and is also the term used to describe connecting two or more
systems. Coupling is broken down into loose coupling, tight coupling, and
decoupled. Coupling is also used to describe software as well as systems. Also
called dependency
Types of Programming
Language
Low Level Language
First-generation language is the
lowest level computer language. Information is
conveyed to the computer by the programmer
as binary instructions. Binary
instructions are the equivalent of the on/off signals used by computers to
carry out operations. The language consists of zeros and ones. In the 1940s and
1950s, computers were programmed by scientists sitting before control panels
equipped with toggle switches so that they could input instructions as strings
of zeros and ones.
Advantages
Ø
Fast and efficient
Ø
Machine oriented
Ø
No translation required
Disadvantages
Ø
Not portable
Ø
Not programmer friendly
Assembly Language
Assembly or assembler language was
the second generation of computer language. By the late
1950s, this language had become popular. Assembly language consists of letters
of the alphabet. This makes programming much easier than trying to program a
series of zeros and ones. As an added programming assist, assembly language
makes use of mnemonics, or memory aids, which are easier for the human programmer to recall than are
numerical codes.
Assembler
An
assembler is a program that takes basic computer instructions and converts them into a
pattern of bits that the computer's processor can use to perform its basic
operations. Some people call these instructions assembler language and others
use the term assembly language In other words An assembler
is a computer program for translating assembly language
— essentially, a mnemonic representation of machine language — into object code. A cross assembler
(see cross compiler) produces code for one
processor, but runs on another.
As
well as translating assembly instruction mnemonics into opcodes, assemblers provide the ability
to use symbolic names for memory locations (saving tedious calculations and
manually updating addresses when a program is slightly modified), and macro facilities for performing textual
substitution — typically used to encode common short sequences of instructions
to run inline instead of in a subroutine.
High Level Language
The introduction of the compiler in 1952 spurred the development of third-generation computer languages. These languages enable a programmer to create program files using commands that are similar to spoken English. Third-level computer languages have become the major means of communication between the digital computer and its user. By 1957, the International Business Machine Corporation (IBM) had created a language called FORTRAN (FORmula TRANslater). This language was designed for scientific work involving complicated mathematical formulas. It became the first high-level programming language (or "source code") to be used by many computer users.
Within the next few years,
refinements gave rise to ALGOL (ALGOrithmic Language) and COBOL (COmmon
Business Oriented Language). COBOL is noteworthy because it improved the record
keeping and data management ability of
businesses, which stimulated business expansion.
Advantages
Ø Portable
or machine independent
Ø
Programmer-friendly
Disadvantages
Ø
Not as efficient as low-level languages
Ø
Need to be translated
Examples : C, C++, Java,
FORTRAN, Visual Basic, and Delphi.
Interpreter
An
interpreter is a computer program that executes other programs. This is in
contrast to a compiler which does not execute its input
program (the source code) but translates it into executable machine code (also called object code) which is output to a file
for later execution. It may be possible to execute the same source code either
directly by an interpreter or by compiling it and then executing the machine
code produced.
It
takes longer to run a program under an interpreter than to run the compiled
code but it can take less time to interpret it than the total required to
compile and run it. This is especially important when prototyping and testing
code when an edit-interpret-debug cycle can often be much shorter than an
edit-compile-run-debug cycle.
Interpreting
code is slower than running the compiled code because the interpreter must
analyses each statement in the program each time it is executed and then
perform the desired action whereas the compiled code just performs the action.
This run-time analysis is known as "interpretive overhead". Access to
variables is also slower in an interpreter because the mapping of identifiers
to storage locations must be done repeatedly at run-time rather than at compile
time.
COMPILER:
A
program
that translates source code into object code. The compiler derives its
name from the way it works, looking at the entire piece of source code and
collecting and reorganizing the instructions. Thus, a compiler differs from an interpreter, which analyzes and executes each line of source code in
succession, without looking at the entire program. The advantage of
interpreters is that they can execute a program immediately. Compilers require
some time before an executable program emerges. However, programs produced by
compilers run
much faster than the same programs executed by an interpreter.
Every
high-level programming language (except
strictly interpretive languages) comes with a compiler. In effect, the compiler
is the language,
because it defines which instructions are acceptable.
Data
types:
- C language is rich in data types
- ANSI – American National Standard Institute
- ANSI C Supports Three classes of data types.
1. Primary data type (fundamental)
2. Derived data types
3. User defined data types
All “C” compiler supports 5 fundamental data types
1. Integer
(int)
2. Character
(char)
3. floating point (float)
4. double-precession (double)
5. void
Declaration
of Variable :
It tells the complier what the variable name
is used, what type of date is held by the variable.
Syn: datatype v1,v2,….vn;
Eg : int a, b;
float sum;
double ratio;
Representation of
Constant
const int r = 10;
Assigning values to
variables
Eg : int x,y;
x= 10;
y=5;
Programs : Program for
variable declaration
main(
)
{
float x,p;
x=10.1;
p=5.2;
printf (“x = %f”, x);
printf (“p =
%f”, p);
}
O/P
:
x= 10.10000
p = 5.2
Operators
An operator is a symbol that tells the Computer to
perform certain mathematical or logical manipulations.
Expression:
An expression is a sequence of operands and
operators that reduces to single value
Eg:
10+25 is an expression whose value is 35
C operators can be classified into a no. of
categories.
They
include:
1. Arithmetic
2. Relational
3. Logical
4. Assignment
5. Increment and Decrement
6. Conditional
7. Bitwise
8. Special
Arithmetic Operators:
C provides
all the basic arithmetic operators, they
are +, -, *, /, % Integer division
truncates any fractional part. The
modulo division produces the remainder of an integer division.
Eg:
a + b a – b a *
b
-a * b
a / b a % b
Here
“a” and “b” are variables and are known as operands.
%
cannot be used for floating point data.
C
does not have an operator for exponentiation.
Integer Arithmetic:
When the operands in an expression are integers then the expression is an
integer expression and the operation is called integer arithmetic. This always
yields an integer value. For Eg. a = 14
and n = 4 then
a
- b = 10 Note : During modulo
division,the
a
+ b = 18 sign of the result is always
the sign
a
* b = 56 of the first operand (the
dividend )
a
/ b = 3 - 14 % 3 = -2
a
% b = 2 -14 % - 3 = 2
14
% -3 = 2
Program to illustrate the use of all
Arithmetic operator
main ( )
{
int sum, prod , sub, div, mod, a, b ;
printf(“Enter
values of a, b :”) ;
scanf(“
/.d %d”, & a, & b) ;
sum
= a+b ;
printf(“sum
= %d”, sum);
sub = a-b;
printf(“sub
= %d”, sub);
prod = a * b ;
printf(“prod
= %d”, a* b);
div = a/b;
printf(“
Div = %d”, div);
mod = a % b ;
printf(“
mod = %d”,a % b);
}
Real Arithmetic /
Floating Pont Arithmetic:
Floating Point Arithmetic involves only real
operands of decimal or exponential notation. If x, y & z are floats,
then
x = 6.0/7.0 = 0.857143
y = -1.0/3.0 = 0.333333
z = 3.0/2.0 = 1.500000
%
cannot be used with real operands
Mixed mode Arithmetic:
When one of the operands is real and the other is
integer the expression is a mixed mode arithmetic expression.
Eg:
15/10.0 = 1.500000
15/10 = 1
10/15 = 0
-10.0/15 = -0.666667
Relational Operator:
These are the operators used to Compare arithmetic,
logical and character expressions.the value of a relational express is either
one or zero .it is 1 if one is the specified relation is true and zero if it is
false
For eg:
10 < 20 is
true 20<10 is false
The
relational operators in C are
Operator Meaning
<
is
less than
< =
is
less than or equal to
>
is
greater than or equal to
> =
is
greater than or equal to
= =
is
equal to
! =
is
not equal to
eg
Condition Return
values
10 != 10 : 0
10
= =
10 : 1
10 > = 10
: 1
10 ! = 9 : 1
Program
to illustrate the use of Logical Operators
void
main ( )
{ clrscr ( );
printf(“In 5>3 && 5<10 : %3d”,
5>3&&5<10);
printf(“
In 8<5 || 5= =5 : % 3d”, 8<5 || 5= =5);
printf(“In !(8 = =8)
: %3d”, !(8= =8) ;
}
O/P
5>3 && 5<10
: 1
8<5 || 5= =5 : 1
!(8 = =8)
: 0
Program
to show the effect of increment and decrement operators
main
( )
{
int
x = 10, y = 20, z, a ;
z=
x * y ++;
a
= x * y ;
printf(“
%d % d\n”, z,a);
z
= x * ++y;
a
= x * y;
printf(“
%d %d\n”, z, a);
printf(“
++ x = %d, x++=%d”, ++x, x++);
}
O/P
200
210
220
220
12 10
Logical
operator:
Logical Operators are used when we want to test more
than one condition and make decisions. here the operands can be constants,
variables and expressions Logical operators are &&, ||, !
Eg:
a > b && x = = 10
Assignment Operator:
Used
to assign the result of an expression to a variable. „= „is the assignment operator. In addition
C has a set of „short hand‟ assignment operators of the form
Var
Op = Exp :
Binary
arithmetic operator
var op = exp;
is
equivalent to
var
= var op exp;
Eg:
x + = 1; == > x = x+1
x+ = y+1 == > x = x+y+1
Program
to print whether a given number is even or odd
main()
{
int a, b
printf(“ Enter a number “);
scanf(“ %d”, & a);
b = a%z;
((b = =o)?
printf(“Even”): printf(“odd”);
}
Program
to print logic 1 if input character is capital otherwise o
main
( )
{
char
x ; int y;
printf((“ \n nter a character” );
scanf(“ % C “, & x);
y = (x>=65 && x <=90? 1:0);
printf(“ y : %d”, y);
}
O/P
1) Enter a character : A
2)
Enter a character : a
y : o
Shorthand
operator Assignment operator
a
+ = 1 a = a+1
a
- = 1 a=a-1
a
* = n+1 a = a* (n + 1)
a
/ = n+1 a = a/(n+1)
a
% = b a
= a % b
Increment and Decrement
Operators:
++
and - -
The
Operator + + adds 1 to the operand while -- subtracts 1, Both are unary operators
Eg
: ++x or x ++ == > x+=1 == > x=x+1
. -- x or
x- - == > x-=1 == > x=x-1
A
Prefix operator first adds 1 to the operand and then the result is assigned to
the variable on left. A postfix operator
first assigns the value to the variable on the left and the increments the
operand.
Eg:
1) m = 5; 2). m = 5
y = ++m; y = m++
O/P
m =6, y=6 m=6, y=5
Conditional
operator
Conditional operator is used to check a condition
and Select a Value depending on the Value of the condition.
Variable
= (condition)? Value 1 : Value 2:
If the Value of the condition is true then Value 1
is e valued assigned to the varable, otherwise Value2.
Eg:
big = (a>b)? a:b;
This
exp is equal to
if
(a>b)
big
= a;
else
big
= b;
Bitwise operator
- Bitwise operators are used to perform operations at binary level i. e. bitwise.
- These operators are used for testing the bits, or Shifting them right or left .
- These operators are not applicable to float or double. Following are the Bitwise operators with their meanings.
Operator
Meaning
&
Bitwise AND
|
Bitwise OR
^
Bitwise Exclusive – OR
<< Left Shift
>>
Right Shift
~
Complement
Sizeof
operator :
It is used to
find the on. of bytes occupied by
a variable / data type in computer
memory.
eg : sizeof (float)
returns 4
int m,
x [ 50 ]
sizeof (m) returns
2
sizeof ( x )
returns 100 ( 50 x 2 )
Program
to illustrate the use of size of
operator
main ( )
{
int x = 2;
float y = 2;
printf (“ in
size of ( x ) is %d bytes “, sizeof
( x ));
printf (“ in
size of ( y ) is %d bytes “, sizeof
( y ));
printf (“ in
Address of x = % u and y = % u “,
& x, & y);
}
o/p sizeof ( x ) = 2
sizeof ( y ) = 4
Address of x = 4066
and y =
25096
Comma operator :
- It can be used to link the related expressions together.
Eg
: value = ( x
= 10, y = 5, x = y)
First 10 is
assigned to x
then 5 is
assigned to y
finally x + y
i .e. which 15
is assigned to
value .
since
comma has the lowest
precedence of all operator, the
parantheses are necessary .
Operator - precedence &
Associativity
Precedence is
nothing but priority that
indicates which operator has to be evaluated first when there are more
than one operator.
Associativity : when
there are more than one operator with same precedence [ priority ] then we
consider associativity , which indicated
the order in‟ which the
expression has to be evaluated. It may be either from Left to Right or
Right to Left.
eg
: 5 * 4 + 10 / 2
1 2
=
20 + 5
3
=25
Basic Input output :
C has many input output functions in order to read
data from input devices and display the results on the screen.
scanf
( ) printf( )
getch() putch()
getchar
( ) puts
( ) gets ( )
scanf
( )
- Function is used to read values using key board. It is used for runtime assignment of variables.
- The general form of scanf( ) is
scanf(“format String “
, list_of_addresses_of_Variables );
- The format string contains
-
Conversion
specifications that begin with % sign
- Eg: Scan f(“ %d %f %c”, &a &b, &c)
- “&” is called the “address” operator.
- In scanf( ) the “&‟ operator indicates the memory location of the variable. So that the Value read would be placed at that location.
printf( ):
- Function is used to Print / display values of variables using monitor:
- The general form of printf( ) is
- printf(“control String “ , list_of_ Variables );
-
Characters that are
simply printed as they are - Conversion
specifications that begin with a % sign - Escape sequences that begin with a
„\‟ sign.
Eg: Program
main (
)
{
int avg = 346;
float per = 69.2;
printf(“ Average = %d \n percentage = %f”,
avg, per);
}
O/P
Average
= 346
Percentage
= 69.200000
getchar ( )
Function
is used to read one character at a time from the key board
Syntax
ch
= getchar ( );
where ch is a char Var.
putchar ( ):
This
function is used to display one character at a time on the monitor.
Syntax: putchar (ch);
Ex
char ch = „M‟
putchar
(ch);
The
Computer display the value char of variable „ch‟ i.e M on the Screen.
getch ( ):
This
function is used to read a char from a key board and does not expect the
“enter” key press.
Syntax:
ch
= getch ( );
When
this function is executed ,computer waits for a key to be pressed from the key
board. As soon as a key is pressed, the control is transferred to the nextline
of the program and the value is assigned to the char variable. It is noted that
the char pressed will not be display on the screen.
String I/O functions
gets ( ) function
is used to read a string of characters including white spaces. Note that white
spaces in a string cannot be read using scanf( ) with %s format specifier.
Syntax:
gets (S);
where
“S‟ is a char string variable
Ex:
char S[ 20 ];
gets (S);
When
this function is executed the computer waits for the string to be entered
CONTROL STRUCTURES /
STATEMENTS
- A program is nothing but the execution of sequence of one or more instructions.
I.
Decision making statements
1) Simple if Statement
2) if – else
Statement
3) Nested if-else
statement
4) else – if
Ladder
5) switch
statement
II.
Loop control statements
1) for Loop
2) while Loop
3) do-while Loop
III.
Unconditional control statements
1) goto Statement
2) break Statement
3) continue Statement
I.
Decision Making Statements
(1) Simple “if” statement:
The
“if‟ statement is a powerful decision making statement and is used to
control the flow of
execution of statements.
Syntax:
if (Condition or test expression)
Statement;
Rest of the
program
Program
to check equivalence of two numbers. Use “if” statement. # include<stdio.h>
#
include<conio.h>
void main( )
{
int
m,n;
clrscr( );
printf(“\n Enter two numbers:”);
scanf(“%d %d”, &m, &n);
if((m-n)= =0)
printf(“\n two numbers are equal”);
//Rest of the program
---------
---------
getch();
}
Output:
Enter
two numbers: 5 5
Two
numbers are equal.
(2) “if-else” Statement:
It is
observed that the if statement executes only when the condition following if is
true
Syntax:
if ( Test Expression or Condition
)
{
Statements; /*true block (or) if block
*/
}
else
{
Statements; /* false block (or) else block
*/
}
Program to print the given number is even or
odd.
#
include<stdio.h>
#
include<conio.h>
main(
)
{
int
n;
clrscr(
);
printf(“Enter
a number:”);
scanf(“%d”,
&n);
if( (n%2)==0 )
printf(“\n The given number is
EVEN ”);
else
printf(“\n The given
number is ODD ”);
getch( );
}
Output:
Run
1:
Enter
a number: 24
The given number is EVEN
Run
2: /* that means one more time we run
the program */
Enter
a number: 17
The given number is ODD
Program
accept two numbers and find largest number and print.
#
include<stdio.h>
#
include<conio.h>
main(
)
{
int
a,b;
clrscr(
);
printf(“Enter
Two numbers:”);
scanf(“%d%d”,
&a,&b);
if( a>b )
printf(“\n %d is largest
number”,a);
else
printf(“\n %d is
largest number”,b);
getch( );
}
Output:
Run
1:
Enter
Two numbers: 13 30
30 is largest number
Run
2: /* that means one more time we run
the program */
Enter
Two numbers: 235 174
235
is largest number
(3)
Nested “if–else” Statement:
Using
of one if-else statement in another if-else statement is called as nested
if-else control statement. When a series of decisions are involved, we may have
to use more than one if- else statement
in nested form.
Syntax:
if
( Test Condition1)
{
if
( Test Condition2)
{
Statement -1;
}
else
{
Statement -2;
}
}
else
{
if ( Test Condition3)
{
Statement -3;
}
else
{
Statement -4;
}
} /* end of outer if-else */
(4) The “else – if” Ladder:
This is another way of putting if „s together when
multiple decisions are involved.
A multipath decision is
a chain of if ‟s in which the statement associated with each else is an
if.
Hence it forms a ladder called else–if ladder.
Syntax:
if (Test Condition -1)
Statement -1;
else
if ( Test Condition -2)
Statement -2;
else if ( Test Condition -3)
Statement -3;
:
:
:
:
else if ( Test Condition –n)
Statement
–n;
else
default statement;
Rest of the Program
Statements-X;
Program
to read three numbers and find the largest one by using “else-if” ladder. # include<stdio.h>
#
include<conio.h>
main(
)
{
int
a, b, c
clrscr
( ) ;
printf(“Enter
1st number:”);
scanf(“%d”,
&a);
printf(“Enter
2nd number:”);
scanf(“%d”,
&b);
printf(“Enter
3rd number:”);
scanf(“%d”,
&c);
if ((a>b) && (a>c))
printf(“Highest Number is: %d”,
a);
else if ((b>a) &&
(b>c))
printf(“Highest Number is: %d”, b);
else
printf(“Highest Numbers is: %d”,
c);
getch(
);
}
Output:
Run-1:
Enter 1st number: 52
Enter 2nd number: 74
Enter 3rd number: 90
Highest Numbers is: 90
Run-2:
Enter 1st number: 81
Enter 2nd number: 237
Enter 3rd number: 65
Highest Numbers is: 237
(5) The “switch-case”
Statement:
- The switch statement causes a particular group of statements to be chosen from several available groups.
- The selection is based upon the current value of an expression which is included within the switch statement.
- The switch statement is a multi-way branch statement.
- In a program if there is a possibility to make a choice from a number of options, this structured selected is useful.
- The switch statement requires only one argument of int or char data type, which is checked with number of case options.
- The switch statement evaluates expression and then looks for its value among the case constants.
- If the value matches with case constant, then that particular case statement is executed.
- If no one case constant not matched then default is executed.
- Here switch, case and default are reserved words or keywords.
- Every case statement terminates with colon “:”.
- In switch each case block should end with break statement, i.e. break;
Syntax:
switch(variable
or expression)
{
case Constantvalue-1: Block -1;
(or)
Statement-1;
break;
case Constantvalue-2: Block -2;
(or)
Statement-2;
break;
_
_ _ _ _
_ _ _
_
_ _ _ _
_ _ _
case Constantvalue-n: Block -n;
(or)
Statement-n;
break;
default: default – block; (or) Statement;
}
Pprogram
to provide multiple functions such as 1. Addition 2. Subtraction 3. Multiplication 4. Division 5. Remainder
6. Larger out of two 7. Exit using “switch” statement.
#
include<stdio.h>
#
include<conio.h>
main(
)
{
int a, b, c, ch;
clrscr ( ) ;
printf(“\t = = = = = = = = = = = =
= =”);
printf (“n\t MENU”);
printf(“\n\t= = = = = = = = = = =”);
printf(“\n \t [1] ADDITION” );
printf(“\n \t [2] SUBTRACTION”
);
printf(“\n \t [3] MULTIPLICATION”
);
printf(“\n \t [4] DIVISION” );
printf(“\n \t [5] REMAINDER” );
printf(“\n \t [6] LARGER OUT OF
TWO” );
printf(“\n \t [7] EXIT” );
printf(“\n \t = = = = = = = = =
=”);
printf(“ \n\n\t ENTER YOUR
CHOICE:”);
scanf(“%d”, &ch);
if(ch < = 6 && ch
>=1)
{
printf(“ENTER TWO
NUMBERS:”);
scanf(“%d %d”, &a,
&b);
}
switch(ch)
{
case
1: c = a+b ;
printf(“ \n Addition: %d”,
c);
break;
case 2:
c=a-b;
printf(“\n Subtraction: %d”, c);
break;
case 3: c =
a* b ;
printf(“\n Multiplication: %d”, c);
break;
case 4: c = a / b;
printf(“\n Division: %d”, c);
break;
case 5: c = a % b;
printf(“ \n Remainder: %d”, c);
break;
case 6: if (a > b)
printf(“\n \t %d
is larger than %d”, a, b);
else if (b > a)
printf(“ \n
\t %d is larger than %d ”, b, a);
else
printf(“\n \t %d and %d are same”,
a, b);
break;
case 7:
printf( “ \ n Terminated by choice”);
exit( );
break;
default: printf(“ \ n invalid choice”);
}
getch ( );
}
Output:
= = = = = = = = =
MENU
= = = = = = = = =
[1] ADDITION
[2] SUBTRACTION
[3] MULTIPLICATION
[4] DIVISION
[5] REMAINDER
[6] LARGER OUT OF TWO
[7] EXIT
= = = = = = = = = = = = = =
=
Enter your choice: 6
Enter two numbers: 8 9
9 is larger than 8
(II)
Loop Control Statements:
Loop: A
loop is defined as a block of statements which are repeatedly executed for
certain number of times.
1)
The “for” loop:
The
for loop statement comprises of 3 actions.
The 3 actions are
“initialize
expression”,
“Test
Condition expression” and
“updation expression” ”
The
expressions are separated by Semi-Colons (;).
The loop variable should be assigned with a starting and final
value. Each time the updated value is
checked by the loop itself. Increment /
Decrement is the numerical value added or subtracted to the variable in each
round of the loop.
Syntax:
for(initialize expression; test condition;
updation )
{
Statement-1;
Statement-2;
}
(i) The initialization sets a loop to an
initial value. This statement is executed only
once.
(ii) The test condition is a relational
expression that determines the number of iterations
desired or it determines when to exit
from the loop. The for loop continues
to execute as long as conditional test is satisfied. When the condition becomes false the control
of the program exits from the body of for loop and executes next statements
after the body of the loop.
(iii) The updation(increment or decrement
operations) decides how to make changes in
the loop.
The body of the loop may contain either a
single statement or multiple statements.
- for loop can be specified by different ways as shown
Syntax Output
Remarks
(i)
for (; ; ) Infinite to loop No arguments
(ii)
for (a=0; a< =20;) Infinite
loop “a‟ is neither increased nor decreased.
(iii)
for (a=0; a<=10; a++) Displays
value “a‟ is increased from 0 to
10
printf(“%d”,
a) from 1 to 10 curly braces are not
necessary default scope of for loop
is one
statement after loop.
(iv)
for (a=10; a>=0; a--) Displays
value „a‟ is decreased from 10 to
0.
printf(„%d”,a); from 10 to 0
Program to Print the first five numbers starting from
one together with their squares.
#include<stdio.h>
#include<conio.h>
main(
)
{
int
i;
clrscr( ) ;
for(i = 1; i <=5; i++)
printf(“\n Number: %d its Square:
%d”, i, i*i);
getch( );
}
Output
:
Number: 1 its Square: 1
Number: 2 its Square: 4
Number: 3 its Square: 9
Number: 4 its Square: 16
Number: 5 its Square: 25
Program
to display from 1 to 15 using for loop and i=i+1.
#
include<stdio.h>
#
include<conio.h>
main( )
{
int i;
clrscr( );
printf(“\n The Numbers of 1 to 15
are:”);
for(i=1; i < =15; i=i+1)
printf(“\n%d ”, i);
getch( );
}
Output :
The Numbers of 1 to 15 are:
1 2
3 4 5
6 7 8
9 10 11
12 13 14
15
(1.1)
Nested “for” loop:
We can also use loop within loops. i.e. one for statement within another for
statement is allowed in C. (or „C‟ allows multiple for loops in the nested
forms). In nested for loops one or more
for statements are included in the body of the loop. * ANSI C allows up to 15 levels of nesting.
Some compilers permit even more. Two
loops can be nested as follows.
Syntax:
for( initialize ; test condition ; updation)
/* outer loop */
{
for(initialize ; test condition ; updation) /* inner loop */
{
Body of loop;
}
}
The outer loop controls the rows while the
inner loop controls the columns.
for(row
=1; row<=rowmax ; ++ row)
{
for (column =1;column<=colmax; ++
column)
{
y = row * column;
printf(“%4d”, y);
}
printf( “\n”);
}
Program
to perform subtraction of 2 loop variables. Use nested for loops.
#
include<stdio.h>
#
include<conio.h>
void main( )
{
int
a, b, sub;
clrscr( );
for
(a=3; a > =1; a - - )
{
for(b=1;b<=2;b++)
{
sub = a – b;
printf(“a=%d b=%d
a-b = %d \n”, a,b, sub);
}
}
getch( );
}
Output:
a=3 b =1
a-b =2
a=3 b =2
a-b =1
a=2 b =1
a-b =1
a=2 b =2
a-b =0
a=1 b =1
a-b =0
a=1 b =2
a-b =-1
(III) Unconditional Control Statements
(1)
The “ break ” Statement:
A break statement terminates the execution of
the loop and the control is transferred to the statement immediately following
the loop. i.e., the break statement is
used to terminate loops or to exit from a switch. It can be used within a for, while,
do-while, or switch statement. The
break statement is written simply as break; Example:
switch (choice = =
toupper(getchar( ))
{
case
„R‟: printf(“Red”);
break;
case
„W‟: printf(“White”);
break;
case
„B‟: printf(“Blue”);
break;
default: printf(“Error”);
}
Notice that each group of statements ends with a break statement, (in
order) to transfer control out of the switch statement. The last group does not require a break
statement; since control will automatically be transferred out of the switch
statement after the last group has been executed.
(2)
The “ continue “ Statement: The
continue statement is used to bypass the remainder of the current pass through
a loop. The loop does not terminate
when a continue statement is encountered.
Instead, the remaining loop statements are skipped and the computation
proceeds directly to the next pass through the loop. The continue statement can be included
within a while, a do-while, a for statement.
It is simply written as “continue”.
The continue statement tells the compiler “Skip the following Statements
and continue with the next Iteration”.
In „while‟ and „do‟ loops continue causes the control to go directly to
the test – condition and then to continue the iteration process. In the case of „for‟ loop, the updation
section of the loop is executed before test- condition, is evaluated.
(1)
while (Test condition)
{
- - - - - - - -
if ( - - - - - - -)
continue;
--------------------
--------------------
}
(2)
do
{
--------------------
if ( - - - - - - )
continue;
-------------------
-------------------
} while(test – condition);
(3) for(initialization; test
condition; increment)
{
- - - - - - - - - -
if( - - - - - - -)
continue;
-------------------
-------------------
}
(3) The “ goto” Statement:
C supports the “goto‟ statement to branch
unconditionally from one point to another in the program. Although it may not be essential to use the
“goto” statement in a highly structured language like „C‟, there may be
occasions when the use of goto is necessary.
The goto requires a label in order to identify the place where the
branch is to be made. A label is any
valid variable name and must be followed by a colon( : ). The label is placed immediately before the
statement where the control is to be transferred. The label can be any where in the program
either before or after the goto label statement.
goto
label; label:
------------- Statement;
------------- ------------
------------- ------------
------------- ------------
label:
------------
Statement; goto label;
Forward Jump Backward Jump During running of a program, when a
statement like “goto begin;” is met, the flow of control will jump to the
statement immediately following the label “begin:” this happens
unconditionally. „goto‟ breaks the
normal sequential execution of the program.
If the “label:” is before the statement “goto label;” a loop will be
formed and some statements will be executed repeatedly. Such a jump is known as
a „backward jump‟. If the “label:” is
placed after the “goto label;” some statements will be skipped and the jump is
known as a “forward jump”.
Program
to detect the entered number as to whether it is even or odd. Use goto
statement.
#
include<stdio.h>
#
include<conio.h>
#
include<stdlib.h>
void main( )
{
int
x;
clrscr( );
printf(“Enter a Number:”);
scanf(“%d”, &x);
if(x % 2 = = 0)
goto
even;
else
goto
odd;
even:
printf(“\n %d is Even Number”);
return;
odd:
printf(“ \n %d is Odd Number”);
}
Output:
Enter a Number : 5
5 is Odd Number.
FUNCTIONS
Introduction
:
Functions
are subprograms which are used to compute a value or perform a task. They
cannot be run independently and are always called by the main ( ) function or
by some other function.
There
are two kinds of functions
1.
Library or built–in functions 2. User–designed functions
1.
Library or built-in functions are used to perform standard operations eg: squareroot
of a number sqrt(x), absolute value fabs(x), scanf( ), printf( ), and so on.
These functions are available along with the compiler and are used along with
the required header files such as math.h, stdio. h, string.h and so on at the
beginning of the program. 2. User
defined functions are self–contained blocks of statements which are written by
the user to compute a value or to perform a task. They can be called by the
main() function repeatedly as per the
requirement.
USES
OF FUNCTIONS :
1.
Functions are very much useful when a block of statements has to be
written/executed again and again.
2.
Functions are useful when the program size is too large or complex.Functions
are called to perform each task sequentially from the main program. It is like
a top-down modular programming technique to solve a problem
3.
Functions are also used to reduce the difficulties during debugging a
program
USER
DEFINED FUNCTIONS :
In
C language, functions are declared to compute and return the value of specific
data type to the calling program. Functions can also written to perform a task.
It may return many values indirectly to the calling program and these are
referred to as void functions.
FUNCTION DECLARATION :
The
general form of a function declaration is
type
name (type arg1, type arg2 ……..
type argn)
{
<local
declaration >
--------------------
<
statement block>
--------------------
return
(variable or expression)
}
Where type is the data type of the value return by
the function and arguments expected.
arg1,
arg2…. argn are the arguments which are variables which will receive values
form the calling program, name is the name of function by which the function is
called by the calling program.
There
is a local declaration of variables. These variables are referred as local
variables, are used only inside the function. The statement block consists of a
set of statements and built-in functions which are executed when the function
is called. The result is returned to the calling program through a return
statement that normally appears at the end of a function block. This function
block starts and ends with braces { }.
Function
main() :
1.
main() is the starting function for any C program. Execution commences from the
first statement in the main () function
2.
It returns int value to the environment that called the program. Usually zero
is returned for normal termination of the main(). Non zero is returned to
convey abnormal termination
3.
It uses no parameter. But it may use two specific parameters
4.
Recursive call is allowed for main () function also
5.
Only the function body varies from programmer to programmer main (). Function
heard follows the common syntax by either having no parameter or only two
standard parameters. 6. The program execution ends when the closing brace of
the in main is reached.
FUNCTION
PROTOTYPE :
When a C program is compiled, the compiler
does not check for data type mismatch of actual arguments in the function call
and the formal arguments in the function declaration. To enable the compiler to
check the same, a function prototype declaration is used in the main
program.
Function
prototype is always declared at the beginning of the main() program.
ACTUAL
AND FORMAL ARGUMENTS
Passing
of values between the main program and the function takes place through
arguments.
The
arguments listed in the function calling statements are referred to as actual
arguments. These actual values are passed to a function to compute a value or
to perform a task.
The
arguments used tin the function declaration are referred as formal arguments.
They are simply formal variables that accept or receive the values supplied by
the calling function.
Note:
The number of actual and formal arguments and their data types should
match.
The
function call sends two integer values 10 and 5 to the function
int
mul(int x, int y) which are assigned to
x and y respectively.
The function computers the product x and y
assigns the result to the local variable p, and then returns the value 25 to
the main() where it is assigned to y again..
Rules
to call a function :
The following rules are used to call a
function is a program:
1.
A function has a statement block which is called by the main( ) or any other
function.
2. When the data type in a function
declaration is omitted the function will return a value of the type integer.
3. The data type of the formal argument may be
declared in the next line which follows the function declaration
statement.
Formal
Parameter List :
The parameter list declares the variables that
will receive the data sent by the calling program.
They serve as input data to the function to
carry out the specified task. Since they represent actual input values, they
are often referred to as formal parameters.
FUNCTION
CALLS:
A function can be called by simply using the
function name followed by a list of actual parameters (or arguments)
main()
{
int y ;
y = mul (10,5); / * function call * /
printf (“‟%d \n”,y) ;
}
int
mul(int x,int y)
{
int
p ; / * local variables x=10, y=5 * /
p=
x * y ;
return(p);
}
FUNCTIONS
ACCEPTING MORE THAN ONE PARAMETER:
A function can accept more than one parameter.
The parameters are separated by commas. For example, consider the following
program having a function maxfunc() that accepts three parameters and computes
their maximum.
#include
<stdio.h >
int
maxfunc(int i, int j, int k)
{
int
max ;
if
(i> = j && i> = k)
max = i ;
else
if (j> = k)
max
= j;
return
max;
}
void
main ( )
{
int
m, a,b,c;
printf
(“ input 3 numbers:”) ;
scanf(“%d%d
%d “, & a ,&b, & c);
m=
maxjunc (a,b,c);
printf(“
The maximum is%d \n”,m);
}
Run:
Input 3 numbers: 4
6 5
The maximum is
6
The
main function calls the function maxfunc().
Three integer variables passed to it are separated by commas. The return
value is assigned to m and is displayed. Since maxfunc() comes before the
function main separate function and function definition are unnecessary.
The variables m,a,b and c are declared in
main. They can be used only in the function main. An attempt to use them in
maxfunc() causes a compile time error. Similarly, the variables max,i,j and k
(i,j,k being the parameters which the function accepts) belong to the
maxfunc(). These variables cannot be accessed in main. The region of the
program where an identifier can be accessed is called the “Scope of the
identifier”. Thus the scope of „a‟ is the function main, while the scope of i
is the function maxfunc().
The variables with the same name can exist in
both main and maxfunc().
CONCEPTS
ASSOCIATED WITH FUNCTIONS:
1.
Function declaration or function prototype
2.
Function definition (function declaration and function body)
3.
Combination declaration and function definition
4.
Passing arguments
5.
Return statement
6.
Function call
Parts of function
:
A function declaration can appear outside all
the other functions. In this case all functions know about the other function
declarations and can call this function. Functions can also be declared within
other functions. In this case only the function within which the declaration is
present will know about it.
Ex:
void main()
{
int i;
double cube (double);
}
Parts of a function
void
main( )
{
void func1(); function declaration
…………….
…………….
func1();
function call
…………….
…………….
}
void
func1()
{
……………
Function body function
definition
……………
}
Function
declaration:
A
function declaration provides the following information to the compiler
- The name of the function
- The Type of the value returned (optioned,
default is integer)
- The number and the type of arguments that
must be supplied in a call to the function.
When a function call is encountered, the
compiler checks the function call with its declaration. So that correct
argument types are used. A function declaration has the following syntax:
return type
function name (type, type ….. type);
return
type specifies the data type of the
value in the return statement. A function can return any data type , if there
is no return value, the keyword void is placed before the function name. The
function declaration terminates with a semicolon.
Ex:
double cube(double);
The above declaration informs the complier
that the function cube has argument of type double. The function cube returns
double value. The complier knows how
many bytes to retrieve and how to interpret the value returned by the in
function declarations are also called prototypes, since they provide a model or
blue print of the function.
Function
definition:
The function definition is similar to the
function declaration but does not have the semicolon. The first line of the
function definition is called a function declarator. This is followed by the
function body. It is composed of the statements that make up the function,
delimited by braces. The declarator and declaration must use the same function
name, number of arguments, arguments types, and the return type. No function
definition is allowed with in a function definition.
Ex:
void main(void)
{
int
i,j; /* variable declaration */
long fact (unsigned int num); /* function
declaration or in prototype */
}
The
definition of the function cube is given below :
double
cube (double dnum)
{
return
dnum * d num * dnum;
}
A function can contain any number of
statements.The statements are enclosed with in curly braces { and }. The
function definition may include declarations of variables and declaration of
other functions. Note that the return statement need not enclose the return
value with in parenthesis.
Elimination of function
declaration:
The programmer can place function declarations
anywhere in the program. If the functions are defined before they are called,
then the declarations are unnecessary.
Ex:
#include <stdio.h>
int max (inta, int b)
{
return a>b ? a: b;
}
void main ()
{
int
i,j, imax;
printf( “ enter two numbers:”);
scanf(“%d%d;
& ;, &;);
i max =max (i,j);
printf(“ the maximum of %d and %d is %d”, i,j,
i max);
}
Function return
type:
Functions in C may or may not return values.
If a function does not return a value the return type in the function
definition and declaration is specified as void. Otherwise, the return type is
specified as a valid data type.
main()
{
unsigned
sq = squareint (32); /*function call *)
printf(“
The square of 32 is ./.n\n”, sq), /*
control returns here */
}
The function squareint is called and the
return value is assigned to the variable sq. the control is returned to the
printf statement after the statements with in the function definition of
squareint are executed.
FUNCTION PARAMETERS:
Function parameters are the means of
communication between the calling and the the called function. They can be
classified into formal parameters and actual parameters. The formal parameters
are the parameters given in the function declaration and function definition.
The actual parameters, often known as arguments, are specified in the function
call.
Ex:
int sum(int a, int b) /* This and the following body (in curly
braces c { constitutes the function
definition */
return
a+b;
}
void
main(void)
{
int
x,y,z;
z
= sum (x,y);
}
Definition
of function that does not return anything is as follows:
void
functionname(parameter list)
{
Statement/Statements
;
return; /* optional since it is at the end of the in
anyway and the in has no ref value */
}
The
definition of a function that returns a value of type . Type name has the
following syntax:
Typename
Functionname (parameterlist)
{
Statement/Statements
;
return
value; /* return keyword must be used.
And it must be followed by a value that matches the return type specified by
typename */
}
Even
in case of functions having return values multiple return statements can exist.
Parameter
list
is the of arguments separated by commas.
Function
Call :
A
function call is specified by the function name followed by the values of the
parameters enclosed with in parenthesis, terminated by a semi colon (;).
Ex:
unsigned squareint(unsigned x)
{
return
x * x;
}
There
are two ways in which we can pass arguments to the function:
Call
by value
Call
by reference.
Call
by value :
In
this type value of actual arguments are passed to the formal arguments and the
operation is done on the formal arguments. Any changes made in the formal
arguments does not effect the actual arguments because formal arguments are
photocopy of actual arguments. Hence when the function is called by the call by
value method, it does not effect the actual contents of the actual arguments.
Changes made in the formal arguments are local to the block of called function.
Once control returns back to the calling function the changes made vanish.
Ex:
program to send values by call by value
main(
)
{
int
x,y, change (int, int);
clrscr();
printf(“
\n enter values of x & y : “);
scanf(“%d
%d “, & x, & y);
change(x,y)
;
printf(“\n
In main ( ) x=% d y = % d”, x,y);
return
0;
}
change(int
a, int b)
{
k
= a; o/p: enter values of x & y :
5 4
a=b;
In change (1) x=4 y=5
b=k;
}
In the above program, the variables
a and b defined in function definition are known as formal parameters or dummy
parameters or place holders. The variables x and y are actual parameters, they
specify the values that are passed to the function change x and y are arguments
in the function change x and y arguments in the function call.
The
number of arguments in the function call and the function declarator must be
the same.
The
date type of each of the arguments in the function call should be the same as
the corresponding parameter in the function declaration statement.
The
names of the arguments in the function call and the names of parameters in the
function definition can be same or different.
Recursion :
A function calling itself again and
again to compute a value is known as recursive function or recursion function
or recursion. Normally a function is called by the main program or by some
other function but in recursion the same function is called by itself
repeatedly.
Use
of recursion function :
1.
Recursion functions are written less number of statements. 2. Recursion is
effective where terms are generated successively to compute value. 3. Recursion
is useful for branching process. Recursion helps to create short code that
would otherwise be impossible .
Program:
Write a recursive fuction to find the factorized of a given integer. Use it to
find ncr = n1 r1 (n-r);
Array:
An array is collection of same data type
elements in a single entity.
Or
An array is collection of homogeneous
elements in a single variable. It
allocates sequential memory locations.
Individual values are called as elements. Types of Arrays:
We can use arrays to represent not only simple
lists of values but also tables of data
in two or three or more dimensions.
One
– dimensional arrays
Two
– dimensional arrays
Multidimensional
arrays
ONE – DIMENSIONAL
ARRAY:
A list of items can be given one variable name
using only one subscript and such a variable is called a single – subscripted
variable or a one – dimensional array.
Declaration of One-Dimensional Arrays
: Like any other variables, arrays must
be declared before they are used. The general form of array declaration is
Syntax:
<datatype> <array_name>[sizeofarray]; The datatype specifies the type of element
that will be contained in the array, such as int, float, or char. The size indicates the maximum number of
elements that can be stored inside the array.
The size of array should be a constant value. Examples:
float height[50];
Declares the height to be an array containing 50 real elements.
MULTI – DIMENSIONAL
ARRAY:
A
list of items can be given one variable name using more than two subscripts and
such a variable is called Multi – dimensional array.
Three
Dimensional Array:
A list of items can be given one variable name
using three subscripts and such a variable is called Three – dimensional
array.
Declaration
of Three-Dimensional Arrays :
Syntax:
<datatype> <array_name>[sizeofno.oftwoDimArray]
[sizeofrow] [sizeofcolom];
The
datatype specifies the type of elements that will be contained in the array,
such as int, float, or char. Initializing Three- Dimensional Arrays:
Like the one-dimensional arrays,
three-dimensional arrays may be initialized by following their declaration with
a list of initial values enclosed in braces.
int table[2][2][3] = {0,0,0,1,1,1,6,6,6,7,7,7}; This initializes the elements of first two
dimensional(matrix) first row to zero‟s and the second row to one‟s and second
matrix elements are first row to six‟s and the second row to seven‟s. This initialization is done row by row.
STRING MANIPULATIONS IN
C
In
C language, an array of characters is known as a string.
STRING HANDLING
FUNCTIONS IN C:
There are
four important string Handling functions in C language.
(i)
strlen( ) function
(ii)
strcpy( ) function
(iii)
strcat( ) function
(iv)
strcmp( ) function
(I)
strlen( ) Function: strlen(
) function is used to find the length of a character string. Ex:
int n;
char
st[20] = “Bangalore”;
n
= strlen(st);
This
will return the length of the string 9 which is assigned to an integer variable
n.
(II) strcpy(
) Function: strcpy( ) function is used to copy from one string to
another string. Ex :
char city[15];
strcpy(city,
“BANGALORE”)
;
This
will assign the string “BANGALORE”
to the character variable city.
(III)
strcat( ) Function: strcat(
) function is used to join character, Strings. When two character
strings are joined, it is referred as
concatenation of strings.
Ex:
char
city[20] = “BANGALORE”;
char
pin[8] = “-560001”;
strcat(city,pin);
This
will join the two strings and store the result in city as “BANGALORE –
560001”.
(IV)
strcmp( ) Function: strcmp (
) function is used to compare two character strings.
It
returns a 0 when two strings are identical. Otherwise it returns a numerical
value which is the different in ASCII
values of the first mismatching character of the strings being compared.
EG:
char
city[20] = “Madras”;
char
town[20] = “Mangalore”;
strcmp(city,
town);
This
will return an integer value “- 10” which is the difference in the ASCII values
of the first mismatching letters “D” and
“N”
Pointer
A pointer is a
variable that points to or references a memory location in which data is
stored. In the computer, each memory cell has an address that can be used to
access that location so a pointer variable points to a memory location we can
access and change the contents of this memory location via the pointer.
Pointer declaration:
A pointer is a
variable that contains the memory location of another variable in which data is
stored. Using pointer, you start by specifying the type of data stored in the
location. The asterisk helps to tell the compiler that you are creating a
pointer variable. Finally you have to give the name of the variable. The syntax
is as shown below.
type * variable name
The following example illustrate the declaration of pointer variable :
int *ptr;
float *string;
float *string;
Address operator:
Once we declare a
pointer variable then we must point it to something we can do this by assigning
to the pointer the address of the variable you want to point as in the
following example:
ptr=#
The above code
tells that the address where num is stores into the variable ptr. The variable
ptr has the value 21260,if num is stored in memory 21260 address then
The following program illustrate the pointer declaration :
/* A program to
illustrate pointer declaration*/
main(){
int *ptr;
int sum;
sum=45;
ptr=&ptr;
printf (”\n Sum is %d\n”, sum);
printf (”\n The sum pointer is %d”, ptr);
}
Pointer expressions & pointer arithmetic:
In expressions,
like other variables pointer variables can be used. For example if p1 and p2
are properly initialized and declared pointers, then the following statements
are valid.
y=*p1**p2;
sum=sum+*p1;
z= 5* – *p2/p1;
*p2= *p2 + 10;
sum=sum+*p1;
z= 5* – *p2/p1;
*p2= *p2 + 10;
C allows us to
subtract integers to or add integers from pointers as well as to subtract one
pointer from the other. We can also use short hand operators with pointers
p1+=; sum+=*p2; etc., By using relational operators, we can also compare
pointers like the expressions such as p1 >p2 , p1==p2 and p1!=p2 are allowed.
The following program illustrate the pointer expression and pointer
arithmetic :
/*Program to illustrate the pointer expression and pointer
arithmetic*/
#include< stdio.h >
main()
{ int ptr1,ptr2;
int a,b,x,y,z;
a=30;b=6;
ptr1=&a;
ptr2=&b;
x=*ptr1+ *ptr2 6;
y=6*- *ptr1/ *ptr2 +30;
printf(”\nAddress of a +%u”,ptr1);
printf(”\nAddress of b %u”,ptr2);
printf(”\na=%d, b=%d”,a,b);
printf(”\nx=%d,y=%d”,x,y);
ptr1=ptr1 + 70;
ptr2= ptr2;
printf(”\na=%d, b=%d,”a,b);
}
#include< stdio.h >
main()
{ int ptr1,ptr2;
int a,b,x,y,z;
a=30;b=6;
ptr1=&a;
ptr2=&b;
x=*ptr1+ *ptr2 6;
y=6*- *ptr1/ *ptr2 +30;
printf(”\nAddress of a +%u”,ptr1);
printf(”\nAddress of b %u”,ptr2);
printf(”\na=%d, b=%d”,a,b);
printf(”\nx=%d,y=%d”,x,y);
ptr1=ptr1 + 70;
ptr2= ptr2;
printf(”\na=%d, b=%d,”a,b);
}
Pointers and function:
In a function
declaration, the pointer are very much used . Sometimes, only with a pointer a
complex function can be easily represented and success. In a function
definition, the usage of the pointers may be classified into two groups.
1. Call by reference
2. Call by value.
Call by value:
We have seen that
there will be a link established between the formal and actual parameters when
a function is invoked. As soon as temporary storage is created where the value
of actual parameters is stored. The formal parameters picks up its value from
storage area the mechanism of data transfer between formal and actual
parameters allows the actual parameters mechanism of data transfer is referred
as call by value. The corresponding formal parameter always represents a local
variable in the called function. The current value of the corresponding actual
parameter becomes the initial value of formal parameter. In the body of the
actual parameter, the value of formal parameter may be changed. In the body of
the subprogram, the value of formal parameter may be changed by assignment or
input statements. This will not change the value of the actual parameters.
/* Include< stdio.h >
void main(){
int x,y;
x=20;
y=30;
printf(”\n Value of a and b before function call =%d %d”,a,b);
fncn(x,y);
printf(”\n Value of a and b after function call =%d %d”,a,b);
}
fncn(p,q)
int p,q;
{
p=p+p;
q=q+q;
}
Call by Reference:
The address
should be pointers, when we pass address to a function the parameters
receiving. By using pointers, the process of calling a function to pass the
address of the variable is known as call by reference. The function which is
called by reference can change the value of the variable used in the call.
/* example of call by reference*?
/* Include< stdio.h >void main()
{
int x,y;
x=20;
y=30;
printf(”\n Value of a and b before function call =%d %d”,a,b);
fncn(&x,&y); printf(”\n Value of a and b after function call =%d %d”,a,b);
}
fncn(p,q)
int p,q;
{
*p=*p+*p;
*q=*q+*q;
}
Pointer to arrays:
an array is
actually very much similar like pointer. We can declare as int *a is an
address, because a[0] the arrays first element as a[0] and *a is also an
address the form of declaration is also equivalent. The difference is pointer
can appear on the left of the assignment operator and it is a is a variable
that is lvalue. The array name cannot appear as the left side of assignment
operator and is constant.
/* A program to display the contents of array using pointer*/
main()
{
int a[100];
int i,j,n;
printf(”\nEnter the elements of the array\n”);
scanf(%d,&n);
printf(”Enter the array elements”);
for(I=0;I< n;I++)
scanf(%d,&a[I]);
printf(”Array element are”);
for(ptr=a,ptr< (a+n);ptr++)
printf(”Value of a[%d]=%d stored at address %u”,j+=,*ptr,ptr);
}
main()
{
int a[100];
int i,j,n;
printf(”\nEnter the elements of the array\n”);
scanf(%d,&n);
printf(”Enter the array elements”);
for(I=0;I< n;I++)
scanf(%d,&a[I]);
printf(”Array element are”);
for(ptr=a,ptr< (a+n);ptr++)
printf(”Value of a[%d]=%d stored at address %u”,j+=,*ptr,ptr);
}
Pointers and structures :
We know the name
of an array stands for address of its zeros element the same concept applies
for names of arrays of structures. Suppose item is an array variable of the
struct type. Consider the following declaration:
struct products
{
char name[30];
int manufac;
float net;
item[2],*ptr;
{
char name[30];
int manufac;
float net;
item[2],*ptr;
STRUCTURES
What is a
Structure?
- Structure is a method of packing the data of different types.
- When we require using a collection of different data items of different data types in that situation we can use a structure.
- A structure is used as a method of handling a group of related data items of different data types.
A structure is a
collection of variables under a single name. These variables can be of
different types, and each has a name which is used to select it from the
structure. A structure is a convenient way of grouping several pieces of
related information together.
A structure can be
defined as a new named type, thus extending the number of available types. It
can use other structures, arrays or pointers as some of its members, though
this can get complicated unless you are careful.
Defining a Structure
A structure type
is usually defined near to the start of a file using a typedef statement.
typedef defines and names a new type, allowing its use throughout the program.
typedefs usually occur just after the #define and #include statements in a
file.
Here is an example
structure definition.
typedef struct {
char name[64];
char course[128];
int age;
int year;
} student;
This defines a new
type student variables of type student can be declared as follows.
student st_rec;
Notice how similar this is to
declaring an int or float.
The variable name
is st_rec, it has members called name, course, age and year.
Accessing Members of a Structure
Each member of a
structure can be used just like a normal variable, but its name will be a bit
longer. To return to the examples above, member name of structure st_rec will
behave just like a normal array of char, however we refer to it by the name .
st_rec.name
Here the dot is an operator which
selects a member from a structure.
Where we have a
pointer to a structure we could dereference the pointer and then use dot as a
member selector. This method is a little clumsy to type. Since selecting a
member from a structure pointer happens frequently, it has its own operator
-> which acts as follows. Assume that st_ptr is a pointer to a structure of
type student We would refer to the name member as.
st_ptr -> name
/* Example program for using a structure*/
#include< stdio.h >
void main()
{
int id_no;
char name[20];
char address[20];
char combination[3];
int age;
}newstudent;
printf(”Enter the student information”);
printf(”Now Enter the student id_no”);
scanf(“%d”,&newstudent.id_no);
printf(“Enter the name of the student”);
scanf(“%s”,&new student.name);
printf(“Enter the address of the student”);
scanf(“%s”,&new student.address);printf(“Enter the cmbination of the student”);
scanf(“%d”,&new student.combination);printf(Enter the age of the student”);
scanf(“%d”,&new student.age);
printf(“Student information\n”);
printf(“student id_number=%d\n”,newstudent.id_no);
printf(“student name=%s\n”,newstudent.name);
printf(“student Address=%s\n”,newstudent.address);
printf(“students combination=%s\n”,newstudent.combination);
printf(“Age of student=%d\n”,newstudent.age);
}
#include< stdio.h >
void main()
{
int id_no;
char name[20];
char address[20];
char combination[3];
int age;
}newstudent;
printf(”Enter the student information”);
printf(”Now Enter the student id_no”);
scanf(“%d”,&newstudent.id_no);
printf(“Enter the name of the student”);
scanf(“%s”,&new student.name);
printf(“Enter the address of the student”);
scanf(“%s”,&new student.address);printf(“Enter the cmbination of the student”);
scanf(“%d”,&new student.combination);printf(Enter the age of the student”);
scanf(“%d”,&new student.age);
printf(“Student information\n”);
printf(“student id_number=%d\n”,newstudent.id_no);
printf(“student name=%s\n”,newstudent.name);
printf(“student Address=%s\n”,newstudent.address);
printf(“students combination=%s\n”,newstudent.combination);
printf(“Age of student=%d\n”,newstudent.age);
}
Arrays of structure:
It is possible to
define a array of structures for example if we are maintaining information of
all the students in the college and if 100 students are studying in the
college. We need to use an array than single variables. We can define an array
of structures as shown in the following example:
structure information
{
int id_no;
char name[20];
char address[20];
char combination[3];
int age;
}
student[100];
An array of structures can be assigned initial values just as any other array can. Remember that each element is a structure that must be assigned corresponding initial values as illustrated below.
#include< stdio.h >
{
struct info
{
int id_no;
char name[20];
char address[20];
char combination[3];
int age;
}
struct info std[100];
int I,n;
printf(“Enter the number of students”);
scanf(“%d”,&n);
printf(“ Enter Id_no,name address combination age\m”);
for(I=0;I < n;I++)
scanf(“%d%s%s%s%d”,&std[I].id_no,std[I].name,std[I].address,std[I].combination,&std[I].age);
printf(“\n Student information”);
for (I=0;I< n;I++)
printf(“%d%s%s%s%d\n”, ”,std[I].id_no,std[I].name,std[I].address,std[I].combination,std[I].age);
}
structure information
{
int id_no;
char name[20];
char address[20];
char combination[3];
int age;
}
student[100];
An array of structures can be assigned initial values just as any other array can. Remember that each element is a structure that must be assigned corresponding initial values as illustrated below.
#include< stdio.h >
{
struct info
{
int id_no;
char name[20];
char address[20];
char combination[3];
int age;
}
struct info std[100];
int I,n;
printf(“Enter the number of students”);
scanf(“%d”,&n);
printf(“ Enter Id_no,name address combination age\m”);
for(I=0;I < n;I++)
scanf(“%d%s%s%s%d”,&std[I].id_no,std[I].name,std[I].address,std[I].combination,&std[I].age);
printf(“\n Student information”);
for (I=0;I< n;I++)
printf(“%d%s%s%s%d\n”, ”,std[I].id_no,std[I].name,std[I].address,std[I].combination,std[I].age);
}
Structure within a
structure:
A structure may be
defined as a member of another structure. In such structures the declaration of
the embedded structure must appear before the declarations of other structures.
struct date
{
int day;
int month;
int year;
};
struct student
{
int id_no;
char name[20];
char address[20];
char combination[3];
int age;
structure date def;
structure date doa;
}oldstudent, newstudent;
struct date
{
int day;
int month;
int year;
};
struct student
{
int id_no;
char name[20];
char address[20];
char combination[3];
int age;
structure date def;
structure date doa;
}oldstudent, newstudent;
the
sturucture student constains another structure date as its one of its members.
UNIONS
Union:
Unions
like structure contain members whose individual data types may differ from one
another. However the members that compose a union all share the same storage
area within the computers memory where as each member within a structure is
assigned its own unique storage area. Thus unions are used to observe memory.
They are useful for application involving multiple members. Where values need
not be assigned to all the members at any one time. Like structures union can
be declared using the keyword union as follows:
union item
{
int m;
float p;
char c;
}
code;
{
int m;
float p;
char c;
}
code;
this
declares a variable code of type union item. The union contains three members
each with a different data type. However we can use only one of them at a time.
This is because if only one location is allocated for union variable
irrespective of size. The compiler allocates a piece of storage that is large
enough to access a union member we can use the same syntax that we use to
access structure members. That is
code.m
code.p
code.c
code.p
code.c
are all valid member
variables. During accessing we should make sure that we are accessing the
member whose value is currently stored.
For example a statement such as -
For example a statement such as -
code.m=456;
code.p=456.78;
printf(“%d”,code.m);
code.p=456.78;
printf(“%d”,code.m);
Would
prodece erroneous result..
Enum declarations
There
are two kinds of enum type declarations. One kind
creates a named type, as in
enum MyEnumType { ALPHA, BETA, GAMMA };
If
you give an enum type a name, you can use that
type for variables, function arguments and return values, and so on:
enum MyEnumType x; /* legal in both C and C++ */
MyEnumType y; // legal only in C++
The
other kind creates an unnamed type. This is used when you want names for
constants but don't plan to use the type to declare variables, function arguments,
etc. For example, you can write
enum { HOMER, MARGE, BART, LISA, MAGGIE };
Values of enum constants
If
you don't specify values for enum constants, the values start at
zero and increase by one with each move down the list. For example, given
enum MyEnumType { ALPHA, BETA, GAMMA };
ALPHA has a value of 0, BETA has a value
of 1, and GAMMA has a value of 2.
If you want, you may provide explicit values
for enum constants, as in enum FooSize { SMALL = 10, MEDIUM = 100, LARGE = 1000 };
enum MyEnumType { ALPHA, BETA, GAMMA };
Then
the following lines are legal:
int i = BETA; // give i a value of 1
int j = 3 + GAMMA; // give j a value of 5
On the other hand, there is not an
implicit conversion from int to an enum type: MyEnumType x = 2; // should NOT be allowed by compiler
MyEnumType y = 123; // should NOT be allowed by compiler
Note that it doesn't matter
whether the int matches one of the constants of
the enum type; the type conversion is
always illegal.
Typedefs
A typedef in C is a declaration. Its purpose is to create new types from existing types; whereas a variable declaration creates new memory locations. Since a typedef is a declaration, it can be intermingled with variable declarations, although common practice would be to state typedefs first, then variable declarations. A nice programming convention is to capitalize the first letter of a user-defined type to distinguish it from the built-in types, which all have lower-case names. Also, typedefs are usually global declarations.Example: Use a Typedef To Create A Synonym for a Type Name
typedef int Integer; //Integer can now be used in place of int
int a,b,c,d; //4 variables of type int
Integer e,f,g,h; //the same thing
In general, a typedef should never be used to assign a different name to a built-in type name; it just confuses the reader. Usually, a typedef associates a type name with a more complicated type specification, such as an array. A typedef should always be used in situations where the same type definition is used more than once for the same purpose. For example, a vector of 20 elements might represent different aspects of a scientific measurement.Example: Use a Typedef To Create A Synonym for an Array Type
typedef int Vector[20]; //20 integers
Vector a,b;
int a[20], b[20]; //the same thing, but a typedef is preferred
Typedefs for Enumerated Types
Every type has constants. For the "int" type, the constants are 1,2,3,4,5; for "char", 'a','b','c'. When a type has constants that have names, like the colors of the rainbow, that type is called an enumerated type. Use an enumerated type for computer representation of common objects that have names like Colors, Playing Cards, Animals, Birds, Fish etc. Enumerated type constants (since they are names) make a program easy to read and understand.We know that all names in a computer usually are associated with a number. Thus, all of the names (RED, BLUE, GREEN) for an enumerated type are "encoded" with numbers. In eC, if you define an enumerated type, like Color, you cannot add it to an integer; it is not type compatible. In standard C++, anything goes. Also, in eC an enumerated type must always be declared in a typedef before use (in fact, all new types must be declared before use).
Example: Use a Typedef To Create An Enumerated Type
typedef enum {RED, BLUE, GREEN} Color;
Color a,b;
a
= RED;
a = RED+BLUE; //NOT ALLOWED in eC
if ((a == BLUE) || (a==b)) cout<<"great";
Notice that an enumerated type is a code that associates symbols and numbers. The char type can be thought of as an enumeration of character codes. The default code for an enumerated type assigns the first name to the value 0 (RED), second name 1 (BLUE), third 2 (GREEN) etc. The user can, however, override any, or all, of the default codes by specifying alternative values.
FILE MANAGEMENT
What is a File?
Abstractly, a file is a collection of bytes stored on a
secondary storage device, which is generally a disk of some kind. The
collection of bytes may be interpreted, for example, as characters, words,
lines, paragraphs and pages from a textual document; fields and records
belonging to a database; or pixels from a graphical image. The meaning attached
to a particular file is determined entirely by the data
structures and operations used by a program to process the file.
It is conceivable (and it sometimes happens) that a graphics file
will be read and displayed by a program designed to process textual data. The
result is that no meaningful output occurs (probably) and this is to be
expected. A file is simply a machine decipherable storage
media where programs and data are stored for machine usage.
Essentially there are two kinds of files that programmers
deal with text files and binary files. These two classes of files will be
discussed in the following sections.
ASCII Text files
A text file can be a stream of characters that a
computer can process sequentially. It is not only processed sequentially but
only in forward direction. For this reason a text file
is usually opened for only one kind of operation (reading, writing, or
appending) at any given time.
Similarly, since text files only process characters, they
can only read or write data one character at a time. (In C Programming
Language, Functions are provided that deal with lines of text, but these still
essentially process data one character at a time.) A text stream in C is a
special kind of file. Depending on the requirements of the
operating system, newline characters may be converted to or from
carriage-return/linefeed combinations depending on whether data is being written
to, or read from, the file. Other character conversions may also
occur to satisfy the storage requirements of the operating system. These
translations occur transparently and they occur because the programmer has
signalled the intention to process a text file.
Binary files
A binary file is no different to a text file.
It is a collection of bytes. In C Programming Language a byte and a character
are equivalent. Hence a binary file is also referred to as a character stream,
but there are two essential differences.
1.
No special processing of the data occurs
and each byte of data is transferred to or from the disk unprocessed.
2.
C Programming Language places no constructs
on the file,
and it may be read from, or written to, in any manner chosen by the programmer.
Binary files can be either processed sequentially or,
depending on the needs of the application, they can be processed using random
access techniques. In C Programming Language, processing a file
using random access techniques involves moving the current file
position to an appropriate place in the file
before reading or writing data. This indicates a second characteristic of
binary files
– they a generally processed using read and write operations simultaneously.
– they a generally processed using read and write operations simultaneously.
For example, a database file
will be created and processed as a binary file.
A record update operation will involve locating the appropriate record, reading
the record into memory, modifying it in some way, and finally writing the
record back to disk at its appropriate location in the file.
These kinds of operations are common to many binary files, but are rarely found
in applications that process text files.
Creating a file and output some data
In order to create files we have to learn about File
I/O i.e. how to write data into a file and how to read data from a file.
We will start this section with an example of writing data to a file.
We begin as before with the include statement for stdio.h, then define some
variables for use in the example including a rather strange looking new type.
/* Program to create a file and write some data the file */
#include <stdio.h>
#include <stdio.h>
main( )
{
FILE *fp;
char stuff[25];
int index;
fp = fopen("TENLINES.TXT","w"); /* open for writing */
strcpy(stuff,"This is an example line.");
for (index = 1; index <= 10; index++)
fprintf(fp,"%s Line number %d\n", stuff, index);
fclose(fp); /* close the file before ending program */
}
The type FILE is used for a file
variable and is defined in the stdio.h file.
It is used to define a file pointer for use in file
operations. Before we can write to a file, we must open it. What this really means
is that we must tell the system that we want to write to a file
and what the file name is. We do this with the fopen()
function illustrated in the first line of the program. The file
pointer, fp in our case, points to the file
and two arguments are required in the parentheses, the file
name first, followed by the file type.
The file name is any valid DOS file
name, and can be expressed in upper or lower case letters, or even mixed if you
so desire. It is enclosed in double quotes. For this example we have chosen the
name TENLINES.TXT. This file should not exist on your disk at this
time. If you have a file with this name, you should change its name
or move it because when we execute this program, its contents will be erased.
If you don’t have a file by this name, that is good because we will
create one and put some data into it. You are permitted to include a directory
with the file name. The directory must, of course, be a
valid directory otherwise an error will occur. Also, because of the way C
handles literal strings, the directory separation character ‘\’ must be
written twice. For example, if the file is to be stored in the \PROJECTS sub
directory then the file name should be entered as
“\\PROJECTS\\TENLINES.TXT”. The second parameter is the file
attribute and can be any of three letters, r, w, or a, and must be lower case.
Reading (r)
When an r is used, the file
is opened for reading, a w is used to indicate a file
to be used for writing, and an indicates
that you desire to append additional data to the data already in an existing file.
Most C compilers have other file attributes available; check your Reference
Manual for details. Using the r indicates that the file
is assumed to be a text file. Opening a file
for reading requires that the file already exist. If it does not exist, the file
pointer will be set to NULL and can be checked by the program.
Here is a small program that reads a file
and display its contents on screen. /* Program to display the contents of a file on screen */
#include <stdio.h>
void main()
{
FILE *fopen(), *fp;
int c;
fp = fopen("prog.c","r");
c = getc(fp) ;
while (c!= EOF)
{
putchar(c);
c = getc(fp);
}
fclose(fp);
}
Writing (w)
When a file is opened for writing, it will be created
if it does not already exist and it will be reset if it does, resulting in the
deletion of any data already there. Using the w indicates that the file
is assumed to be a text file.
#include <stdio.h>
int main()
{
FILE *fp;
file = fopen("file.txt","w");
/*Create a file and add text*/
fprintf(fp,"%s","This is just an example :)"); /*writes data to the file*/
fclose(fp); /*done!*/
return 0;
}
Appending (a):
When a file is opened for appending, it will be
created if it does not already exist and it will be initially empty. If it does
exist, the data input point will be positioned at the end of the present data
so that any new data will be added to any data that already exists in the file.
Using the a indicates that the file is assumed to be a text file.
Here is a program that will add text to a file
which already exists and there is some text in the file.
#include <stdio.h>
int main()
{
FILE *fp
file = fopen("file.txt","a");
fprintf(fp,"%s","This is just an example :)"); /*append some text*/
fclose(fp);
return 0;
}
Outputting to the file
The job of actually outputting to the file
is nearly identical to the outputting we have already done to the standard
output device. The only real differences are the new function names and the
addition of the file pointer as one of the function arguments.
In the example program, fprintf replaces our familiar printf function name, and
the file
pointer defined earlier is the first argument within the parentheses. The
remainder of the statement looks like, and in fact is identical to, the printf
statement.
Closing a file
To close a file you simply use the function fclose with
the file
pointer in the parentheses. Actually, in this simple program, it is not
necessary to close the file because the system will close all open
files before returning to DOS, but it is good programming practice for you to
close all files in spite of the fact that they will be closed automatically,
because that would act as a reminder to you of what files are open at the end
of each program.
You can open a file for writing, close it, and reopen it for
reading, then close it, and open it again for appending, etc. Each time you
open it, you could use the same file pointer, or you could use a different one.
The file
pointer is simply a tool that you use to point to a file
and you decide what file it will point to. Compile and run this
program. When you run it, you will not get any output to the monitor because it
doesn’t generate any. After running it, look at your directory for a file
named TENLINES.TXT and type it; that is where your output will be. Compare the
output with that specified in the program; they should agree! Do not erase the file
named TENLINES.TXT yet; we will use it in
some of the other examples in this section.
some of the other examples in this section.
Reading from a text file
Now for our first program that reads from a file.
This program begins with the familiar include, some data definitions, and the file
opening statement which should require no explanation except for the fact that
an r is used here because we want to read it.
#include <stdio.h>
main( )
{
FILE *fp;
char c;
funny = fopen("TENLINES.TXT", "r");
if (fp == NULL)
printf("File doesn't exist\n");
else {
do {
c = getc(fp); /* get one character from the file
*/
putchar(c); /* display it on the monitor
*/
} while (c != EOF); /* repeat until EOF (end of file)
*/
}
fclose(fp);
}
In this program we check to see that the file
exists, and if it does, we execute the main body of the program. If it doesn’t,
we print a message and quit. If the file does not exist, the system will set the
pointer equal to NULL which we can test. The main body of the program is one do
while loop in which a single character is read from the file
and output to the monitor until an EOF (end of file)
is detected from the input file. The file
is then closed and the program is terminated. At this point, we have the
potential for one of the most common and most perplexing problems of
programming in C. The variable returned from the getc function is a character,
so we can use a char variable for this purpose. There is a problem that could
develop here if we happened to use an unsigned char however, because C usually
returns a minus one for an EOF - which an unsigned char type variable is not
capable of containing. An unsigned char type variable can only have the values of zero to 255, so it will return a 255 for a minus one in C. This is a very frustrating problem to try to find. The program can never find the EOF and will therefore never terminate the loop. This is easy to prevent: always have a char or int type variable for use in returning an EOF. There is another problem with this program but we will worry about it when we get to the next program and solve it with the one following that.
capable of containing. An unsigned char type variable can only have the values of zero to 255, so it will return a 255 for a minus one in C. This is a very frustrating problem to try to find. The program can never find the EOF and will therefore never terminate the loop. This is easy to prevent: always have a char or int type variable for use in returning an EOF. There is another problem with this program but we will worry about it when we get to the next program and solve it with the one following that.
After you compile and run this program and are satisfied
with the results, it would be a good exercise to change the name of
TENLINES.TXT and run the program again to see that the NULL test actually works
as stated. Be sure to change the name back because we are still not finished
with TENLINES.TXT.
UNIT 11
C - PREPROCESSOR
Overview
The C preprocessor, often known as cpp, is a macro processor that is used automatically by the C compiler to transform your program before compilation. It is called a macro processor because it allows you to define macros, which are brief abbreviations for longer constructs.The C preprocessor is intended to be used only with C, C++, and Objective-C source code. In the past, it has been abused as a general text processor. It will choke on input which does not obey C's lexical rules. For example, apostrophes will be interpreted as the beginning of character constants, and cause errors. Also, you cannot rely on it preserving characteristics of the input which are not significant to C-family languages. If a Makefile is preprocessed, all the hard tabs will be removed, and the Makefile will not work.
Having said that, you can often get away with using cpp on things which are not C. Other Algol-ish programming languages are often safe (Pascal, Ada, etc.) So is assembly, with caution. -traditional-cpp mode preserves more white space, and is otherwise more permissive. Many of the problems can be avoided by writing C or C++ style comments instead of native language comments, and keeping macros simple
Include Syntax
Both user and system header files are included using the preprocessing directive `#include'. It has two variants:#include <file>
This variant is used for system
header files. It searches for a file named file in a standard list
of system directories. You can prepend directories to this list with the -I option (see Invocation).
#include "file"
This variant is used for header
files of your own program. It searches for a file named file first
in the directory containing the current file, then in the quote directories and
then the same directories used for
<file>. You can prepend directories to the list of quote
directories with the -iquote option.
The
argument of `#include', whether delimited with quote
marks or angle brackets, behaves like a string constant in that comments are
not recognized, and macro names are not expanded. Thus,
#include <x/*y> specifies inclusion of a system header
file named x/*y.
However,
if backslashes occur within file, they are considered ordinary text
characters, not escape characters. None of the character escape sequences
appropriate to string constants in C are processed. Thus,
#include "x\n\\y" specifies a filename containing three
backslashes. (Some systems interpret `\' as a pathname
separator. All of these also interpret `/' the same
way. It is most portable to use only `/'.)
It is
an error if there is anything (other than comments) on the line after the file
name.
Object-like Macros
An object-like macro is a
simple identifier which will be replaced by a code fragment. It is called
object-like because it looks like a data object in code that uses it. They are
most commonly used to give symbolic names to numeric constants.
You create macros with the `#define' directive. `#define' is
followed by the name of the macro and then the token sequence it should be an
abbreviation for, which is variously referred to as the macro's body,
expansion or replacement list. For example,
#define BUFFER_SIZE 1024
defines a macro named
BUFFER_SIZE as an abbreviation for the token 1024. If somewhere after this `#define'
directive there comes a C statement of the form . foo = (char *) malloc (BUFFER_SIZE);
then the C preprocessor will recognize and expand the macro
BUFFER_SIZE. The C compiler will see the same tokens
as it would if you had written . foo = (char *) malloc (1024);
By
convention, macro names are written in uppercase. Programs are easier to read
when it is possible to tell at a glance which names are macros.
The
macro's body ends at the end of the `#define' line. You
may continue the definition onto multiple lines, if necessary, using
backslash-newline. When the macro is expanded, however, it will all come out on
one line. For example,
#define NUMBERS 1, \
2, \
3
int x[] = { NUMBERS };
==> int x[] = { 1, 2, 3 };
The most common visible consequence of this is surprising line numbers in
error messages.
There
is no restriction on what can go in a macro body provided it decomposes into
valid preprocessing tokens. Parentheses need not balance, and the body need not
resemble valid C code. (If it does not, you may get error messages from the C
compiler when you use the macro.)
The C
preprocessor scans your program sequentially. Macro definitions take effect at
the place you write them. Therefore, the following input to the C preprocessor
foo = X;
#define X 4
bar = X;
produces
foo = X;
bar = 4;
When
the preprocessor expands a macro name, the macro's expansion replaces the macro
invocation, then the expansion is examined for more macros to expand. For
example,
#define TABLESIZE BUFSIZE
#define BUFSIZE 1024
TABLESIZE
==> BUFSIZE
==> 1024
TABLESIZE is expanded first to produce BUFSIZE, then that macro is expanded to produce
the final result, 1024.
Notice
that
BUFSIZE was not defined when TABLESIZE was defined. The `#define'
for TABLESIZE uses exactly the expansion you specify—in
this case, BUFSIZE—and does not check to see whether it too
contains macro names. Only when you use TABLESIZE is the result of its expansion scanned for more
macro names.
This
makes a difference if you change the definition of
BUFSIZE at some point in the source file. TABLESIZE, defined as shown, will always expand
using the definition of BUFSIZE that is currently in effect: #define BUFSIZE 1020
#define TABLESIZE BUFSIZE
#undef BUFSIZE
#define BUFSIZE 37
Conditional Syntax
A conditional in the C preprocessor begins with a conditional directive: `#if', `#ifdef' or `#ifndef'.Ifdef
#ifdef MACRO
controlled text
#endif /* MACRO */
This block is called a conditional
group. controlled text will be included in the output of the
preprocessor if and only if MACRO is defined. We say that the
conditional succeeds if MACRO is defined, fails
if it is not.
The controlled
text inside of a conditional can include preprocessing directives. They
are executed only if the conditional succeeds. You can nest conditional groups
inside other conditional groups, but they must be completely nested. In other
words, `#endif' always matches the nearest `#ifdef' (or `#ifndef', or `#if'). Also, you cannot start a conditional group in one file
and end it in another.
Even
if a conditional fails, the controlled text inside it is still run
through initial transformations and tokenization. Therefore, it must all be
lexically valid C. Normally the only way this matters is that all comments and
string literals inside a failing conditional group must still be properly
ended.
The
comment following the `#endif' is not required, but it
is a good practice if there is a lot of controlled text, because it
helps people match the `#endif' to the corresponding `#ifdef'. Older programs sometimes put MACRO
directly after the `#endif' without enclosing it in a
comment. This is invalid code according to the C standard. CPP accepts it with
a warning. It never affects which `#ifndef' the `#endif' matches.
Sometimes you wish to use some code if a
macro is not defined. You can do this by writing `#ifndef'
instead of `#ifdef'. One common use of `#ifndef' is to include code only the first time a header file
is included. See Once-Only Headers.
If
The `#if' directive allows you to test the value of an arithmetic expression, rather than the mere existence of one macro. Its syntax is #if expression
controlled text
#endif /* expression */
expression is a C expression of integer type,
subject to stringent restrictions. It may contain - Integer constants.
- Character constants, which are interpreted as they would be in normal code.
- Arithmetic operators for addition, subtraction, multiplication,
division, bitwise operations, shifts, comparisons, and logical operations
(
&&and||). The latter two obey the usual short-circuiting rules of standard C. - Macros. All macros in the expression are expanded before actual computation of the expression's value begins.
- Uses of the
definedoperator, which lets you check whether macros are defined in the middle of an `#if'. - Identifiers that are not macros, which are all considered to be the
number zero. This allows you to write
#if MACROinstead of#ifdef MACRO, if you know that MACRO, when defined, will always have a nonzero value. Function-like macros used without their function call parentheses are also treated as zero.
Defined
The special operatordefined is used in `#if' and `#elif' expressions to test whether a certain name is defined
as a macro. defined name and defined (name) are both expressions whose value is 1 if name
is defined as a macro at the current point in the program, and 0 otherwise.
Thus, #if defined MACRO is precisely equivalent to #ifdef MACRO. defined is useful when you wish to test more than
one macro for existence at once. For example, #if defined (__vax__) || defined (__ns16000__)
would succeed if
either of the names
Conditionals written like this: __vax__ or __ns16000__ is defined as a macro. #if defined BUFSIZE && BUFSIZE >= 1024
can generally be
simplified to just
If the #if BUFSIZE >= 1024, since if BUFSIZE is not defined, it will be interpreted as having
the value zero. defined operator appears as a result of a macro
expansion, the C standard says the behavior is undefined. GNU cpp treats it as
a genuine defined operator and evaluates it normally. It
will warn wherever your code uses this feature if you use the command-line
option -pedantic, since other compilers may handle it differently.
Else
The `#else' directive can be added to a conditional to provide alternative text to be used if the condition fails. This is what it looks like: #if expression
text-if-true
#else /* Not expression */
text-if-false
#endif /* Not expression */
If expression
is nonzero, the text-if-true is included and the text-if-false
is skipped. If expression is zero, the opposite happens.
You can use `#else'
with `#ifdef' and `#ifndef',
too. Elif
One common case of nested conditionals is used to check for more than two possible alternatives. For example, you might have #if X == 1
...
#else /* X != 1 */
#if X == 2
...
#else /* X != 2 */
...
#endif /* X != 2 */
#endif /* X != 1 */
Another conditional directive, `#elif', allows this to be abbreviated as follows: #if X == 1
...
#elif X == 2
...
#else /* X != 2 and X != 1*/
...
#endif /* X != 2 and X != 1*/
`#elif' stands for “else if”. Like `#else',
it goes in the middle of a conditional group and subdivides it; it does not
require a matching `#endif' of its own. Like `#if', the `#elif' directive includes
an expression to be tested. The text following the `#elif'
is processed only if the original `#if'-condition failed
and the `#elif' condition succeeds.
More
than one `#elif' can go in the same conditional group.
Then the text after each `#elif' is processed only if
the `#elif' condition succeeds after the original `#if' and all previous `#elif'
directives within it have failed.
`#else' is allowed after any number of `#elif'
directives, but `#elif' may not follow `#else'.
Command Line Arguments
Some C programs
can behave in many different ways, based on the users request. For example, if
we use the "ls" command to list files in a directory, we get one
format of data back. If we use "ls -l" we get a long listing, which
is a different format. The "-l" is considered a command line argument. The C
program must "parse" the command line arguments (which are given to
the program as a list of strings) and transform this type of data into a form
useful in "guiding" the program to execute in the manner specified by
the user.
Command Line Args
Many programs have command line args that tell the program how to
behave:
% ls -l
% g++ -g -Wall
% grep -v abc
In C, when you run a program via the linux command line, you can
look at these command line values and alter the behavior of your program as
well.
The first step to tell a C program to "get" the command
line values is to change the signature of the main function, as follows:
intmain(intnumber_of_args,char* list_of_args[] ){...}//// Note: Often you will see "traditional" programs using the more// archaic (if more concise) "Lingo" and syntax for// these values (argc and argv)//intmain(intargc,char** argv ){...}
1. number_of_args : the total number of
"values" on the command line.
Note: The name of the program is counted
and is the first value.
Note: Values are defined by lists of
characters separated by whitespace.
2. list_of_args : this is an array of
strings.
Note: The array has a length defined by
the number_of_args parameter.
When the program is invoked with "values" after the name
of the program, they are stored in the list_of_args. We normally use a loop to
"search" through this list of strings to find (and set) the state of
the program.
Here is a sample program to print out all the information
"given" to the program:
intmain(intnumber_of_args,char* list_of_args[] ){for(inti=0; i<number_of_args; i++){printf("the %2d arg is: %s\n", i, list_of_args[i]);}}
Processing Command Line Args
Usually, you will create a function in C which reads through all
the command line args and returns the state.
For simple cases, where the command line args are well defined,
this can be done in the first few lines of code of the main function:
// example 1intmain(intnumber_of_args,char* list_of_args[] ){if( number_of_args !=1){printf("this program does not take any args!\n");exit(-1);}}// example 2intmain(intnumber_of_args,char* list_of_args[] ){charinvoke_command[] ="./program_name #";intrepeat;if( number_of_args !=2){printf("Please use: %s\n", invoke_command);exit(-1);}// read the second arg and put the value in a number variable:sscanf(list_of_args[1],"%d", &repeat);}