Cnotes - 2019
Cnotes - 2019
19UCA02 – PROGRAMMING IN C
Unit – I
Overview of C: History of C – Importance of C – Basic structure of C programs. Constants,
variables and data types: Character set – Keywords and identifiers – Constants – Variables –
Declaration of storage classes. Operators and expression – Evaluation of expressions – Type
conversions in expressions – Operator precedence and associatively – Mathematical functions.
Managing input and output operations: Reading and writing a character – Formatted input and
output.
Unit – II
Decision making and branching: Simple IF, IF-ELSE, Nesting of IF-ELSE, ELSE-IF ladder,
Switch statements – GOTO statements. Decision making and looping: WHILE statement – DO
statement – FOR statement – Jumps in loops. Arrays: Definition & Declaration – One dimensional –
Two dimensional – Multi dimensional arrays – Dynamic arrays.
Unit – III
Character arrays and strings: Introduction – Declaring and initializing string variables –
Reading strings from terminal – Writing strings to screen – String handling functions – Table of
Strings. User – Defined functions: Introduction – Need for user – Defined function – A Multi –
function program – elements of user – Definition of functions – definitions of Functions - Return
values and their types – Function calls – Function declaration – All category of functions – Nesting
of functions – Recursion – Passing arrays to functions – Passing strings to function.
Unit – IV
Structures and Unions: Introduction – Definition a structure – Declaring structure variables –
Accessing structure members – Structure initialization – Copying and comparing structure variables
– Arrays of structures – Arrays within structures – Structures within structures – Structures and
functions – Unions – Size of structures – Bit fields. Pointers: Introduction – Understanding pointers –
Accessing the address of variables – Initializing of pointer variables. Chain of pointers – Pointers –
Pointers expressions – Pointers and arrays – Pointers and character strings- Arrays of pointers –
Pointers as function arguments – Functions returning pointers – Pointers to functions- Pointer and
structures.
UNIT – V
File Management: Introduction – Defining and opening a file – Closing a file – Input/Output
operation on files – Error handling during I/O operations – Random access files- Command line
arguments. The Preprocessor: Introduction – Macro substitution – File inclusion – Compiler control
directives.
ARIGNAR ANNA COLLEGE - KRISHNAGIRI 1
19UCA02 - PROGRAMMING IN C M.NARESHKUMAR M.C.A.,M.Phil.,B.Ed.,
UNIT-I
OVERVIEW OF C
History of C:
C is one of the most popular computer languages.
It is structured, high level, machine independent language.
It is platform independent
ALGOL is the first structured programming language used in Europe.
In 1967, Martin Richards developed a language called BCPL (Basic Combined programming
Language)
In 1970, ken Thompson created a language using BCPL features called B.
C was evolved from ALGOL, BCPL and B by Dennis Ritchie at Bell Laboratories in 1972.
Unix Operating system, which was developed at Bell Laboratories, was coded almost entirely
in C
C is running under a variety of operating system and hardware platform.
C proved to be an excellent programming language for writing system programs.
“The C programming language” by Kernighan and Ritchie, 1977 is known as “K&RC”
ANSI, in 1983 standard for C was introduced it is called an ANSI C.
Advantages
– C is a real world language, widely available and popular with professional
– C is a small, efficient, powerful and flexible language
– C has been standardized, making it more portable than some other languages
– C is close to the computer hardware revealing the underlying architecture
– C provides enough low level access to be suitable for embedded systems
– C is a high level language allowing complex systems to be constructed with minimum effort
– C‟s modular approach suits large, multi-programmer projects
– C‟s use of libraries makes it adaptable to many different application areas
– The Unix operating system was written in C and supports C
– C gave birth to C++, widely used for applications programming and more recently Java which was
based upon C++
– Many other languages borrow from C‟s syntax: e.q. Java,JavaScript, Perl etc
Disadvantages
– C is not really a language for novices; it was designed for professional users
– There are many things that can go wrong if you‟re not careful
– C lacks much of he automatic checking found in other high level languages
– Small typing errors can cause unwanted effect
– Does not support modern concepts such as object orientation and multi threading.
Documentation Section
Link Section
Definition Section
Global Declaration Section
Main( ) Function Section
{
Declaration Part
Executable Part
}
Subprogram Section
Function 1
Function 2
“
Function N
Documentation Section:
This section consists of a set of comment lines useful for documentation. A comment is one
in C, When it is used in the program should be ignored by the compiler in C. “/*” is used to mark the
start of comment and it teminate with “*/”.
Example :
/* Programmer name : WELCOME
Programmer : Nareshkumar */
(or)
Link Section:
It provides instruction to the compiler to link function from the system library. They are also
known as preprocessor directive used to include header files in C program.
Example :
#include<stdio.h>
#include<conio.h>
#include<math.h>
Definition Section:
The definition section defines all the symbolic constants to define any symbolic constant to
our program. We should use # define instructions.
Define all symbolic constant.
It must be in uppercase.
Example:
#define PI 3.14.
#define MONTHS 12
Example:
#include<stdio.h>
int a=10;
float b=3.14;
void main( )
{
---------
---------
}
Declaration Part:
In the part, declare all variables used in the executable part.
Executable Part:
There is at least one statement in the executable part.
These two parts appear between the opening and closing braces &all statements end with a
semicolon.
Subprogram Section:
The subprogram section contains all the user-defined function that are called in the main
function.
Example :
Myfunction( )
{
Printf(“Hello”);
}
Example program:
/* Program For Example */
#include<stdio.h>
int a = 10, b=20;
void main( )
{
int x = 30, y;
y = x;
printf(“%d”,y);
}
EXCUTING A C PROGRAM:-
The different steps involved in executing (or) running a program.
A sequence of instruction is used to perform a particular task. The instructions are formed
using the character set.
Character Set:
The character sets are grouped into the following categories.
1. Letter (A….Z)&(a….z).
2. Digits (1…9).
3. Special characters
4. White spaces.
Special Characters:
SYMBOL NAME SYMBOL NAME
White Space:
Black space.
Horizontal tab(„\t‟)
Carriage return(„\r‟).
New line(„\n‟)
Form Feed.(„\f‟)
C Tokens:
The smallest individual units are known as c Tokens. It consist Individual words, punctuation
mark, text are called tokens.
Keywords
Identifiers
constants
C Tokens -
Strings
Operators
Special Symbols
Keyword:
All keywords have fixed meaning & these meanings cannot be changed. It must be written in
lower case.
„C„support 32 keywords only.
EX:
Auto double int struct
Break else long switch
Case enum register typedef
Char extern return union
Const float short unsigned
Continue for signed void
Default goto sizeof volatile
Do if static while
Identifiers:
It refer to the name of variables, functions & arrays. Both lowercase & uppercase are
permitted. It cannot use a keyword.
Identifiers are user-defined names and consist of a sequence of letters and digits with a
letter as a first character..
Both upper case and lower case letters are permitted lower case letters are commonly
used.
Identifiers are permits by using underscore.
Rules of Identifiers:
First character must be an alphabet or underscore.
Must consists of only letters, digits or underscore.
Only first 31 characters are significant
Cannot use a keyword.
EX:
Valid Identifiers Invalid Identifiers
ADD, Add, - Add 3add . add+123 , for
Constants:
It refers to fixed data value that does not change during the execution of a program.
Constants
Hexadecimal :
It is formed from the hexadecimal number 0 through 9 and A through F (either upper
or lowercase), leading with 0X, or 0x
Valid Invalid
0x0 626
0x9A 0626
-0X9Aff 0Xapq
String Constant:
A string constant is a sequence of characters enclosed in double quotes.
The characters may be letters, numbers, special characters and blank spaces.
ARIGNAR ANNA COLLEGE - KRISHNAGIRI 9
19UCA02 - PROGRAMMING IN C M.NARESHKUMAR M.C.A.,M.Phil.,B.Ed.,
Valid Invalid
“Hello!” Program
“987” „Area‟
“Good” Maths”
“5+3”
„K‟ gives the integer value
“K” It is a string constant that contains the character K.
Syntax :
#define symbolic name value of constant
Ex:
#define Max 200
Rules:
Symbolic names have the same form as variable names It Should declare as a capital letters.
No blank space between # and define.
A blank space is required between the symbolic name and the constant.
# define statement is declared in definition section in the c programme and it end with
semicolon.
Symbolic names are NOT declared for data types. Its depend on type of constant.
#define statement may appear anywhere in the program but before it is referees in the
program.
#define statement is called a pre-processor compiler.
Variables:
A variable is a data name that may be used to store a data value.
Variable may take different values at different times during execution.
Variable names may consist of letters, digits and underscore (_) character.
Rules:
They must begin with a letter or underscore.
ANSI standard recognizes a length of 31 characters but normally should not be exceed
more than eight characters.
It should not be a keyword.
White space is not allowed.
Valid Invalid
John 123
X1 (area)
Mark 25th
T-raise Char
int-type group one
Declaration Of Variables:
The declaration statement tells the complier 2 things.
1) It tells the complier what the variable name is.
2) It specify what type of data variable name is.
Example:
enum flowers { ROSE,JASMINE, LOTUS};
enum vehicles {BUS,TRAIN,SCOOTER,CAR};
enum currency {rupee=1,dollar=50,pound=60,euro=40};
If there is no value the identifier represent the values 0,1,2,3 and so on, from left to
right.
During explicit assignment, the value may be in any order.
main()
{
int i;
enum swtch
{ OFF,ON
}
enum swtch flag;
i = setflag(flag);
Assignment statement:
Syntax:
variable-name = constant/ variable/expression;
Ex:
Initial-value = 0;
Balance = 75.84;
Final-value = balance * 1000;
C permits multiple assignments in one line.
Initial-value = 0; final-value = 100;
Assign a value to a variable at the time the variable is declared.
Ex:
int final-value = 100;
int yes = 1;
float balance = 756.56;
char yellow = „y‟;
Ex:
main()
{
int number;
printf(“enter an integer number”);
scanf(“%d”,&number);
printf(“print the number value \n”);
printf(“%d”,number);
}
Output:
i = 1211 j= 211
Eg:2
Main()
{
Auto int i=1;
{
{
Printf(“\n %d”,i);
}
Printf(“%d”,i);
}
}
Output:
1
1
Output:
i =0
i=1
i=2
i=1
i=0
Ex:
main()
{
increment();
increment();
}
increment()
{
static int i=1;
printf(“%d\n”, i);
i=i+1;
}
DATA TYPES:
Data type is a term that refers to the kind of data used in a program.
Two major categories of data types are
(i) Scalar data types or Fundamental data types.
(ii) Derived data types or Structured data types.
Scalar Derived
Integral Floating
Void types:
The void types has no values.
This is usually used to specify the type of functions.
Ex Program:
#include<stdio.h>
#include<conio.h>
void main()
{
typedef int marks;
marks m1,m2,m3,tot;
char name;
scanf(“%d%d%d%s”,&m1,&m2,&m3,&name);
tot=m1+m2+m3;
printf(“%d”,tot);
getch();
}
General format:
enum identifier {value1,value2……valuen}
OPERATORS:
It is a symbol that tells the computer to perform certain mathematical or
logical manipulations.
o Arithmetic operators
o Relational operators
o Logical operators
o Assignment operators
o Increment & decrement operators
o Conditional operators
o Bitwise operators
o Special operators
+ addition
- subraction
* multiplication
/ division
% modulo(It is used to give the reminder value )
Integer Arithmetic:
We use integer values in the arithmetic expression is called integer arithmetic.
Eg:
A=5,b=3
Expression value
a+b 8
a-b 2
a*b 15
a/b 1 (decimal point truncated)
a%b 2
Example program
/*calculate months &days*/
void main()
{
int months, days;
printf(“enter the days”);
scanf(“%d”,&days);
months=days/30;
days=days%30;
printf(“months=%d days=%d”,months,days);
}
Real Arithmetic:
The arithmetic operation involves only real numbers is called real arithmetic.
A=5.5,b=2.0
Expression value
a+b 7.0
a-b 3.0
a*b 10.0
a/b 2.75
2. Relational Operators:
These operators are used to compare two or more quantities. the result is either true or false.
Operators Meaning
< is less than
<= is less than or equal to
< is greater than
>= is greater than or equal to
== is equal to
!= is not equal to
General format:
Program
#include<stdio.h>
#include<conio.h>
void main()
{
int a,b;
clrscr();
scanf(“%d%d”,&a,&b);
if(a>b)
printf(“ the largest value is %d”,a);
else
printf(“ the largest value is%d”,b);
getch();
}
3. Logical Operator:
Working of AND,OR:
0 0 0 0
0 1 0 1
1 0 0 1
1 1 1 1
Working of NOT:
Op1 !op1
0 1
1 0
Shorthand Assignment:
The shorthand assignment operator is op=.
Op->operator.
Statement with simple statement with shorthand
Assignment operator operator
a=a+1 a+=1;
a=a-1 a-+1;
a=a*(n+1) a*=n+1;
Advantages:
The statement more concise and easier to read.
The left-hand side variable need not to repeat on the right-hand side.
The statement is more efficient.
The increment is operator (++) add one and decrement operator(--) is subtract one.
Eg.
++m =>m=m+1=>m+=1.
M++=>m=m+1=>m+=1.
In general m++,++m are same but when they are used in assignment statement they have
different meanings.
If the operator placed before the operand it is known as preincrement operator. if the operator
placed following the operand it is known as post increment operator.
For eg.
M=5 m=5;
Y=++m; y=m++;
Y=6,m=6. y=5,m=6.
A prefix operator first adds 1 to the operand and then the result is assigned to the variable on
left.
Postfix operators first assigns the value to the variable on left and then increment the operand.
It is a ternary operator and takes three operands. The “?:” is jointly known as conditional
operator.
General format:
Exp1?Exp2:Exp3
Exp1 is evaluated and if it is true,exp2 is evaluated and the value is assign to variable.
Exp1 is false exp3 is evaluated and the value is assign to variable.
7. Bitwise Operator:
Ex:
a&b 00000101
& 00000011
00000001 result =1
Bitwise or (|) inclusive:
- The | operator performs a bitwise OR between two operators.
Compared bits result
0|0 0
0|1 1
1|0 1
1|1 1
Ex:
a|b 00000101
00000011
00000111
given number 187 Binary Representation: 10111011
15 00001111
91 10111111
Ex:
a^b 00000101
00000011 result(decimal)
00000110 6
given number 214 11010110
selected second operand 31 ^ 00011111
201 11001001
Shift operators:
- The right shift operator >> and the left shift operator << more the bit patterns
To the right or less respectively,
Syntax: constant shift operator n
Variable or shift operator n
- Where shift operator is any one of the shift operator >>. And << n is the number
of bit positions to be shifted.
Ex:
Bit pattern 10101101 is to be shifted by 3 bit position
1 0 1 0 1 1 0 1
The bit paten after the right shift operation is given below
0 0 0 1 0 1 0 1
Left shift operator
0 1 1 0 1 0 0 0
Example:
+20 >> 2 00010100 >> 2 100 >> 1 01100100 >> 1
00000101 5 Decimal 00110010 50 Decimal
+20<<2 00010100 <<2
01010000 ->80 (decimal)
100<< 1 01100100 <<1
11001000 -> 200(decimal)
One’s compliment operator:
- this operator converts all 1 bits to 0 and all 0 bit to 1
illustration of ~operator
Expression Binary representation one‟s compliment
Binary decimal
~17 ~00010001 11101110 238
8 .Special Operators:
- Special operators such as comma operator, size of operator, pointer operators
(& and *)
- And member selection operator (. And ->)
EXPRESSION:
1. Arithmetic expression:
An arithmetic expression is a combination of variable, constant, and operator arranged
as per the a syntax of the language.
Algebraic expression ‘C’ Expression
axb-c a*b-c
(m+n)(x+y) (m+n) * (x+y)
(ab/c) a*b/c
3x^2 +2x+1 3*X*X+2*X+1
EVALUATION OF EXPRESSIONS:
Expressions are evaluated using an assignment statement
variable =expression
X=a*b-c;
Y=b/c*a;
PRECEDENCE OF ARITHMETIC OPERATORS:
An arithmetic expression without parentheses will be evaluated from left to right using the
rules of precedence of operators
Arithmetic operator:
+,-,*,/,%
high priority * /%
low priority + -
First the high priority operators are evaluated and then the low priority operators
x=a-b/3+c*2-1
when a=9,b=12 and c=3
x=9-12 /3+3*2-1
it is evaluated as
step:
x=9-4+3*2-1
x=9-4+6-1
x=5+6-1
x=11-1
x=10
Integer Expression:
An arithmetic expression involving only integer operands is known as an integer expression.
Let a=2,b=3,c=4,d=5,e=6
Eg 1:
(a+c)/c*d
Step 1). (2+4)/4*5
Step 2). 6/4*5
Step 3).1*5
Step 4). 5
Eg 2:
(a+c)/(c*d)
Step 1). (2+4)/(4*5)
Step 2). (6)/(4*5)
Step 3). (6)/(20)
Step 4). 0
Real Expression:
If all the operands in an expression are of real type the expression is known as real
expression. where a,b, c, d, are real variables
Eg :
Let a=.0 ; b=15.0;c=2.5
=10.0+15.0*2.5
=10.0+37.5
=47.5
E.g.: a=5,b=6
a>b = false (0)
a!=b = True (1)
Logical Expressions:
An expression containing logical operators is known as the logical expression.
It is used to combine two or more relative expression.
The result of a logical expression is either true or false.
E.g. 1:
(test 1 > 40)||(test 2 > 40)
Mark = 5
E.g. 2:
Mark 1 > 40)&& (mark 2 >40) && (mark 3 > 40)
R = „p‟
l NOT (!)
Second priority: logical AND (&&)
Third priority: logical OR (||)
Rules:
1. First, parenthesized sub expression from left to right are evaluated
2. If parentheses are nested, the evaluation begins with the
3. Arithmetic expression are evaluated from left to right using the rules of precedence.
4. When parentheses are used ,the expressions with in parentheses assume highest priority.
TRIGNOMETRIC FUNCTIONS;
sin(x) – used to find the sine valve of x . x in radians
cos(x)- used to find the cosine value of x.
tan (x)- used to find the tangent value of s.
a sin (x) = sin -1 (x)
a cos (x)= cos-1 (x)
a tan (x)= tan-1 (x)
Other functions:
Ceil (x)- >If rounds the number to the next highest integer ceil (10.6)=1, ceil (10.3)=11
Floor(x)-> it rounds the number to the next lowest integer floor (10.6)= 11, floor (10.3)= 10
Exp(x)->e to the power.
abs(x)-absolute value of x.
Sqrt(x)->square root of x.
Log(x)->natural log of x.
Ex:
#include<stdio.h>
#include<math.h>
void main()
{
int a,c;
scanf(“%d”,&a);
c= sin(a);
printf(“%d”,c);
}
Reading a character:
I/O Functions:
1) Character-Oriented I/O functions:
i. getchar()
ii. putchar()
2) Formatted I/O Functions
i. Scanf()
ii. Printf()
i. getchar()
getchar() is used to read a single character from the keyboard.
Syntax:
variable_name = getchar();
variable_name is a valid C name.
It is declared as char type.
char name;
name = getchar();
getchar is used on the right-hand side of an assignment statement, the character value
of getchar is turn assigned to the variable name on the left.
# include <stdio.h>
main()
{
char answer;
printf(“ Would u like to know my name ? \n”);
printf(“Type Y for Yes and N for No :”);
answer = getchar();
if(answer == „Y‟ || answer == „y‟)
printf(“\n\n My name is Busy Bee\n”);
else
printf(“\n\n You are good for nothing\n”);
}
The Character functions are contained in the file ctype.h. # include <ctype.h>
2. scanf(“Rs.%f %d %%”,&amount,&interest);
If the data are entered as Rs.2200.75 11%
3. scanf(“%d,%f,%c”,&x,&y,&z);
If the inputs are entered as 15,34.32,
Syntax:
%[Field width] conversion Character
Where the optional item is enclosed within square brackets.
scanf(“%2d %2d”,&p,&q);
If the inputs are given as
7 56
7 is assigned to p and 56 is assigned to q.
If the inputs are given as 50 356
50 is assigned to p and 35 is assigned to q, 6 is read by the next scanf if any, else the
data 6 is ignored.
If the inputs are 356 47 3
356 is assigned to p and 6 is assigned to q and the remaining data are ignored.
scanf(“%6f%4f”,&x,&y);
If the inputs are given as 425.35 1.3
425.35 is assigned to x and 1.3 is assigned to y.
Inclusion of placeholder:
scanf function can input strings containing more than one character.
%ws or %wc
main()
{
int no;
char name1[15], name2[15];
printf(“Enter serial number and name one\n”);
scanf(“%d%15c”,&no,&name1);
printf(“%d%15s\n\n”,no,name1);
printf(“Enter serial number and name two\n”);
scanf(“%d%s”,&no,name2);
}
output:
Enter Address:
New delhi 110002
Newdelhi
New delhi 110 002
New delhi 110 002
Formatted output:
printf function for printing captions and numerical results.
Syntax:
printf(“Control string”, arg1,arg2,…,argn);
control string consists of three types of items
1. characters that will be printed on the screen as they appear.
2. Format specifications that define the output format for display of each item.
3. Escape sequence characters such as \n \t and \b.
Format output
Printf(“%d”,9876); 9876
Printf(“%6d”,9876) 9876
printf(“%06d”,9876) 009876
UNIT-II
DECISION MAKING AND BRANCHING
DECISION MAKING STATEMENT (OR) CONTROL STATEMENT:
The control statements are used to make a decision several control statement available in c.
1. If statement.
2. If else statement.
3. Nested if statement.
4. Else if ladder.
5. Switch statement.
6. Goto statement.
1. Simple if statement:
Simple if is a one-way branching statement .when the condition of if is true, the
statement present within the if block are executed, otherwise the if block is skipped by
transferring the control directly to the first statement after the if block
Syntax:
if(condition)
{
statement;
}
Flowchart:
If
condition true
statement
False
exit
Example:
# include<stdio.h>
void main()
{
int a;
scanf(“%d”,&a);
if(a>20)
printf(“Greater than 20”);
}
Output:
30
Greater than 20
Description:
The above program as illustrated for using simple if statement. If the user
enter the a value is greater than 20. Then the “greater than 20” statement will be
printed otherwise if block is skipped by transferring the control directly to the first
statement after if block.
2. If ..else statement
If …else statement is two way branching statement.
If the condition is true ,then the statement present within the if block are
executed, otherwise the else block are executed.
Syntax:
if(condition)
{
true_block statement
}
else
{
false_block statement
}
Flow chart:
Entry
True If false
condition
Next statement
Example:
if(marks>=40)
printf(“passed”);
else
printf(“failed”);
Example program:
#include<stdio.h>
void main()
{
int n;
scanf(“%d”,&n);
if(n%2= =0)
printf(“even number”);
else
printf(“odd number”);
}
Output:
8
Even number
Description:
The above program is illustrated for the use of if else statement, if(n%2= =0) the
condition is true the given number is even otherwise false the given number is odd should be
printed.
Syntax:
if (condition)
{
if(condition-2)
{
Statement-1
}
else
{
Statement-2
}
}
else
{
Statement-3
}
Statement-x;
Flowchart:
entry
False true
Con
-1
False Co true
n-2
statement-3
Statement-2 Statement-1
Statement-x
Example:
if (a>b)
{
if(a>c)
{
printf(“largest a”);
}
else
{
printf(“largest b”);
}
}
Example program:
#include<stdio.h>
void main()
{
inta,b,c;
scanf(“%d%d%d”,&a,&b,&c);
if(a>b)
{
if(a>c)
{
printf(“%d largest”,a);
}
else
{
printf(“%d largest”,c);
}
}
else
{
if(c>b)
{
printf(“%d largest”,c);
}
else
{
prinf(“%d largest”,b);
}
}
}
Output:
10 20 5
20 largest
Description:
The above program as illustrated the use of nested if statement. hear the first
condition (a>b) is true then it will enter to the second condition (a>c) otherwise it will entered
for the third condition(c>b). if the second condition is true the a is largest will be printed
otherwise false c largest will be printed , if the third condition is true c largest will be printed
otherwise false means b largest will be printed.
4. Else…if Ladder
The else-if ladder is a multiday decision maker which contains two or more else if
,from any one block is executed.
Syntax:
if(condition-1)
Statement-1
elseif (condition-2)
Statement-2;
elseif (condition-3)
Statement-3;
------------------
--------------------
elseif (condition-n)
Statement-n;
else
Default statement
Statement-x;
Flowchart:
Entry
True false
Statement-1
Con
Statement-2 -2
True false
Con
-3
Statement-3
True Con
false
-n
Statement-n Default statement
Statement-x
Example program:
#include<stdio.h>
void main()
{
float per;
scanf(“%f”,&per);
if(per>=75)
printf(“distinction”);
elseif (per>=60)
printf(“first class”);
elseif(per>=50)
printf(“second class”);
elseif(per>=40)
printf(“third class”);
else
printf(“fail”);
}
Output:
56
First class
Description:
The above program is illustrated the use of else if ladder structure. If the first
condition (per>=75) is true then distinction will be printed otherwise false means the second
condition (per>=60) will be checked if its true first class will be printed otherwise it will enter to
third condition (per>=50) if its true second class will be printed, otherwise false means it will
Flowchart:
Switch
expression
Next statement
6. Goto statement
Go to statement transfer control unconditionally to another part of the program which
is marked by a label.
Syntax:
Goto label;
A lable is a valid name of variable.
Goto label;
-------------
-------------
label: statement;
Output:
5
Odd number
Description
The above program is illustrated the use of goto statement. When if the condition
(x%2== 0) if matchs to true the label even statement will be printed otherwise false means
label odd statement will be printed.
Looping:
A sequence of statement is executed until some condition for termination of the loop are
satisfied. It consists of two segments.
1. Body of the loop
2. Control statement
Classification of control structure
1. Entry controlled loop/pre test
2. Exit controlled loop/post test
1. Entry controlled loop:
The control condition is tested before the start of the loop execution. If the condition
are not satisfied, then the body of the loop will not be executed.
2. Exit controlled loop:
The test is performed at the end of the body of the loop and the body of the loop is
executed unconditionally for the first time.
1. While statement:
While is an entry controlled loop statement. If is used to execute the statements repeated as
long as the condition is true.
Syntax:
while (condition)
{
Body of the loop;
}
The test condition is evaluated and if the condition is true, then the body of loop is executed.
After execution of the body, the test condition is once again evaluated and if it is true, the boy
is executed once again.
If the condition is false then the control is transferred out of the loop.
Example:
#include<stdio.h>
void main()
{
int n,i=0;
int s=0;
scanf(“%d”,&n);
while (i<=n)
{
s =s+i:
i =i+1;
}
printf(“%d”,s);
}
Output:
5
15
Description:
The above program is the use of wile statement when for user may entered n value is 5, then
the condition (i<=n) must be checked repeat up to that the s value will be calculated s=s+i and I
value also increase for the body of the loop when the condition is false immediately the final
calculation value of s will be printed in the screen.
Syntax:
do
{
Body of the loop;
}
while(test –condition);
Flowchart:
The test condition is evaluated at the bottom of the loop is called exit controlled loop.
Example:
#include<stdio.h>
void main()
{
int i=0,s=0,n;
scanf(“%d”,&n);
do
{
s=s*I;
i=i+1;
}
while(i<=n);
printf(“%d”,s);
}
printf(“%d”,s);
}
Output:
5
120
Description:
The above program is illustrated the use of do-while statement .when the user entered the n
value is 5,it will calculated s=s+I and i=i+1 upto the condition (i<=n) false onwards , if reached false
then the process will be stopped , then the output s value 120 will be printed in the screen.
Syntax:
For (initialization; test condition; increment /decrement)
{
Body of the loop;
}
Flow chart:
Example :
• for (i=0;i<10;i++)
{
prinf(“%d”,i);
}
• for (i=0;i>=0;i--)
{
printf(“%d”,i)
}
Additional features:
1. More then one variable can be initialized at time using separator comma.
Ex.
for (p=1,n=0;n<10;++n)
2. The initialization section, increment /decrement section may also have more then one part .
Ex.
for (n=1,m=50;n<=m;n=n+i; m=m-1)
{
p=m/n;
printf(“%d%d%d”,n,m,p);
}
3. The test condition may have any compound relation the loop uses a compound test condition
Ex.
s=0;
for (i=1;i<20&&s<100;++i)
{
s=s+i;
printf(“%d%d”,i,s);
}
4. For loop is also permissible to use expressions in the assignment statement of initialization
and increment /decrement sections.
Ex.
for x=(m+n)/2;x>0;x=x/2)
JUMPS IN LOOP:
Unconditional Execution:
1. Break Statement
2. Continue statement
3. goto statement
If the flow of execution is transferred from one part of a program to another part without
carrying out any conditional test, it is known as an unconditional execution.
1. Break statement:
Syntax:
break;
When a break statement appears inside a loop or in a switch-case control structure is
terminates the execution at that point and transfer execution control to the statement
immediately following the loop or switch-case construct statement.
Continue Statement:
The General format is
Continue;
The continue statement is used within loops to end the execution of the current iteration and
proceed to the next iteration.
It provides a way of skipping the remaining statements in that iteration after the continue
statement.
Continue statement should be used only in loop constructs and not in selective constructs.
goto Construct:
The goto construct causes an unconditional transfer of execution.
Goto may be used for breaking more than one loop at a time.
Syntax:
label:
{
statement;
}
.
.
.
goto label;
Where label is an identifier and not a number .
Identifier is a statement label and it is not declared.
Statement label can also be used as a variable name in the same program.
The statements to be executed follow the label ending with a colon (:).
If these statements appear before a goto statement, the flow is in backward direction and it is
known as backward goto.
If the statements appear after a goto statement; this type of goto is known as forward goto.
Same label cannot have in different places.
ARRAY
An arrays is a fixed size sequenced collection of elements of the same data type.(or)
An array is a sequential collection of related data items that‟s share a comma name
Types of Array :
1. One-dimensional arrays
2. Two-dimensional arrays
3. Multi dimensional arrays
1. ONE-DIMENSIONAL ARRAYS:
A list of items can be given one variable name using only one subscript and such as variables
is called a single subscripted or a one dimensional arrays.
Example:
int n[5];
Memory location
N[0]
N[1]
N[2]
N[3]
N[4]
• Declaration of one dimensional arrays:
An array must be declared before they one used the compiler can allocate space for them in
memory .
Syntax:
Data Type Array Name [SIZE];
Example program:
#include<stdio.h>
#include<conio.h>
void main ()
{
intI,j,t,a[10];
printf(“\n enter the number of value \n”);
scanf(“%d”,&n);
for (i=0;I<n;i++)
scanf(“%d”,&a[i]);
for (i=0;I<n;i++)
for (j=0;j<n;j++)
if (a[i]>a[j])
{
ARIGNAR ANNA COLLEGE - KRISHNAGIRI 50
19UCA02 - PROGRAMMING IN C M.NARESHKUMAR M.C.A.,M.Phil.,B.Ed.,
temp =a[i];
a[i]=a[j];
a[j]=temp;
}
printf(“\n asendingoder \n”);
for (i=0;j<n;i++)
printf(“%d\t”,a[i]);
getch();
}
Output :
Enter the numbers
5
Enter the values
20 10 30 50 40
Ascending order
10 20 30 40 50
Description :
The above program is illustrated using single dimensional array the user entered the n number
of elements which can be stored in single dimensional array for using for loop the elements
locations are compared i and j for using temp variable finally the sorted elements are stored in
a[i] output location then the numbers are printed in the screen.
Example:
#include<stdio.h>
void main()
{
int a[0][10],b[10][10],c[10][10];
int i,j,k,n;
scanf(“d”,&n)
for(i=1;j<=n;i++)
{
for(j=1;j<=n;j+i)
{
scanf(“%d”,&a[i][j]);
printf(“%d”,a[i][j]);
}
}
Syntax:
Datatypes arrayname [s][2]…….[sn];
• S1,s2………..sn is the size of the dimension
• Data type is any basic data type
• Array name is the variables name of the array
Ex.
int a[3][3][3];
float b[3][3][3];
• Initializing multi dimensional array:
Ex:
int n[2][3][5]={{1,2,3,4,5};
{6,7,8,9,10};
{2,3,4,5,6};}
{{7,8,9,10,1};
{1,2,4,5,6};
{8,7,9,1,2};}}
DYNAMIC ARRAYS:
To allocate memory be an arrays at run time this is known as dynamic memory
allocation and
The array created at runtime are called dynamic arrays.
Dynamic arrays are created using what are known as pointer variable and memory
management functions malloc , calloc and realloc .
These function are included in the head files <stdio.h>
Dynamic array is used to creating and manipulating data structures.
Ie. Linked list, stack and queue. Now that we have firm grasp on pointers, how can
we allocate memory at run-time instead of compile time? ANSI C provides five
standard functions that helps you allocate memory on the heap.
Dynamic Memory Allocation :: sizeof()
We have already seen this function in the array section. To recap, sizeof() returns a size_t of the
item passed in. So on a typical 32-bit machine, sizeof(int) returns 4 bytes. size_t is just an unsigned
integer constant. sizeof() is helpful when using malloc or calloc calls. Note that sizeof() does not
always return what you may expect (see below).
STRING:
A string is a sequence of character that is treated as a single data item.
Ex.
C close not support string as a data type it allows us to represent string as character array
Operations :
1.reading and writing strings.
2.combinig strings together
3.copying one string to another
4.comparing strings for equality.
5.extracting a portion of a string .
The compiler assigns a character string to a character array it automatically assign a null
character (‟10‟) at the end of the string.
The size should be equal to the maximum number of character in the string plus one.
• Additional features:
To initialize a character array without specifying the number of elements .
The size of the array will be determined automatically based on the number of elements
initialized .
Ex.
char s[] ={ „g‟,‟o‟,‟O‟,‟D‟,‟10‟};
We can also declare the size much longer than the string size in the initialized.
Problem:
Scanf function is termination its input on the first white space it finds.
A white space includes blanks ,tabs, carriage, returns, form, feeds, and, new line.
The scanf function automatically terminates the string that is read with a null
character
Ex.
char a[0];
scanf(“%s”,a);
Input string :
New York
Memory a NEW \0………
To read the entire string ,it use two character arrays of appropriate size .
char a [5],a[5];
scanf(“%s%s”,a,a);
A NEW \0 A1=YORK \0
Problem:
If cannot assign one string to another string directly
Ex:
S=”ABC”;
S1=s2;
Example program:
#include<stdio.h>
void main()
{
char s1[80],s2[80];
int I;
scanf(“%s”,s1);
for(i=0; s1[i] !=‟10‟;i++)
s2[i]=s1[i];
printf(“%s”,s2);
printf(“ no of characters=%d”,i);
}
Writing string to screen:
Two ways to writing string to screen they are
1.using printf() function
2.using putchar () and puts function .
Ex.
Printf(“%10-43”,name);
Input string:
I N D 1 V 1 D U A 1
Output string:
I N D 1
It indicates that the first four character are to be printed in a filed with to colums
Example:
#include<stdio.h>
void main ()
{
int c,d;
char s[ ]="cprogramming";
for(c=0;c<=11;c++)
{
d=c+1;
printf("%-12*s\n",d,s);
}
for(c=11;c>=10;c--)
{
d=c+1;
printf"%-12,*s\n",d,string);
}
}
1. Strcat() function:
The strcat()function joins two strings together
Syantax :
stracat (string1,string2);
Example:
#include<stdio.h>
void main()
{
char s1[]="very";
chars2[]="good";
strcat(s1,s2);
print("%s",s1);
}
Output:
very good
Strcat function may also append a string constant to a string constant to as tring variable.
Example:
strcat (s1,"Good");
C permits nesting of strcat functions
Syntax:
strcat(strcat (string1,string2)string3);
It allowed and concatenates all the three strings together. The resultant string is stored in
string.
Example:
scanf("%s",s1)
strcat(strcat(strcat(s1,"Naresh"),"Kumar");
printf("%s",s1);
ARIGNAR ANNA COLLEGE - KRISHNAGIRI 60
19UCA02 - PROGRAMMING IN C M.NARESHKUMAR M.C.A.,M.Phil.,B.Ed.,
output:
Input string s1=Mr
output string s1=Mr.Nareshkumar
2.strcmp()function:
strcmp() function compares two string to find out whether they are same or different.
the two strings are compared character by character until there is a mismatch or end of the strings is
reached, whichever occurs first.
If the two strings are identical strcmp() returns a value zero. if they are not, same it returns the
numeric difference between the ASCII value of the first non-matching pairs of character.
syantax:
strcmp(string1,string2);
Example:
strcmp(name1,name2);
strcmp("Ran","Ram");
strcmp(name1,"Hassan");
Example Program:
#include<stdio.h>
void main()
{
char s1[ ]=="Jerry";
char s2[ ]="Ferry";
inti,j,k;
i=strcmp(s1,"Jerry");
j=strcmp(s1,s2);
printf("%d%d",i,j);
}
output :
0 4
3. strcpy() function:
strcpy( ) function copies the contents of one string into another.
strcpy( ) function works almost like a string assignment operator.
syantax:
strcpy (string1,string2);
Program:
main()
{
char s1[20];
char s2[]=vijay;
strcpy(s1,s2);
printf("%S",S1);
}
output:
s1= vijay
s2= vijay
4. strlen() function:
strlen() counts the number of character presents in a string.
Syantax:
ARIGNAR ANNA COLLEGE - KRISHNAGIRI 61
19UCA02 - PROGRAMMING IN C M.NARESHKUMAR M.C.A.,M.Phil.,B.Ed.,
integer variable name = strlen(string);
Integer variable recieves the value of the lengeth of the string.
Example:
c=strlen ("vijay");
Program:
#include<stdio.h>
void main()
{
chair c[ ]="All is well";
int i;
i=strlen(c);
printf("%d",i);
}
output:
11
5. Strrev ()function :
It reverse the input string character by character.
syntax:
strrev(string);
Example:
#include<stdio.h>
void main()
{
char s1[ ]="vijay";
chars2[ ];
s2=strrv(s1);
printf("%s",s2);
}
output:
yajiv
Table of strings:
A list of names can be treated as a table of strings and a two-dimensional character array can
be used to store the entire list.
Example:
static char city [] []={"chennai","madurai", “madurai", “krishnagiri"};
C H E N N A I
M A D U R A I
K R I S H N A G I R I
FUNCATION:
A function is a independent section of code that performs a specific task. C function can be
classified into two categories
1. Library function c printf , scanf, etc.
2. User define function (main etc)
2. User-defined function:
A user defined function has be developed by the user at the time of writing a program.
Ex.
Main()
Need for user defined functions:
1. When the same of statement must be repeated several times in various parts of a program
these statement can be placed in a function and invoked whenever required.
2. When user define function are used in a program the number of lines of code decreases.
3. Easier to understand debug and test.
4. Usage of user define functions leads to modular and structured programming.
5. User defined function can be include in the c library allowing other usage to utilize them.
It facilitates top-down modular programming.
Ex.
Top-down modular programming using function multi function program:
Multifunction program:
A function is a self contained block of code that performs a particular task. Once a function
has been designed and packed it can be treated as block box that takes some data from the main
function and return a value.
The inner details of operations are invisible to the rest of the program.
main()
{
Function1();
Function2();
}
Function1();
Function2();
}
Function1();
}
}
Function2();
}
Function3();
}
Function3();
}
Output:
Welcome to aac
Characteristics of modular programming:
1. Each module should do only are thing
2. Communication between modules is allowed only by a calling module
3. A module can be called by one and only one higher module .
4. No communication can take place directly between modules that‟s do not have calling called
relationship.
5. All module are designed as single entry single edit system using control structures.
Elements :
1. Function name.
2. Function type
3. List of parameters
4. Local variables declaration
5. Function statements
6. Return statements
Parts:
1.function header
2. function body
Syntax:
function type function name (parameter list)
{
Local variable declaration;
Executable statements;
Return statements; }
Ex:
1. float mul(float x,float y)
{
}
Example:
int sum (int a,int b)
{
int c;
c=a=b;
return c;
}
Function calls
A function can be called by simply using the function name followed by a list of actual
parameters (arguments) enclosed parentheses.
Syntax:
Function name (argument list )
Ex.
main( )
{
int c;
c=sum(10,20); /* functo call */
printf(“%d”,c);
}
Function call sends two integer values to called function
int sum (int a,int b)
{
int c; \* local variable declaration )*/
c=a+b;
return c;
}
ARIGNAR ANNA COLLEGE - KRISHNAGIRI 66
19UCA02 - PROGRAMMING IN C M.NARESHKUMAR M.C.A.,M.Phil.,B.Ed.,
A function that does not return any value may not be used in expression but can be called into
perform certain takes specified in the function
Ex.
main( )
{
printline( )
}
Function declaration:
All function in a c program must be declared before they are invoked. A function
declaration (function prototype) consist of four parts
1. Function type ( return type)
2. Function name
3. Parameter list
4. Terminating semicolon.
Syntax:
Ex:
int mul (int m,int n); /* function prototype */
int mul (int ,int);
int mul (int a, int b);
A function does not return any parameters and does not return any value
void display (void);
Prototype declaration may be placed in two places in a program.
Above all type the function (including main) inside a function definition
Global prototype:
When we place the declaration above all the function the prototype is referred to a global
prototype .such declarations are available for the function in he program
Local prototype:
When we place it in function definition the prototype is called a local prototype.
Ex.
void printline(void); /*global prototype */
main()
{
printline();
}
void printline (void)
{
int i;
for(i=1;i<=35;i++)
Importance :
Parameters list must be separated by commas
The type must match the type of parameters in the function definition in numbers &
order
Parameters names in the declaration is optional
Function has no formal parameters the list is written as void
The return type is optional when the function return int type data
The declared type do not match with the types in the function definition compiler will
produce an error.
Parameters names do not need to be the same in the prototype declaration and the
function definition parameters:
To pass data from one function to another function is called parameters passing.
1.Declaration (prototype)
2.Function call
3.Function definition
Formal parameters:
The parameters used in prototype and function definition are called formal parameters
and those used in function calls are called actual parameters.
Ex
int sum (int a, int b)
Actual parameters:
Actual parameters used in a calling statements may be simple constants variables or
expression .
Ex.
int sum (10,20);
Formal and actual parameters must match exactly in type , order and number.
Category of function:
A function depending on whether arguments are present or not and whether a value is
return or not
1. Function with no arguments and no return values
2. Function with no arguments and no return values
3. Function with no arguments and one return values
4. Function with no arguments and but return values
5. Function that return multiple values.
1. Function with no arguments and no return value :
The function does not contain any formal parameters and it does not return anyvalue to call
calling function .
The is no data transfer between the calling function and the called function.
Example :
#include<stdio.h>
void main()
{
sum();
}
Example :
#include<stdio.h>
int sum (inta,int b);
void main()
{
int a=0 ,b=20,c;
c=sum (a,b);
printf(“%d”,z);
}
int sum (int x,int y)
{
int z;
z=x+y;
return(z);
}
Example :
#include<stdio.h>
int sum (void)
{
int c;
c=sum();
printf(“%d”,c); }
int sum ( void)
{
int x=10,y=20 z;
z=x+y;
retrun(z);
}
Calling one function from within another function is called nesting of function .
Syntax:
main()
{
Function1();
}
Function1()
{
Function2();
}
Function2()
}
}
Example:
main ()
{
{
palindrome()
}
reverse();
getch();
}
factorial(int n)
{
int fact;
return(1);
else
fact =n* factorial (n-1);
return(fact);
}
Output:
5
Value:120
Evaluation of output
=5* factorial(4)
=5*4 * factorial (3)
=5*4*3* factorial(2)
=5*4*3*2* factorial
=5*4*3*2*1 = 120
Advantage:
1) Recursion reduces the comp lenity of the problem
2) Program implemented by recursion will be smaller in length
3) The recursion program can have any number of netting levels
4) The recursion technique is more natural and compact
Ex:
float largest (float array [ ], int size )
Array [] refers to array name and the fair of brackets informs the compiler that the arguments array
of numbers of elements in the array
Example:
#include<stdio.h>
void main ()
{
float largest (float a[ ], int n);
STRUCTURES:
Structure is a derived data type which consists of different data type. Combined together in a
single room or template, its known as heterogeneous data type.
Syntax:
Struct tagname
{
Data type member 1;
Data type member 2;
----------------
----------------
};
Memory allocation:
Title-> array of 20 characters
Author-> array of 15 characters
struct book, book1,book2; Here, book is the name of the structure, book1,book2 as a structure
variable each variable has three members.
Syntax:
structure variable. structure member
Ex:
struct book
{
char author[15];
char title[20];
float price;
};
void main()
{
struct book b;
scanf(“%s%s%f”,&b.title,&b.author,&b,price);
printf(“%s%s%f”,b.title,b.author,b.price);
}
Output:
Input string:
Programming in c
Balagurusamy
235
Result String:
Programming in C
Balagurasamy
235
EXAMPLE PROGRAM:
# include <stdio.h>
struct book
{
char title[20];
char author[15];
float price;
};
void main()
{
int x;
struct book b1={“c”,”gurusamy”, 235.0};
struct book b2={“c++”,”gurusamy”,325.0};
struct book b3;
b3=b1;
x=((b3.title==b1.ttle)&&(b3.author,b3.price))? 1: 0
if(x= =1)
{
printf(“b1 and b3 are same”);
Printf(“%s%s%f”,b3.title,b3.author,b3.price);
}
else
{
printf (“b1 and b3 are different”);
}
OUTPUT :
B1 and b3 are different
ARRAYS OF STRUCTURES:
To declare an array of structures: a structure is first defined and then an array variable of that
type is declared.
An array of structure is stored inside the memory in the same way as a multi-dimensional
array.
Ex:
main()
{
struct book
{
char name;
float price;
int pages;
};
struct book b[100];
int i;
for(i=0; i<=99; i++)
{
scanf(“%c%f%d”,&b[i].name,&b[i].price,&b[i].pages);
printf(“%c%f%d”,b[i].name,&b[i].price,b[i].pages);
}
Example :
struct book
{
char title [20];
char author[20];
float price;
} b;
PROGRAM:
#include<stdio.h>
struct marks
{
char sname[20];
int sub[3];
int total;
}s;
void main()
{
int i=0;
int total;
scanf (“%s”, s. sname);
}
while (i<2)
{
scanf(“%d”,s.sub[i]);
i++;
}
i=0;
while (i<2)
Example :
struct book
{
char b name[25];
char author[20];
int edition;
Float price;
};
struct issue
{
char borrower[20];
char dt.o.issue[8];
struct book b;
}iss;
Initialization:
struct issue iss= {“vijay”,”28/12/93”},{“c”,”gurusamy”,4,235.00};
Rules:
1. The structure variable used as the actual argument and the corresponding formal
argument in the Called function must be of the same struct type.
2. The return expression can be a simple variable or a structure variable or simple
expression.
3. When a functions returns a structure; it must be assigned to a structure of identical
in the calling function.
4. Called functions must be declared in the calling function appropriately.
EXAMPLE:
#include<stdio.h>
main()
{
struct{char name[20]; int name; float amt;}xyz;
gets (xyz.name);
scanf(“%d”,xyz.num);
scanf(“%f”,xyz.amt);
calculate(xyz);/*passing the structure*/
}
calculate (struct {char name[20];
int numb;
float amt; }abc)
{
float si,rate=5.5,year=2.5;
si=(abc.amt*rate*year)/100;
printf (“%f”,si);
return;
}
Size of structures:
We normally use structures, unions , arrays to create variables of large sizes. The actual size of
these variables in terms of bytes may change from machine to machine.
We use the unary operator sizeof to tell us the size of a structure.
SYNTAX:
sizeof (struct x)
Will evaluate the member of bytes required to hold all the member of the structure x.
If Y is a simple structure variable of type struct x. then the expression is
sizeof(y)
The union is a data type having the similar concept of structures. The declaration for a
union is identical to that of a structure, except that the keyword “UNION” must be substituted in
place of struct.
Declaration of union:
Syntax:
union<tag_ name>
{
<union member (s)>
} <list of union variables>;
Ex:
union student
<int age :
char sex ;
}Un,vz, (or) union student union variables s1, s2, s3;
Example:
#include<stdio‟h>
void main()
{
union demo
{
int age;
char sex;
float percent;
};
union demo d;
d.age =15;
d.sex=‟m‟;
d. percent= 38.22;
printf (“%d\n” ,d.age);
d.sex=‟F‟;
printf (“% cln”,d.sex);
getch();
}
Structure Union
1. The struct keyword is used to start the 1. The union keyword is used to start the
declaration of structure declaration of a union.
2.Memory allocated is separate for all 2.Memory allocated is common for all the
members declared within the structure members
3. The maximum size is allocated Is greater 3.The maximum memory size allocated is
than or equal to the sum of all the equal to the memory size of the larger
individual members declared. number.
4. All the individual members can be accessed 4. Only one member can be accessed at a
at a time. time.
BIT-FIELDS:
While declaring integer data type members within structure ,its size will be 16 bits. There are
occasions where data items require much less than 16 bits space ,there by waste of memory space.
We can overcome the wastage of space by specifying the bit length specifies the number of
bits that should be allotted to a member.(here member can be considered as a bit –field)
POINTER:
A pointer is a variable which holds the address of another variable. This process allows the
indirect access to the objects.
Pointer Expressions:
I ) Pointer Assignments:
We can assign one pointer to another pointer. It is similar of assigning one variable value to an
another variable .When both pointers one some type then we can go for assignment.
Ex: int a =10, b= 20;
int *ptr 1, *ptr 2;
ptr1 =&a; a b
ptr2 =&b; 10 20
ptr1=ptr2
2004 2005
Ptr1 ptr2
2004 2006
a b
10 20
2004 2005
2006 2006
Printf (“The values at ptr1 and ptr2 are : %d%d%”,*ptr**ptr2); will display 20 and 20.
ptr1=&a[0]
Ptr1 Ptr2
2002 2008
4000 4002
ptr2=&a[3]
Ex:
if (ptr1<ptr2)
printf(“ptr1 points to lower memory than ptr2\n”);
else
printf(“ptr1 points to higher memory than ptr2\n”);
then based on ptr1 address the statement will be printed.
Ex.2 :
main ()
{
int n =10; n ptr1
int*ptr; 10 2002
ptr=&n; 2002 4015
ptr++; after p++
nptr
10 2004
2002 4015
printf(“%u\n”,ptr);
}
o/p =>2004
Example program:
#include <studio.h>
void main ( )
{
int a,b,x,y;
int *ptr1, *ptr2;
a=10;
b=20;
ptr1 = &a;
ptr2 = &b;
x=*ptr1+*ptr2;
y=*ptr2/*ptr1;
printf(“The value of X=%d\n”,x);
printf(“The value of Y=%d\n”,y);
*ptr1 =*ptr1+10;
*ptr2=*ptr2+5;
printf(“\n a =%d, b=%d,a,b);
printf(“\n a =%d, b=%d”,*ptr1,*ptr2);
}
The value of x=30
The value of y=2
a=10, b=20
a=20, b=100
Example :
#include<stdio.h>
void main( )
{
int A[3][3]={{10,20,30},{40,50,60},{70,80,90}};
int i,j;
for(i=0;i<=2;i++)
{
printf(“\n”);
for( j=0;j<=2;j++)
printf(“%d”,*(*(a+i)+j));
}
}
Output:
10 20 30
40 50 60
70 80 90
Example:
#include<stdio.h>
void main()
{
int choice;
char*ptrs[]={“welcome to c language\n”,”welcome to aac\n”};
printf (“%s”,ptrr[choice]);
return 0;
}
ARRAYS OF POINTERS:
A pointer variable always contains an address of another variable, but an array of pointers can
contain address of many variables or address of array elements or any other address.
int a=10,b=20,c=30,d=40,e=50;
We require 5 integer pointers to store the address of 5 integer variable mentioned above.
int *ptr1,*ptr2,*ptr3,*ptr4,Ptr5;
Then we can store the address as shown below:
{
ptr1=&a;
ptr2=&b; instead of declaring 5 integer pointer it can declared as int*
ptr3=&c; ptr[5];
ptr4=&d;
ptr5=&e;
}
Example :
#include<stdio.h>
void main()
{
int a=10, b=20,c=30,d=40,e=50;
int**[5];
*[0]=&a; *[1]=&b; *[2]=&c; *[3]=&d; *[4]=&e;
for(i=0;i<5;i++)
{
printf (“Elements%d=%d”,i+1,*ptr(i));
}
}
Output:
Element1=10 Element 2 =20 element 3=30
Element 4=40 Element 5=50
OUTPUT :
a=5 b=10
a=10 b=5
2.Call by reference:
The process of passing the addresses of actual variables to the function is known as call by
reference
Example:
# include<stdio.h>
void swap (int *i, int *j)
{
int t;
t=*I;
*i=*j;
*j=t;
}
POINTERS TO FUNCTION:
A function has a physical location in memory that can be assigned to a pointer. This address is
the entry point of the function and it is the address used when a function is called a pointer to a
function. We can obtain the address of a function by using the function‟s name without parenthesis
or arguments. The name of the function itself represents the starting address of function definitions.
This address can be assigned to a pointer to function variable.
Syntax:
data type(*pointer variable) (argument list of function);
Example:
#include <stdio.h>
#include<conio.h>
int sum (int a, int b)
{
int c ;
c=a+b;
printf(“the sum =%d”, c);
}
void main()
{
int(*ptr)(int,int);
ptr= sum ;
printf(“function sum is located at u address \n”,ptr);
printf(“function sum is located at u address \n”,sum);
(*ptr)(10,20);
getch();
}
Output:
Function sum is located at 4855 address
Function sum is located at 4855 address
The sum is =30
UNIT – V
FILE MANAGEMENT IN C
INTRODUCTION:
FILE:
A file is a collection of records which are stored permanently on secondary storage devices
such as disk.
I/O operations pose two major problems:
i. It becomes cumbersome and time consuming to handle large volume of data through
terminals.
ii. The entire data is lost when either the program is terminated or the computer is tuned off.
It is therefore necessary to have a more flexible approach where data can be stored on the disks and
read whenever necessary, without destroying the data. This method employs the concept of files to
store data. C supports a number of functions that have the ability to perform basic file operations,
which include:
Naming a file,
Opening a file,
Reading data from a file,
Writing data to a file, and
Closing a file.
There are two distinct ways to perfume file operations in C. The first one is known as the low-
level I/O and uses UNIX system calls.
The second method is referred to as the high-level I/O operation and uses functions in C‟s
standard I/O library.
Explanation of syntax
The first statement declares the variables fp as a “pointer to the data type FILE”. As stated
earlier, File is a structure that is defined in the I/O library.
The second statement opens the file named filename and assigns an identifier to the FILE
type pointer fp.
The second statement also specifies the purpose of opening this file. The mode does this job.
Mode can be one of the following:
r open the file for reading only.
w open the file for writing only.
a open the file for appending(or adding) data to it.
The file name and mode are specified as strings. They should be enclosed in double quotation marks.
Trying to open a file
1. When the mode is „writing‟ a file with the specified name is created if the file does not exist.
The contents ate deleted, if the file already exists.
2. When the purpose is „appending‟, the file is opened with the current contents safe. A file with
the specified name is created if the file does not exist.
3. If the purpose is „reading‟, and if it exists, then the file is opened with the current contents
safe otherwise an error occurs.
Consider the following statements:
FILE *p1,*p2;
P1=fopen(“data”,‟ “r”);
P2=fopen(“results”, “w”);
Many recent compilers include additional modes of operation. They include:
r+ The existing file is opened to the beginning for both reading and writing.
w+ Same as w except both for reading and writing.
a+ Same as a except both for reading and writing.
CLOSING A FILE:
A file must be closed as soon as all operations on it have been completed
Syntax
fclose (file _pointer);
Example:
----------------------
----------------------
File *p1, *p2;
P1 = fopen(“INPUT”, “w”);
ARIGNAR ANNA COLLEGE - KRISHNAGIRI 94
19UCA02 - PROGRAMMING IN C M.NARESHKUMAR M.C.A.,M.Phil.,B.Ed.,
P2= fopen(“OUTPUT”, “r”);
-------------------
-------------------
fclose(p1);
fclose(p2);
fclose all():
The close all the files associated with the file pointers.
Syntax:
Int fcloseall();
If it is success returns the number of files closed.
If it‟s error-EOF (ENDOF FILE)
1.fscanf(): fscanf() function reads formatted data. It reads data from the current position of file
pointer into the location given by the argument.
Syntax
fscanf(fp,”controlstring”,argument);
here
fp is a file pointer.
Control string like %d %f.....etc.,
Arguments are the list of data items.
Example:
fscanf(f1,”%s%d%f”, name , &rno,&sal);
2.fprintf(): fprintf ( )function prints formatted data to the file. The printf function formats and prints a
series of characters and values to output file.
Syntax
fprintf(fp,”contro lString”, arguments);
here
fp is a file pointer.
Control string like %d %f.....etc.,
Argument is converted and output according to corresponding formal specification
format.
Example
fprintf(f1,”%s%d%f”, ename,eno, sal);
fprintf(f1,”%s%d%f”, “vijay”,1234,600.75);
1. fgets( ) 2.fputs( )
a) fgets( ): To read a string, from file.
Syntax:
fgets(String, variable, size, filepointer);
Example:
fgets(char,s[50],int n, file *fp);
b) fputs( ): To write the contents of the string at specified position. The terminating
character(„10‟) is not copied.
Syntax:
fputs(string variable, fp);
Example:
fputs(S, fp);
Example:
main( )
{
File *fp;
fp = fopen(“s1.txt”, “r”);
if (fp= = NULL)
{
printf(“Error in opening file”);
}
exit( );
}
1 ftell( ) :This function is used to know the current pointer position of the file form the beginning the
position value is long int.
Syntax:
long int variable = ftell(fP);
Or
position = ftell(fp);
here
fp is a file pointer & position is a current pointer position.
Example
n=ftell(fp);
2 fseek( ):
fseek function is used to move the file position to a desired location with in the file.
Syntax:
fseek(file ptr, offset, position);
Here
File ptr is the file pointer of the file.
Offset is the number of bytes / characters should be moved from desired position.
Position specify the seek position like from beginning ending or current position.
Program
#include <stdio.h>
void main(int argc, char *argv[ ])
{
int a, b, sum;
a = ato i(arg v[1]=);
b=ato i(arg v[2]);
sum=a+b;
c:\> Add 10 to 15
Example Program :
#include <stdio.h>
void main(int argc, char * argv[ ])
{
FILE *fp;
int i;
char word[15]);
fp=fopen(argv[1],”v”);
printf(%d”,argc);
for(i-2;i<argc;i++)
fprintf(fp,”%s”,argv[i]);
fclose(fp);
printf(“%s”,argv[1]);
fp=fopen(argv[1], “v”);
for(i=2;i< argc;i++)
{
fscanf(fp,”%s”,word);
fprintf(“%s”,word);
}
fclose(fp);
for(i=0;i<argc;i++)
printf(“%s”,argv[i]);
}
PREPROCESSOR:
Preprocessor is a tool to make the program easy to read, easy to modify, portable and more
efficient.
Preprocessor, as its name implies, is a program that process the source code before it passes
through the compiler.
Preprocessor directives are placed in the source program before the main line.
They all begin with the symbol # in column one and do not require a semicolon at the end.
A preprocessor directives facilities
1) File Inclusion
2) Macro Substitution facilities
3) Compiler control directives
The preprocessor directives appear before the function main()
But they appear anywhere in a c program
It modifies the c source code before compilation.
Any preprocessor directive must begin with the character #.
Any number of white space, character may follow or precede #.
There is no semicolon to end any preprocessor facility.
HEADER FILES :
Definitions and declarations of common objects shared by many programs may be available
in one or more files. these files are known as header files.
A complete source code uses multiple header files when it makes use of common objects
The header files are included in a program by # include directive.
NESTING OF MACROS:
We can also use one macro in the definition of another macro.
#defineM 5
#defineN M+1
result= (M > N) ? M : N;
Program :
#define BEGIN
main()
{
#define END
}
#define EQUAL = =
#define READ(N) scanf(“%d”,&n)
#define WRITE(N) printf(“%d \n “,N)
BEGIN
General formats :
# if const-expression
#elif const-expression
#else
#if const-expression.
#define TYPE-I 1
#define TYPE-F 1
# if TYPE-I
char type[]=”INTEGER”;
#elif TYPE-F
char type[]=”FLOAT”;
#else
char type[]=”CHARACTER”;
#end if
#define ODD(N) if(N%2)printf(“%d is add\n”)
main ()
{
int i;
for(i=0;i<10;i++)
{
if(i!=0) ODD(i);
else
printf(“%d is even \n”);
}
}
OUTPUT:
1 is odd
2 is even
3 is odd
4 is even
ARIGNAR ANNA COLLEGE - KRISHNAGIRI 103
19UCA02 - PROGRAMMING IN C M.NARESHKUMAR M.C.A.,M.Phil.,B.Ed.,
1. To find the total and average percentage obtained by a student for 6 subjects
AIM:
Write a simple C program to find the total and average percentage obtained by a student for
six subjects.
ALGORITHM :
FLOWCHART :
#include<stdio.h>
#include<conio.h>
void main()
{
char name[20];
int no,m1,m2,m3,m4,m5,m6;
float total, average, percentage;
clrscr();
printf("************Input***************\n");
printf("Enter the Reg.No \n");
scanf("%d",&no);
printf("Enter the Name of the Student \n");
scanf("%s",name);
printf("Enter marks of six subjects: \n");
scanf("%d%d%d%d%d%d",&m1, &m2, &m3, &m4, &m5, &m6);
total = m1 + m2 + m3 + m4 + m5 + m6;
average = total / 6.0;
percentage = (total / 600.0) * 100;
printf("************Output***************\n");
printf("Reg.No : 17UCA%d\n",no);
printf("Name : %s\n",name);
printf("Tamil-II : %d\nEnglish-II: %d\nC : %d\n",m1,m2,m3);
printf("Allied-Maths-II : %d\nSBEC-I-Internet : %d\nEVS : %d\n",m4,m5,m6);
printf("Total marks : %.2f\n", total);
printf("Average marks : %.2f\n", average);
printf("Percentage : %.2f", percentage);
getch();
}
************Input***************\
Enter the Reg.No
1803
Enter the Name of the Student
M.Nareshkumar
************Output***************\
Reg.No : 17UCA1803
Name : M.Nareshkumar
Tamil-II : 78
English-II : 70
C : 80
Allied-Maths-II : 90
SBEC-I-Internet : 75
EVS : 70
Total Marks : 463
Average Marks : 77.16
Percentage : 77.16 %
RESULT:
Thus the above c program is created successfully and the outputs are verified.
2. To check whether a given character is vowels or not using Switch – Case statement.
AIM:
Write a simple C program to check whether a given character is vowels or not using Switch –
Case statement.
ALGORITHM :
FLOWCHART :
PROGRAM :
#include<stdio.h>
#include<conio.h>
void main()
{
char ch , ch1;
clrscr();
printf("**************Input***********\n");
printf("Enter any alphabet: ");
scanf("%c", &ch);
ch1 = tolower(ch);
printf("**************Output***********\n");
switch(ch1)
{
case 'a': printf("It‟s Vowel");
break;
case 'e': printf("It‟s Vowel");
break;
case 'i': printf("It‟s Vowel");
break;
case 'o': printf("It‟s Vowel");
break;
case 'u': printf("It‟s Vowel");
break;
default : printf("Sorry! You are entered character is not vowel");
}
getch( );
}
**************Input***********
Enter any alphabet: E
**************Output***********
It‟s Vowel
**************Input***********
Enter any alphabet: D
**************Output***********
Sorry! You are entered character is not vowel
RESULT:
Thus the above c program is created successfully and the outputs are verified.
AIM:
Write a simple C program to print the numbers 1 to 10 along with their squares.
ALGORITHM :
FLOWCHART :
#include<stdio.h>
#include<conio.h>
void main()
{
int i,n;
clrscr();
printf("************Input************\n");
printf("Enter the n value\n");
scanf("%d",&n);
printf("************Output***********\n");
printf("i i * i\n");
printf("------------\n");
for(i = 1; i <= n; i++)
{
printf("%d %d\n", i, i * i);
}
getch();
}
************Input************
Enter the n value
10
************Output***********
i i*i
-------------------
1 1
2 4
3 9
4 16
5 25
6 36
7 49
8 64
9 81
10 100
RESULT:
Thus the above c program is created successfully and the outputs are verified.
AIM:
Write a simple C program to find the sum of „n‟ numbers using for do-while statement.
ALGORITHM :
FLOWCHART :
PROGRAM :
#include<stdio.h>
#include<conio.h>
void main()
{
int i,n,sum=0;
clrscr();
printf("************Input***********\n");
printf("Enter the how many terms\n");
scanf("%d",&n);
i=1;
printf("************Output**********\n");
do
{
printf("%d+",i);
sum=sum+i;
i++;
}
while(i<=n);
printf("\n\nSum of first %d numbers = %d\n",n,sum);
getch();
}
************Input***********
Enter the how many terms
12
************Output**********
1+2+3+4+5+6+7+8+9+10+11+12+
RESULT:
Thus the above c program is created successfully and the outputs are verified.
AIM:
Write a simple C program to find the factorial of a given numbers using function.
ALGORITHM :
FLOWCHART :
PROGRAM :
#include<stdio.h>
#include<conio.h>
int factorial(int);
void main()
{
int no;
clrscr();
printf("*************Input*************\n");
printf("Enter a number to calculate it's factorial\n");
scanf("%d",&no);
printf("*************Output************\n");
printf("Factorial of %d is = %d\n", no, factorial(no));
getch();
}
int factorial(int n)
{
int i;
int fact = 1;
for( i = 1 ; i <= n ; i++ )
fact = fact * i;
return ( fact );
}
*************Input*************
Enter a number to calculate it's factorial
5
*************Output************
Factorial of 5 is = 120
RESULT:
Thus the above c program is created successfully and the outputs are verified.
AIM:
Write a simple C program to swap two numbers using call by values and call by reference.
ALGORITHM :
FLOWCHART :
PROGRAM :
#include<stdio.h>
#include<conio.h>
void swap(int , int);
void swap1(int* , int*);
void main()
{
int x, y;
clrscr();
printf("***********Input************\n");
printf("Enter the value of x and y\n");
scanf("%d%d",&x,&y);
printf("*************Output**********\n");
printf("Before Swapping\nx = %d\ny = %d\n", x, y);
printf("After Swapping the numbers using call by value method\n");
swap(x , y);
printf("After Swapping the numbers using call by reference method\n");
swap1(&x , &y);
printf("x = %d\ny = %d\n", x, y);
getch();
}
void swap( int x, int y )
{
int t ;
t=x;
x=y;
y=t;
printf("x = %d\ny = %d\n", x, y);
}
ARIGNAR ANNA COLLEGE - KRISHNAGIRI 115
19UCA02 - PROGRAMMING IN C M.NARESHKUMAR M.C.A.,M.Phil.,B.Ed.,
***********Input************
Enter the value of x and y
20
30
*************Output*********
Before Swapping
x = 20
y = 30
After swapping the numbers using call by value method
x = 30
y = 20
After swapping the numbers using call by reference method
x = 30
y = 20
RESULT:
Thus the above c program is created successfully and the outputs are verified.
AIM:
Write a simple C program to find the smallest and largest element in an array.
ALGORITHM :
FLOWCHART :
Start
int arr[10]
int i ,max , min
Read size
Read arr[i]
i++
max =arr[0]
min = arr[0]
Stop
#include<stdio.h>
#include<conio.h>
void main()
{
int arr[10];
int i, max, min, size;
clrscr();
printf("**********Input***********\n");
printf("Enter size of the array: ");
scanf("%d", &size);
printf("Enter elements in the array\n");
for(i=0; i<size; i++)
{
scanf("%d", &arr[i]);
}
max = arr[0];
min = arr[0];
for(i=1; i<size; i++)
{
if(arr[i]>max)
{
max = arr[i];
}
if(arr[i]<min)
{
min = arr[i];
}
}
printf("***********Output**********\n");
printf("Maximum element = %d\n", max);
printf("Minimum element = %d", min);
getch();
}
**********Input***********
Enter size of the array: 5
Enter elements in the array
10
5
30
60
45
***********Output**********
Maximum element = 60
Minimum element = 5
RESULT:
Thus the above c program is created successfully and the outputs are verified.
AIM:
Write a simple C program to perform matrix multiplication.
ALGORITHM :
FLOWCHART:
Start
Read m , n
Read a[i][j]
j++
i++
Read b[i][j]
j++
i++
c[i][j]=0
k++
j++
i++
Print c[i][j]
j++
i++
Stop
#include<stdio.h>
#include<conio.h>
void main()
{
int a[5][5],b[5][5],c[5][5],i,j,k,m,n;
clrscr();
printf("***************Input*************\n");
printf("\nEnter the row and column of input matrix\n");
scanf("%d %d",&m,&n);
printf("\nEnter the First matrix->\n");
for(i=0;i<m;i++)
for(j=0;j<n;j++)
scanf("%d",&a[i][j]);
printf("\nEnter the Second matrix->\n");
for(i=0;i<m;i++)
for(j=0;j<n;j++)
scanf("%d",&b[i][j]);
for(i=0;i<m;i++)
{
for(j=0;j<n;j++)
{
c[i][j]=0;
for(k=0;k<n;k++)
c[i][j]=c[i][j]+a[i][k]*b[k][j];
}
}
printf("\n*************Output*************\n");
printf("\nThe multiplication of two matrix is\n");
for(i=0;i<m;i++)
{
printf("\n");
for(j=0;j<n;j++)
{
printf("%d\t",c[i][j]);
}
}
getch();
}
***************Input*************
Enter the row and column of input matrix
2
2
*************Output*************
The multiplication of two matrix is
36 50
24 33
RESULT:
Thus the above c program is created successfully and the outputs are verified.
AIM:
Write a simple C program to find the sum of an integer array using pointers.
ALGORITHM :
Step 2: Declare the required input and output variables n , numArray[10] , i ,sum = 0 , *ptr as
integer.
Step 8: Calculate the sum value sum = sum + *ptr and increase the ptr value using ptr++.
FLOWCHART :
Start
int n , numArray[10]
int i , sum = 0 , *ptr
Read n
Read numArray[i]
i++
ptr = numArray
i++
Print sum
Stop
#include<stdio.h>
#include<conio.h>
void main()
{
int n,numArray[10];
int i, sum = 0;
int *ptr;
clrscr();
printf("*************Input***********\n");
printf("\nEnter the number of elements : ");
scanf("%d",&n);
printf("\nEnter the element values\n");
for (i = 0; i < n; i++)
scanf("%d", &numArray[i]);
ptr = numArray; /* a=&a[0] */
for (i = 0; i < n; i++)
{
sum = sum + *ptr;
ptr++;
}
printf("***************Output************\n");
printf("The sum of array elements : %d", sum);
getch();
}
*************Input***********
Enter the number of elements : 6
Enter the element values
20
30
60
40
50
10
***************Output************
The sum of array elements: 210
RESULT:
Thus the above c program is created successfully and the outputs are verified.
AIM:
Write a simple C program to copy the contents of one file into another file.
ALGORITHM :
Step 2: Declare the required input and output variables FILE *fp , *fp1 , *fp2 and ch as char.
Step 3: Open the input file fp = fopen(“sample.txt” , “w”) and enter the input contents then press
ctrl + z.
Step 4: Check the while condition while( ( ch = getchar( ) ) ! = EOF ) inside the loop putc(ch , fp)
Step 6: Check the while(1) condition , inside the loop assign ch = fgetc(fp1) and if(ch == EOF) then
Step 9: Print the contents of output.txt file using while(( ch = getc(fp)) != EOF) then print ch.
FLOWCHART :
Start
fp = fopen(“sample.txt”,”w”)
putc( ch , fp)
fclose( fp)
fp1 = fopen(“sample.txt”,”r”)
fp2= fopen(“output.txt”,”w”)
while(1)
ch = fgetc(fp1)
Putc(ch ,fp2)
fclose(fp1 ,fp2)
fopen(“Output.txt”,”r”)
Print ch
fclose(fp)
Stop
PROGRAM :
#include<stdio.h>
#include<conio.h>
#include<stdlib.h>
void main()
{
FILE *fp,*fp1,*fp2;
char ch;
clrscr();
printf("*****************Input**************\n");
fp = fopen("Sample.txt", "w");
printf("Enter data to Sample.txt file and Press ctrl + z after entering the details in to a file :\n");
while( (ch = getchar()) != EOF)
{
putc(ch,fp);
}
fclose(fp);
fp1 = fopen("Sample.txt", "r");
fp2 = fopen("Output.txt", "w");
while (1)
{
ch = fgetc(fp1);
if (ch == EOF)
break;
else
putc(ch, fp2);
}
ARIGNAR ANNA COLLEGE - KRISHNAGIRI 130
19UCA02 - PROGRAMMING IN C M.NARESHKUMAR M.C.A.,M.Phil.,B.Ed.,
printf("**************Output*************\n");
printf("File copied Successfully!\n");
fclose(fp1);
fclose(fp2);
fp = fopen("Output.txt", "r");
printf("The Copied contents of Output.txt file are:\n");
while((ch = getc(fp)) != EOF)
{
printf("%c",ch);
}
fclose(fp);
getch();
}
*****************Input**************
Enter data to Sample.txt file and Press ctrl + z after entering the details in to a file :
Arignar Anna College(Arts and Science) – Krishnagiri
ALL IS WELL
ctrl + z
**************Output*************
File copied Successfully!
RESULT:
Thus the above c program is created successfully and the outputs are verified.