0 - C Notes PDF
0 - C Notes PDF
1
SYLLABUS
Programming in C
Unit 1: C fundamentals Character set - Identifier and keywords – data types – constants - Variables
- Declarations - Expressions - Statements - Arithmetic, Unary, Relational and logical, Assignment
and Conditional Operators - Library functions.
Unit-2: Data input output functions - Simple C programs - Flow of control - if, if-else, while, do-
while , for loop, Nested control structures -Switch, break and continue, go to statements - Comma
operator.
Unit-4: Arrays - Defining and Processing - Passing arrays to functions –Multi-dimension arrays -
Arrays and String. Structures - User defined data types - Passing structures to functions - Self-
referential structures –Unions - Bit wise operations.
Unit-5 : Pinters - Declarations - Passing pointers to Functions -Operation in Pointers - Pointer and
Arrays - Arrays of Pointers -Structures and Pointers - Files : Creating , Processing ,Opening and
Closing a data file.
1. Recommended Texts
i.E.Balaguruswamy, 1995,Programming in ANSI C, TMH Publishing Company Ltd.
2. Reference Books
i.B.W. Kernighan and D.M.Ritchie, 1988,The C Programming Language, 2 nd Edition,
PHI.
ii.H. Schildt, C,2004, The Complete Reference, 4th Edition, TMH
iii. Gottfried,B.S, 1996,Programming with C, Second Edition, TMH Pub. Co. Ltd.,
New Delhi .
iv. Kanetkar Y., 1999,Let us C, BPB Pub., New Delhi.
2
2 – MARKS
UNIT-I
Syntax:-
Eg:-
int sum;
float average;
Syntax:-
char variable_name=’singlecharacter’;
Eg:-
1. ‘a’
2. ‘1’
3. ‘#’
4. ‘<‘
5. ‘X’
ۥ ۥ
Invalid constants: 123 - Length should be 1
3
! (logical negation),
~ (one’s complement or bitwise negation),
– (unary minus),
+ (unary plus),
& (addressof),
* (dereferencing),
++ (pre-increment),
— (pre-decrement),
sizeof operator,
(type) or cast operator
4
An operator is a symbol that tells the compiler to perform specific mathematical or
logical functions. C language offers many types of operators. They are,
1. Arithmetic operators
2. Assignment operators
3. Relational operators
4. Logical operators
5. Bit wise operators
6. Conditional operators (ternary operators)
7. Increment/decrement operators
8. Special operators
An expression is any legal combination of symbols that represents a value. The expression
may consist of a single entity, such as a constant or variable, or it may consist of some combination
of such entities, interconnected by one or more operators. Expressions can also represent logical
conditions which are either true or false. However, in C, the conditions true and false are
represented by the integer values 1 and 0, respectively. There are three types of expressions. They
are
1. Arithmetic expression.eg:-x+y
A symbolic constant is an "variable" whose value does not change during the entire
lifetime of the program. Symbolic constant is defined as below:
#define symbolic_name value
Example :
#define PI 3.1415
5
Name of the constant Value of the constant
Pi 3.1415926535...
e (Natural log) 2.718281828...
9. What is library function? APR’13
Library functions in C language are inbuilt functions which are grouped together
and placed in a common place called library. Each library function in C performs specific
operation. We can make use of these library functions to get the pre-defined output instead
of writing our own code to get those outputs. These library functions are created by the
persons who designed and created C compilers. We are including these header files in our
C program using “#include<filename.h>” command to make use of the functions those are
declared in the header files
Eg:-
If you want to use printf() function, the header file <stdio.h> should be included.
Some of the library functions are
1.<stdio.h>
2.<conio.h>
3.<math.h>
4.<string.h>
5.<ctype.h>
floor( ) function in C returns the nearest integer value which is less than or equal to the
floating point argument passed to this function. Syntax for floor( ) function in C is given
below.
6
eg:-float j=5.9;
printf("floor of %f is %f\n", j, floor(j));
o/p:-floor of 5.900000 is 5.000000
ceil( ) function in C returns nearest integer value which is greater than or equal to the
argument passed to this function.”math.h” header file supports ceil( ) and floor() function
in C language. Syntax for ceil( ) function in C is given below.
double ceil (double x);
eg:- float i=5.4, j=5.6;
printf("ceil of %f is %f\n", i, ceil(i));
printf("ceil of %f is %f\n", j, ceil(j));
C Constants are also like normal variables. But, only difference is, their values can not be
modified by the program once they are defined.Constants refer to fixed values. They are also called
as literals.Constants may be belonging to any of the data type.
Syntax:
Syntax:-
Eg:-
int sum;
float average;
Identifiers are names for entities in a C program, such as variables, arrays, functions,
structures, unions and labels. An identifier can be composed only of uppercase, lowercase letters,
underscore and digits, but should start only with an alphabet or an underscore Identifier names
must be unique. They are created to give unique name to a C entity to identify it during the
execution of a program. An identifier is a string of alphanumeric characters that begins with an
alphabetic character or an underscore character that are used to represent various programming
7
elements such as variables, functions, arrays, structures, unions and so on. Actually, an identifier
is a user-defined word.
A statement is a command given to the computer that instructs the computer to take a specific
action, such as display to the screen, or collect input. A computer program is made up of a series
of statements.There are 3 types.They are
➢ Compound Statements
➢ Expression statement
➢ Control statement
Eg:- x = 5;
x = x + 1;
variable = expression;
where:
8
or certain other characters in a character constant, you must use escape sequences. An escape
sequence is regarded as a single character and is therefore valid as a character constant. They are
also used to provide literal representations of nonprinting characters and characters that usually
have special meanings,.
Escape
Represents
Sequence
\a Bell (alert)
\b Backspace
\f Formfeed
\n New line
\r Carriage return
\t Horizontal tab
\v Vertical tab
\' Single quotation mark
\" Double quotation mark
\\ Backslash
\? Literal question mark
\ooo ASCII character in octal notation
\xhh ASCII character in hexadecimal notation
Unicode character in hexadecimal notation if this escape sequence is used in a
\xhhhh
wide-character constant or a Unicode string literal
le quotation ma rk (").
9
21. Write the general form of the conditional operator. NOV’15
Unary operators take just one operand. Unary operators appear before their operand and
associate from right to left. We consider each, one by one.
UNIT-II
1.Write the syntax for if…else statement.Apr’12
If(test condition)
{
Else
Next statement
The comma operator can be used to link the related expressions together.The comma
operator has left-to-right associativity. ie.,Two expressions separated by a comma are
evaluated left to right and the value of right-most expression is the value of the combined
expression
For example:
Value=(x=10,y=5,x+y)
This statement first assigns x=10, then y=5 and finally assigns 15 to value.
10
Commas can be used as separators in some contexts, such as function argument lists and
in for loop. The comma operator and its operands must be enclosed in parentheses.
For example:
val( x, y + 2, z );
For(n=1,m=10;n<=m;n++,m++)
gets(str)
This function is used to read a string of characters including blank space from the standard
input device and stores the string into the character array ‘str’.
This function appends the null character to the stored set of characters.
char c;
c=getchar();
This function is used to read a single character from the standard input device.
It is used to transfer control of the program outside loop or switch statement either
conditionally or unconditionally.
6.What is looping?Apr’13
getchar()
getc(st,fp)
gets(str)
11
9.Write a note on : Continue statement.Apr’15
It is used to skip some statement of the loop and moves to the next iteration of the loop.
Branching is the process of executing or skipping some statements based on some condition
or a selection is made from several alternatives available.
The while loop tests its condition before execution of the contents of the loop begins;
syntax:
while(expression)
{
}
next statement;
if the test condition is true, the body of the loop will be executed, then the control is transferred
to next statement.
if the test condition is false, the block of code is never executed, then the control is transferred
to next statement
When goto is used, many compilers generate a less efficient code. The usage of goto makes
a program logic complicated and renders the program unreadable. For these reasons the
goto statement is discouraged in ‘c’.
syntax
putchar( variable name);
Where variable name should be a character type variable.
In do..while statement, its body of the loop is executed at least once before checking the
condition.
12
syntax:
do
{
} while (condition);
next statement;
if the test condition is true, the body of the loop is executed repeatedly until the condition becomes
false, then the control is transferred to next statement.
if the test condition is false, the block of code is executed atleast once, then the control is
transferred to next statement.
Also called as decision making statements. In a selection structure, based on the condition the
program takes one or two choices and execute the corresponding statements, after which the
program moves on to the next statement.
If Condition is True then the true block statements will be executed ,otherwise false block
statements will be executed
16.What is the minimum number of times that a do…while loop can be executed?Nov’14
One only time the do..while loop will be executed because its body of the loop is executed at least once
before checking the condition.
• scanf function :- It is used to read the input from the standard input device
• printf function:- It is used to display or print a set of output to the standard output
device
CONTINUE STATEMENT
BREAK STATEMENT
13
It is used to skip some statement of the loop
It is used to transfer control of the program and moves to the next iteration of the loop.
outside loop or switch statement either
conditionally or unconditionally.
It is used only within loop
It is used in loop as well as switch case
statement
UNIT – III
1.State any two advantages of using function. Apr’12
A function definition has two principal components : the function header and the body of the
function.
14
Return type:It is the data type of the value the function returns.
1.Automatic variable
2.External variable
3.Register variable
4.Static variable
The variables which are stored in the register are called register variable.
It is a function that call itself again and again until some condition is statisfied.
f=n*fact(n-1);
The arguments present in the function definition are called formal arguments. These are also called
as dummy arguments.
15
The address of variables are passed to the functions in the form of arguments is called call by
reference.(i.e) the address of the argument to the formal parameter. Inside the function, the address
is used to access the actual argument used in the call
Function body
Example :
int c;
c=a+b;
return c;
The automatic variables are declared inside a function in which they are to be utilized.They are
created when function called and destroyed automatically when function exited,Hence it called
automatic variable.
The variable that is defined inside a function and used only within the particular function is called
local variable.
16
13.What is a global variable? Nov’14
The variable which has been declared before the main function is called global variable.It can be
used in all functions in the program.
Example:
int v;
main( )
V=5;
func1( );
printf(“\n v = %d”,v);
void func1( )
V=10;
Printf(“\n”,v = %d”,v);
Output:
v=5
v=10
The arguments used in the function when it is called by a list of parameters enclosed with in
parentheses is called actual arguments.
Example :
17
The scope of the variable determines in which region of the program the variable is actually
available for use.
The lifetime of a variable is the duration of time a variable exists in the memory during execution.
UNIT – IV
1.Write a syntax for declaration for a string variable.Nov’15
char string_name[size];
struct tag-name
------------ --------
------------ ---------
18
};
Example:
struct book
char title[20];
char author[15];
int pages;
float price;
};
3.Define array.Nov’14
An array is a fixed size sequenced collection of elements of the same data type that share a common
name.
Example: salary[10];
Which represent salary of 10 employees and the number called index or subscript in brackets after
array name.
A self referential structure is used to create data structure like linked lists,stacks,etc.
int value;
};
The individual array elements are identified using index or subscript starts from zero(0).
19
Example: mark[0],mark[1],mark[2],…..
To access the members i.e elements of a structure using member operator or dot operator.
Example:book1.price
Where the price of book1 representing the link between the variable book1 and element price.
8.What is union?Apr’16
Union are derived datatype.union is similar to structure but use the same location for all the
members of union.It is declared with keyword union as follows
union tag-name
------------ --------
------------ ---------
};
union item
int m;
20
float x;
char c;
}code;
This declares a variable code of type union item which contains three members with different data
type.
The declaration of array use subscript which is mentioned in the square bracket and the general
form is
datatype variable-name[size];
The data type specfies the type of element contained in the array such as int,float or char and sizes
indicates the maximum number of elements stored inside the array.
2.The order of values enclosed in braces must match the order of members in the structure
definition.
Example :
struct Patient
{
21
float height;
int weight;
int age;
};
UNIT - V
1.How declare a pointer variable?Apr’12
Pointer variables like other variables should be declared before using it.
When a pointer variable is declared, the variable name must be preceded by an asterisk(*).
This indicates the fact that the variable is a pointer.
Syntax:
datatype * pointer_variable_name;
the datatype refers to the datatype of the variable that the pointer will point to.
a) A data file is a computer file which stores data to be used by a computer application or
system ie., The data files are the files that store data pertaining to a specific application, for
later use
1. Text files.
2. Binary files.
A text file (also called ASCII files) stores information in ASCII characters.
22
A binary file is a file that contains information in the same format in which the information
is held in memory i.e. in the binary form.
The indirection operator (*) is used to access the value of the variable using pointer.ie., “*”
indicates that “The value at the address of “. It otherwise known as dereferencing operator.
Eg.,
int *p,qty,n;//declaration
qty=150;//assignment 150 to qty
p=&qty;//assign the address of qty to “p”
n=*p; // it accesses the value 150 and assigns to n.
In c program, all files are referred through file pointers. A file pointer is a pointer variable
of the type FILE. The syntax for defining a file pointer variable fp is as follows.
file *fp;
this declares a pointer variable fp which is a pointer to the datatype FILE. Here FILE is a
structure datatype that is used to establish the file buffer area.
5.What is a file?Apr’14,Nov’12,Apr’16
7.Define File.Apr’15,Nov’15
23
2.datastructue- defined as FILE in the library of standard I/O function.All files should be
declared as type FILE.
3.purpose-it specifies the purpose of opening the file.
FILE *fp;
fp=fopen(“filename”,,mode);
8.What is a pointer?Apr’16
A pointer is a variable that represents the memory location(rather than the value) of a data
item, such as a variable or array element.
Otherwise pointer is a variable which contains the address of another variable.
The address of a variable is accessed by means of the address operator “&”. The following
program will display the address of the variable.
#include<stdio.h>
void main()
{
int a=1;
printf(“The value is: %d”,a);
printf(“The address is: %u”,&a);
}
Output:
The value is:1
The address is:9364
24
10.What are logical bitwise operators?Nov’13
In the first second category of stream-oriented data files are text files consisting of
consecutive characters. These characters can be interpreted as components of strings or
numbers or as individual data items.
13.What is a file?Nov’14
FILE *fp;
fp=fopen(“filename”,,mode);
25
This declares a pointer variable fp which is a pointer to the datatype FILLE.
fp=fopen(“filename”,”mode”);
“typedef “ declaration is used to define our own identifiers that can be representing an existing
data types such as int,float,double etc.
The identifier defined using “ typedef” is used to declare a variables of that type. The syntax is
given by
typedef datatype identifier;
typedef-keyword
datatype-existing datatype int,float,…
identifier-new name for the existing datatype
26
5 MARKS
UNIT – I
C data types are defined as the data storage format that a variable can store a data to
perform a specific operation. Data types are used to define a variable before to use in a program.
Size of variable, constant and array are determined by data types.
C – data types:
27
1. Basic data type:
1. float
2. double
1. float:
2. double:
• Double data type is also same as float data type which allows up-to 10 digits after decimal.
• The range for double datatype is from 1E–37 to 1E+37.
datatype will vary depend on the CPU processor (8,16, 32 and 64 bit)
28
S.No C Data types storage Size Range
Enumeration data type consists of named integer constants as a list. It start with 0 (zero) by default
and value is incremented by 1 for the sequential identifiers in the list.
syntax:
eg:-
29
enum month { Jan = 1, Feb, Mar };
/* Feb and Mar variables will be assigned to 2 and 3 respectively by default */
Array, pointer, structure and union are called derived data type in C language.
Void is an empty data type that has no value. This can be used in functions and pointers.
A relational operator checks the relationship between two operands. If the relation is true,
it returns 1; if the relation is false, it returns value 0.Relational operators are used in decision
making and loops.
5 == x == y x is equal to y
30
6 != x != y x is not equal to y
Logical Operators
They are, logical AND (&&), logical OR (||) and logical NOT (!).
Logial AND. True only if all If c = 5 and d = 2 then, expression ((c == 5) &&
&&
operands are true (d > 5)) equals to 0.
Logical OR. True only if either one If c = 5 and d = 2 then, expression ((c == 5) || (d
||
operand is true > 5)) equals to 1.
Constants refers to fixed value that do not changed during the execution of the program. The
constants has several types.They are shown below.
Constants
31
Integer constants Real constants single character String constants
Constants
Integer constants:
An integer constant refers to a sequence of digits. There are 3 types of integer constants.
1. Decimal integer
2. Octal integer
1. Decimal integer:
Eg: 123
-123
78
2. Octal Integer:
3. Hexadecimal Integer:
• It consists of any combinations of digits taken from the set 0 through 7 andalso a through
f (either uppercase or lowercase).
• The letters a through f (or A through F) represent the decimal quantities 10 through 15
respectively.
• This constant must begin with either 0x or 0X.
32
• In programming, hexadecimal numbers are used.
Real Constants:
Numbers with fractional part are called real constants. These are often called as floating
point constants. Real constants are generally represented in two forms are fractional form and
exponential form. Fractional form is the general form of representing a floating point value,
exponential or scientific form is used when the value is so big or so small. Exponential form has
two parts. The part before appearing to E is called mantissa and the part following E is called
exponent. Here the mantissa must be multiplied by 10^exponent for example 345.25E-4 is equal
to 345.25*10-4 and 4.56E4 is equal to 4.56*104.
• It must be a number
• It can be either +ve or –ve but by default it is a positive number
• It must have one decimal point.
• No commas and spaces are used in a number
Eg:
+234.45
-34.02
12.0
0.0
A character constant should be enclosed with a pair of single quoate marks. Character
constant can hold Single character at a time. Single Character is smallest Character Data
33
Type in C. A single character constant or character constant is a single alphabet. The
maximum length of a single character constant can be one character.
Syntax:-
Eg:-
6. ‘a’
7. ‘1’
8. ‘#’
9. ‘<‘
10. ‘X’
String Constants:
Escape sequences are used to represent certain special characters within string literals and
character literals.The following escape sequences are available (extra escape sequences may be
provided with implementation-defined semantics):
Escape
Description
sequence
\' single quote
\" double quote
\? question mark
\\ backslash
\a audible bell
\b backspace
\f form feed - new page
\n line feed - new line
\r carriage return
\t horizontal tab
\v vertical tab
34
4.What are the rules for evaluation of expression? Give an example. NOV’15
Precedence of C Operators:
Operator precedence determines the grouping of terms in an expression. This affects how
an expression is evaluated. Certain operators have higher precedence than others; for example, the
multiplication operator has higher precedence than the addition operator:
For example x = 7 + 3 * 2; Here x is assigned 13, not 20 because operator * has higher
precedence than + so it first get multiplied with 3*2 and then adds into 7.Here operators with the
highest precedence appear at the top of the table, those with the lowest appear at the bottom.
35
• Library functions in C language are inbuilt functions which are grouped together and
placed in a common place called library.
• Each library function in C performs specific operation.
• We can make use of these library functions to get the pre-defined output instead of writing
our own code to get those outputs.
• These library functions are created by the persons who designed and created C compilers.
• All C standard library functions are declared in many header files which are saved as
file_name.h.
• Actually, function declaration, definition for macros are given in all header files.
• We are including these header files in our C program using “#include<file_name.h>”
command to make use of the functions those are declared in the header files.
• When we include header files in our C program using “#include<filename.h>” command,
all C code of the header files are included in C program. Then, this C program is compiled
by compiler and executed.
1.<stdio.h>:-
36
2.<conio.h>
3.<string.h>
Strcpy:
strone = "abc";
strtwo = "def";
strcpy(strone , strtwo); // strone becomes "def"
strcmp:
This library function is used to compare two strings and can be used like this: strcmp(str1, str2).
• If the first string is greater than the second string a number greater than null is returned.
• If the first string is less than the second string a number less than null is returned.
• If the first and the second string are equal a null is returned.
eg:
strcat:
This library function concatenates a string onto the end of the other string. The result is returned.
example:
37
printf("Enter you age: ");
scanf("%s", age);
result = strcat( age, " years old." ) == 0 )
printf("You are %s\n", result);
strlen:
This library function returns the length of a string. (All characters before the null termination.)
example:
name = "jane";
result = strlen(name); //Will return size of four.
4.Math.h
1.Sin(x):-
The C library function double sin(double x) returns the sine of a radian angle x.
Eg: sin(30)=0.5
2.Cos(x):-
Eg: cos(30)=0.866
3.Tan(x):-
Eg: tan(30)=0.577
4.Exp(x):-
Eg: exp(30)=1.68
5.Sqrt(x):-
Eg: sqrt(25)=5
6.Abs(x):-
38
It is used to find abs value
Eg: abs(-30)=30
7.Ceil(x):-
Eg: ceil(15.99)=16
Ceil(15.01)=16
8.floor(x):-
Eg: ceil(15.99)=15
Ceil(15.01)=15
4.<ctype.h>
1 int isalnum(int c)
2 int isalpha(int c)
3 int isdigit(int c)
4 int islower(int c)
5 int isupper(int c)
39
Eg: isupper('A') = true
6 int tolower(int c)
Eg: tolower('A') = a
7 int toupper(int c)
Eg: toupper('a') = A
Identifiers
Identifiers are names for entities in a C program, such as variables, arrays, functions,
structures, unions and labels. An identifier can be composed only of uppercase, lowercase letters,
underscore and digits, but should start only with an alphabet or an underscore. An identifier is a
string of alphanumeric characters that begins with an alphabetic character or an underscore
character that are used to represent various programming elements such as variables, functions,
arrays, structures, unions and so on.
Rules for constructing identifiers
1. The first character in an identifier must be an alphabet or an underscore and can be followed
only by any number alphabets, or digits or underscores.
2. They must not begin with a digit.
3. Uppercase and lowercase letters are distinct. That is, identifiers are case sensitive.
4. Commas or blank spaces are not allowed within an identifier.
5. Keywords cannot be used as an identifier.
6. Identifiers should not be of length more than 31 characters.
7. Identifiers must be meaningful, short, quickly and easily typed and easily read.
Invalid identifiers
1x - begins with a digit
char - reserved word
x+y - special character
Keywords:
40
All keywords have fixed meaning and these meanings cannot be changed. Keyword is a basic
building blocks for program statements. The keywords are also called ‘Reserved words’. All
keywords must be written in lowercase.
.
Expression:- The expression may consist of a single entity, such as a constant or variable, or it
may consist of some combination of such entities, interconnected by one or more operators.
Expressions can also represent logical conditions which are either true or false. However, in C, the
conditions true and false are represented by the integer values 1 and 0, respectively. There are 3
types of expressions.
1) Arithmetic Expression
2) Relational Expression
3) Logical Expression
1)Arithmetic expression:-
Syntax:-
Constant constant
Or arithmetic operator or
Variable variable
Eg:-
X+Y;
X+50;
(x+y)/50;
2)Relational expression:-
41
Relational expressions are formed by connectiong constants,variables or arithmetic
expressions by relational operators. Relational expression is an expression that can only take the
values true(1) or false(0). A simple form of logical expression is the relational expression.
Syntax:-
Constant constant
Or or
Or or
Eg:-
or
a>b
(a+b)<50
2)Logical expression:-
Eg:-
(a>0) || (b>25)
Statement
A statement causes the computer to carry out some definite action. There are three different
classes of statements in C
1. expression statements
2. compound statements,
3. control statements.
42
1.Expression statement:-
eg:
a = 6;
c = a + b;
++j;
The first two expression statements both cause the value of the expression on the right of
the equal sign to be assigned to the variable on the left. The third expression statement causes the
value of j to be incremented by 1
2.Compund statement:-
pi = 3.141593;
circumference = 2. * pi * radius;
area = pi * radius * radius;
}
3.Control statement:-
Control statements enable us to specify the flow of program control; ie, the order in which the
instructions in a program must be executed. They make it possible to make decisions, to perform
tasks repeatedly or to jump from one section of code to another.
43
Eg:
if(a>b)
printf(“\n A is big”);
else
printf(“B is big”);
44
UNIT - II
1.Explain the looping statements in ‘C’ with examples.Apr’12
#include<stdio.h>
void main()
int a,b,c;
printf(“\nEnter a,b,c\n”);
scanf(“%d %d %d”,&a,&b,&c);
if((a>b)&&(a>c))
elseif((b>a)&&(b>c))
elseif((c>a)&&(c>a))
else
(Or)
#include<stdio.h>
void main()
45
int a,b,c;
printf(“\nEnter a,b,c\n”);
scanf(“%d %d %d”,&a,&b,&c);
if(a>b)
If(a>c)
Printf(“a=%d\n”,a);
Else
Printf(“c=%d\n”,c);
Else
If(c>b)
Printf(“c=%d\n”,c);
Else
Printf(“b=%d\n”,b);
OUTPUT:
Enter a,b,c;
50
100
70
46
3.Write a note on Input and Output functions in ‘C’Apr’13
4.Write a ‘C’ program to check whether the given string as Palindrome or not. Apr’13
#include<stdio.h>
#include<conio.h>
#include<string.h>
void main()
Char str[80],rev[85];
int i,j,len;
printf(“\nPalindrome checking\n”);
gets(str);
len=strlen(str);
for(i=len-1,j=0;i>=0;i--,j++)
rev[j]=str[i];
rev[j]=’\0’;
if(strcmp(str,rev)==0)
printf(“\n\n%s is a palindrome\n”);
else
getch();
47
5.Explain the working principle of Switch statement with an example. Apr’14
String input and output functions – the gets() and the puts() functions
gets()
it is used to read a string of characters including blank space from the standard input device.
Syntax: gets(st)
it is used to read a string of characters and stores the string into the char array ‘st’.
puts()
it is used to display a string of characters including blank spaces to the standard output device.
Syntax: puts(st)
This function automatically sends the new line character to the terminal after the string has
been printed.
Example
#include<stdio.h>
void main()
char name[20];
gets(name);
puts(name);
48
Single character input functions –
getchar() function
It is used to accept a single character from the keyboard and assigns it to character variable
Syntax:
Example:
char c;
c=getchar();
putchar()
this function is used to display or write a single character on to the standard output
device.
Syntax:
puts() function
It is used to display a string of characters including blank spaces to the standard output device.
Syntax:
puts(st)
This function automatically sends the new line character to the terminal after the string has
been printed.
Example:
#include<stdio.h>
49
void main()
char name[20];
gets(name);
puts(name);
While For
Syntax: Syntax:
next statement
In while loop, initialization is done prior to In for loop, initialization, condition and
the beginning of the loop, , condition is increment or decrement statements are all
given at the end and increment or put together in one line
decrement statements are given in the
body of the loop
The number of iterations can be identified The number of iterations can be identified
at the time of execution. before it starts execution.
9.Discuss the use of break and continue statement with examples. Nov’13
50
BREAK STATEMENT CONTINUE STATEMENT
It is used to transfer control of the program It is used to skip some statement of the
outside loop or switch statement either loop and moves to the next iteration of the
conditionally or unconditionally. loop.
It is used in loop as well as switch case It is used only within loop because the
statement code has no effect in switch case statement
#include<stdio.h> #include<stdio.h>
{ {
for(i=1;i<=10;i++) for(i=1;i<=10;i++)
{ {
if(i%5==0) if(i%5==0)
break; continue;
else else
printf(“%d\t”,&i); printf(“%d\t”,&i);
} }
Output: Output:
1234 12346789
51
12.Write a ‘C’ program to compute the sum of the digits of a given integer numbers.Nov’14
#include<stdio.h>
void main()
int n,r,sum=0;
scanf(“%d”,&n);
do
r=n%10;
n=n/10;
sum=sum+r;
}while(n>0);
52
UNIT – III
1.Distinguish between Automatic and External variables.Give examples.NOV’15
1.Automatic variable are declared inside a External variables are declared before the main
function in which they are local or private to function i.e outside the function.
the function.
2.It is used only within the function It is used throughout the program.
4.Variable can be declared with keyword Auto. It is also declared with keyword extern.
5.Example : Example :
main( ) Extern int v;
{ main( )
int a=10; {
func1( ); V=5;
Printf(“\n a = %d”,a); Func1( );
Printf(“\n b = %d”,b); Printf(“\n v = %d”,v);
}
} Void func1( )
Void func1( ) {
{ V=10;
Auto b=20; Printf(“\n”,v = %d”,v);
Printf(“\n”,b = %d”,b); }
}
53
Output: Output: v = 5
b = 20 V=10
b=0
a = 10
External variables:
Variables that are alive and active throughout the entire program are known as
External Variables.They are also called as Global variables.External variable are declared outside
the function.
Example:
Extern int v;
main( )
V=5;
func1( );
printf(“\n v = %d”,v);
void func1( )
v=10;
printf(“\n”,v = %d”,v);
Output:
54
v=5
v=10
Static Variables:
Static Variable retain its value till the end of the program.It is declared using keyword
static.A static variable may be either an internal type or an external type.
Example:
main( )
int i;
for(i=1;i<=2;i++)
func1( );
void func1( )
x=x+1;
printf(“x = %d”,x);
Output:
x=1
x=2
OR
What are function prototypes?Explain with examples.APR’15
55
All functions must be declared before they are invoked.Afunction declaration also known as
function prototype consists of four parts.
Example:
The return type is int type data which is the function type and returns an integer value.
The parameters list separated by commas and they are m,n which is a type of integer.
1.Automatic variable
2.External variable
3.Register variable
4.Static variable
1.Automatic variable are declared inside a function in which they are local or private to the
function with keyword Auto. Hence it is also known as local or internal variables.
Example :
main( )
int a=10;
56
func1( );
printf(“\n a = %d”,a);
printf(“\n b = %d”,b);
void func1( )
Auto b=20;
printf(“\n”,b = %d”,b);
Output:
b = 20
b=0
a = 10
2.External variables are declared outside a fuction with keyword Extern. Hence it is also known
as global variables.
Example :
Extern int v;
main( )
V=5;
Func1( );
Printf(“\n v = %d”,v);
Void func1( )
57
V=10;
Printf(“\n”,v = %d”,v);
Output:
v=5
v=10
3.Static Variable retain its value till the end of the program.It is declared using keyword static.
Its scope is only with in the functionand it is never initialized again.
Example:
main( )
int i;
for(i=1;i<=2;i++)
func1( );
void func1( )
x=x+1;
printf(“x = %d”,x);
Output:
x=1
x=2
Register variables which are stored in the register are called register variable.
58
The general format is
Example:
Void main( )
Printf(“%d”,i);
Output:
i=30
Recursion is a function that call itself again and again until some condition is statisfied.Recursive
functions normally take less memory space than normal functions.The coding size is also become
small.
Example:
int fact(int);
main( )
int n,r;
printf(“Enter n”);
scanf(“%d”,&n);
r=fact(n);
printf(“factorial = “,r);
int fact(int n )
59
{
int f;
if(n==1)
return(1);
else
f=n*fact(n-1);
return(f);
Output:
n=3
factorial = 6.
60
UNIT – IV
Union are derived datatype.union is similar to structure but use the same location for all the
members of union.It is declared with keyword union as follows
union tag-name
------------ --------
------------ ---------
Example:
union item
int m;
float x;
char c;
61
}code;
This declares a variable code of type union item which contains three members with different data
type. However only one of them can be used at a time.
This is due to the fact that only one location is allocated for a union variable, irrespective of its
size.
The compiler allocates the storage that is large enough to hold largest variable type in the union.
In the union declared above the member x requires 4 bytes which is largest among the members in
16-bit machine. Other members of union will share the same address.
The main advantage of union is they conserve memory that is shared by two or more variables
2.How will you define and process one dimensional arrays in c?Give examples.Nov’13
A list of items can be given in one variable name using only one subscript and such a variable is
called one dimensional arrays.
datatype variable-name[size];
The data type specfies the type of element contained in the array such as int,float or char and sizes
indicates the maximum number of elements stored inside the array.
Example:
int group[10];
Similarly,
char name[10];
This declaration will reserve ten contiguous memory locations capable of storing an character type
as shown below
‘W’
‘E’
‘L’
‘C’
‘O’
‘M’
62
‘E’
‘\O’
When declaring character arrays one extra element allowed for null character.And ensure that the
array should not exceed the declared limits.In the above exampled we can use 10 numbers or 10
characters not more than that.
Unions are conceptually similar to structures. The syntax of union is also similar to that of
structure. The only differences is in terms of storage.
In structure each member has its own storage location, whereas all members of union uses a single
shared memory location which is equal to the size of its largest data member.
This implies that although a union may contain many members of different types, it cannot
handle all the members at same time. A union is declared using union keyword.
union item
{
int m;
63
float x;
char c;
}It1;
This union contains three members each with a different data type. However only one of them can
be used at a time.
This is due to the fact that only one location is allocated for a union variable, irrespective of its
size.
The compiler allocates the storage that is large enough to hold largest variable type in the union.
In the union declared above the member x requires 4 bytes which is largest among the members
in 16-bit machine. Other members of union will share the same address.
4.Summarize the rules for writing a one-dimenasional array definition.Apr’15
a. A list of items can be given in one variable name using only one subscript and such a
variable isone dimensional arrays.
b. The declaration of array will reserve contiguous memory locations capable of storing an
any data type .
c. When declaring character arrays one extra element should be allowed for null character.
d. Ensure that the array should not exceed the declared limits.
e. The declared date type and the given input should be of same type.
Survey is a three dimensionsal array declared to contain 180 integer type values.
The array survey represents the survey data of rainfall during the last three years from January to
December in five cities.
In the first index denote year, the second city and the third month,then the array survey[2][3][10]
denoted the rainfall in the month of October during the second year in city-3.
64
Three-dimensional array can be represented as a series of two dimensional arrays as shown below:
Year 1
Month 1 2 …………….. 12
City
1
.
.
.
.
.
5
Year 2
Month 1 2 …………….. 12
City
1
.
.
.
.
.
5
The function largest is defined with two arguments the array name and size of the array to specify
the number of elements in the array.
float array[ ];
The square brackets informs that it is not necessary to specify the size of the array
main()
65
int n;
int i;
for(i=0;i<n;i++)
scanf(“%f”,a[i]);
int i,j;
for(i=0;i<m;i++)
for(j=1;j<n;J++)
Scanf(“%d”,x[i][j]);
main()
int m,n;
66
void rowcol(int [ ][n], int, int)
UNIT – V
Whenever a variable is declared, system will allocate a location to that variable in the memory, to
hold value. This location will have its own address number.
Let us assume that system has allocated memory location 80F for a variable a.
int a = 10 ;
We can access the value 10 by either using the variable name a or the address 80F. Since the
memory addresses are simply numbers they can be assigned to some other variable. The variable
that holds memory address are called pointer .
A pointer variable is therefore nothing but a variable that contains an address, which is a location
of another variable. Value of pointer variable will be stored in another memory location.
67
2.List the various rules of pointer operations. Nov’15
Example
68
int *p;
declares the variable p as the pointer variable that point to an integer data type.The type int refers
to the data type of the variable being pointed to by p and not the type of the value of pointer.
In the above program, the pointer *p will print all the values stored in the array one by one. It can
also use the Base address (a in above case) to act as pointer and print all the values.
Or
This is the different file access mode when opening a file. It includes −
Mode Description
"w" Creates an empty file for writing. If a file with the same name already exists, its
content is erased and the file is considered as a new empty file.
69
"a" Appends to a file. Writing operations, append data at the end of the file. The file is
created if it does not exist.
"r+" Opens a file to update both reading and writing. The file must exist.
Example
int *p;
declares the variable p as the pointer variable that point to an integer data type.The type int refers
to the data type of the variable being pointed to by p and not the type of the value of pointer.
Initialization of Pointer variable
Pointer Initialization is the process of assigning address of a variable to pointer variable. Pointer
variable contains address of variable of same data type.
int a = 10 ;
int *ptr ; //pointer declaration
ptr = &a ; //pointer initialization
or,
int *ptr = &a ; //initialization and declaration together
70
float a;
int *ptr;
ptr = &a; //ERROR, type mismatch
fopen
To open a file need to use the fopen function, which returns a FILE pointer. Once file opened the
file pointer let the compiler perform input and output functions on the file.
FILE *fp;
fp=fopen("filename”,”mode”);
The file opens the named filename and assigns an identifier to file type pointer fp.
fopen modes
The allowed modes for fopen are as follows:
FILE *fp;
fp=fopen("c:\\test.txt", "r");
This code will open test.txt for reading in text mode.
fclose
When you're done working with a file, you should close it using the function
71
fclose returns zero if the file is closed successfully.
An example of fclose is
fclose(fp);
8.Write a c program to diplay array elements and their corresponding array address.Apr’15
#include<stdio.h>
#include<stdlib.h>
#define size 10
main()
OUTPUT:
9.Explain the different file types that can be specified by the fopen( ) function.Apr’16
Filename is a string of characters that make valid filename.It contain two parts,a primary name
and an optional period with extension.
72
Example:
Input.data
Store
Prog.c
Student.c
Text.out
Data structure of a file is defined as FILE in the library of standard I/O function
definition.Therefore all files should be declared as type FILE before they are used.FILE is a
defined data type.
File *fp;
10.Write a note on operation on pointers.Apr’12
To add integers to or subtract integers from pointers,as well as subtract one pointer from another.
The examples are
Int *p1,*p2,a,b,x,y;
a=12;
b=4;
p1=&a;
p2=&b;
x=(*p1)+(*p2);
y=(*p1)-(*p2;)
x=*p1+5;
y=*p2-3;
For multiplication and division
x=(*p1) * (*p2);
y=(*p1)/(*p2);
x=*p1*3;
y=*p2/2;
To increment or decrement pointer
int *i;
i++;
i--;
73
In the above case, pointer will be of 2 bytes. And when we increment it, it will increment by 2
bytes because int is also of 2 bytes. And when we decrement it, it will decrement by 2 bytes ..
float *i;
i++;
i--;
In this case, when we increment it, it will increment by 4 bytes because float is of 4 bytes.
11.Write a c program that reads the values of three sides of a triangle and display either its
area or its perimeter as per the request of the user using function. (Given the three sides a,b
and c;perimeter=a+b+c;
Area of a Triangle = √(s*(s-a)*(s-b)*(s-c));Where s = (a + b + c)/2 ).APR’13
#include<stdio.h>
#include<math.h>
main()
float a, b, c, Area;
scanf("%f%f%f",&a,&b,&c);
return 0;
74
float s, Area,perimeter;
s = (a+b+c)/2;
Area = sqrt(s*(s-a)*(s-b)*(s-c));
return Area;
10 – MARKS
UNIT – I
1.List and explain different categories of operators in C with suitable Examples.APR’14(or)
Describe the various types of operators in C. NOV’14 (or)Explain the various operators
supported by the C language. APR’12
Operator:-
An operator is a symbol which helps the user to command the computer to do a certain
mathematical or logical manipulations. Operators are used in C language program to operate on
data and variables. C has a rich set of operators which can be classified as
1.Arithmetic operators
2. Relational Operators
3. Logical Operators
4. Assignment Operators
5. Increments and Decrement Operators
6. Conditional Operators
7. Bitwise Operators
8.Special operators.
Arithmetic operator
It is used to perform arithmetic operations. All the basic arithmetic operations can be carried
out in C.
75
+ For performing Addition
- For performing Subtraction
/ For performing Division
* For performing Multiplication
% Modulo for finding remainder in division operation
1) Integer arithmetic
2) Real arithmetic
1)Integer Arithmetic
When an arithmetic operation is performed on two whole numbers or integers than such an
operation is called as integer arithmetic. It always gives an integer as the result. Let x = 27 and y = 5 be 2
integer numbers. Then the integer operation leads to the following results.
x + y = 32
x – y = 22
x * y = 115
x%y=2
x/y=5
x + y = 18.0
x – y = 10.0
x * y = 56.0
x / y = 3.50
2. Relational Operators
It is used to compare the relationship between operands and bring out a decision and
program accordingly. C supports the following relational operators.
76
Operator 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
It is required to compare the marks of 2 students, salary of 2 persons, we can compare them using
relational operators. A simple relational expression contains only one relational operator and takes the
following
exp1relationaloperatorexp2
Where exp1 and exp2 are expressions, which may be simple constants, variables or combination of
them. Given below is a list of examples of relational expressions and evaluated values.
3. Logical Operators
C has the following logical operators, they compare or evaluate logical and relational
expressions.
Operator Meaning
&& Logical AND
|| Logical OR
! Logical NOT
Example
a > b && x = = 10
The expression to the left is a > b and that on the right is x == 10 the whole expression is
true only if both expressions are true i.e., if a is greater than b and x is equal to 10.
Logical OR (||)
The logical OR is used to combine 2 expressions or the condition evaluates to true if any one of
the 2 expressions is true.
77
Example
a < m || a < n
The expression evaluates to true if any one of them is true or if both of them are true. It evaluates
to true if a is less than either m or n and when a is less than both m and n.
For example
! (x >= y) the NOT expression evaluates to true only if the value of x is neither greater than or
equal to y
4. Assignment Operators
The Assignment Operator evaluates an expression on the right of the expression and substitutes it
to the value or variable on the left of the expression.
Example
x=a+b
Here the value of a + b is evaluated and substituted to the variable x. In addition, C has a set of
shorthand assignment operators of the form.
Here var is a variable, exp is an expression and oper is a C binary arithmetic operator. The
operator oper = is known as shorthand assignment operator
Example
x + = 1 is same as x = x + 1
The commonly used shorthand assignment operators are as follows
78
The increment and decrement operators are one of the unary operators which are very
useful in C language. They are extensively used in for and while loops. The syntax of the operators
is given below
1.++ variable name
2. variable name++
3. – –variable name
4. variable name– –
The increment operator ++ adds the value 1 to the current value of operand and the
decrement operator – – subtracts the value 1 from the current value of operand. ++variable name
and variable name++ mean the same thing when they form statements independently, they
behave differently when they are used in expression on the right hand side of an assignment
statement.
m = 5;
y = ++m; (prefix)
m = 5;
y = m++; (post fix)
Then the value of y will be 5 and that of m will be 6. A prefix operator first adds 1 to the operand and
then the result is assigned to the variable on the left. On the other hand, a postfix operator first assigns
the value to the variable on the left and then increments the operand.
79
7. Bitwise Operators
C has a distinction of supporting special operators known as bitwise operators for manipulation
data at bit level. A bitwise operator operates on each bit of data. Those operators are used for
testing, complementing or shifting bits to the right on left. Bitwise operators may not be applied
to a float or double.
Operator Meaning
& Bitwise AND
| Bitwise OR
^ Bitwise Exclusive
<< Shift left
>> Shift right
8. Special Operators
C supports some special operators of interest such as comma operator, size of operator, pointer
operators (& and *) and member selection operators (. and ->). The size of and the comma
operators are discussed here.
The Comma Operator
The comma operator can be used to link related expressions together. A comma-linked list of
expressions are evaluated left to right and value of right most expression is the value of the
combined expression.
For example the statement
value = (x = 10, y = 5, x + y);
First assigns 10 to x and 5 to y and finally assigns 15 to value. Since comma has the lowest
precedence in operators the parenthesis is necessary. Some examples of comma operator are
The size of Operator
The operator size of gives the size of the data type or variable in terms of bytes occupied in the
memory. The operand may be a variable, a constant or a data type qualifier.
Example
m = sizeof (sum);
n = sizeof (long int);
k = sizeof (235L);
The size of operator is normally used to determine the lengths of arrays and structures when their
sizes are not known to the programmer. It is also used to allocate memory space dynamically to
variables during the execution of the program.
Library functions in C language are inbuilt functions which are grouped together and placed in a
common place called library.
Each library function in C performs specific operation.
80
We can make use of these library functions to get the pre-defined output instead of writing our
own code to get those outputs.
These library functions are created by the persons who designed and created C compilers.
All C standard library functions are declared in many header files which are saved as file_name.h.
Actually, function declaration, definition for macros are given in all header files.
We are including these header files in our C program using “#include<file_name.h>” command to
make use of the functions those are declared in the header files.
When we include header files in our C program using “#include<filename.h>” command, all C
code of the header files are included in C program. Then, this C program is compiled by compiler
and executed.
1.<stdio.h>:-
2.<conio.h>
81
3 getche() It reads character from keyboard and echoes to o/p screen
3.<string.h>
Strcpy:
strone = "abc";
strtwo = "def";
strcpy(strone , strtwo); // strone becomes "def"
strcmp:
This library function is used to compare two strings and can be used like this: strcmp(str1, str2).
• If the first string is greater than the second string a number greater than null is returned.
• If the first string is less than the second string a number less than null is returned.
• If the first and the second string are equal a null is returned.
eg:
strcat:
This library function concatenates a string onto the end of the other string. The result is returned.
example:
strlen:
This library function returns the length of a string. (All characters before the null termination.)
example:
82
name = "jane";
result = strlen(name); //Will return size of four.
4.Math.h
1.Sin(x):-
The C library function double sin(double x) returns the sine of a radian angle x.
Eg: sin(30)=0.5
2.Cos(x):-
Eg: cos(30)=0.866
3.Tan(x):-
Eg: tan(30)=0.577
4.Exp(x):-
Eg: exp(30)=1.68
5.Sqrt(x):-
Eg: sqrt(25)=5
6.Abs(x):-
Eg: abs(-30)=30
7.Ceil(x):-
Eg: ceil(15.99)=16
Ceil(15.01)=16
83
8.floor(x):-
Eg: ceil(15.99)=15
Ceil(15.01)=15
4.<ctype.h>
1 int isalnum(int c)
2 int isalpha(int c)
3 int isdigit(int c)
4 int islower(int c)
5 int isupper(int c)
6 int tolower(int c)
Eg: tolower('A') = a
7 int toupper(int c)
84
Eg: toupper('a') = A
Constants refers to fixed value that do not changed during the execution of the program.
The constants has several types.They are shown below.
Constants
Constants
Integer constants:
An integer constant refers to a sequence of digits. There are 3 types of integer constants.
1.Decimal integer
2.Octal integer
1.Decimal integer:
Eg: 123
-123
78
2.Octal Integer:
85
• It consists of any combinations of digits taken from the set 0 through 7.
• If a constant contains two or more digits, the first digit must be 0.
• In programming, octal numbers are used.
3.Hexadecimal Integer:
• It consists of any combinations of digits taken from the set 0 through 7 andalso a through
f (either uppercase or lowercase).
• The letters a through f (or A through F) represent the decimal quantities 10 through 15
respectively.
• This constant must begin with either 0x or 0X.
• In programming, hexadecimal numbers are used.
Numbers with fractional part are called real constants. These are often called as floating
point constants. Real constants are generally represented in two forms are fractional form and
exponential form. Fractional form is the general form of representing a floating point value,
exponential or scientific form is used when the value is so big or so small. Exponential form has
two parts. The part before appearing to E is called mantissa and the part following E is called
exponent. Here the mantissa must be multiplied by 10^exponent for example 345.25E-4 is equal
to 345.25*10-4 and 4.56E4 is equal to 4.56*104.
86
Rules for real constants in fractional form:
• It must be a number
• It can be either +ve or –ve but by default it is a positive number
• It must have one decimal point.
• No commas and spaces are used in a number
Eg:
+234.45
-34.02
12.0
0.0
A character constant should be enclosed with a pair of single quoate marks. Character
constant can hold Single character at a time. Single Character is smallest Character Data
Type in C. A single character constant or character constant is a single alphabet. The
maximum length of a single character constant can be one character.
Syntax:-
char variable_name=’singlecharacter’;
Eg:-
11. ‘a’
12. ‘1’
13. ‘#’
14. ‘<‘
15. ‘X’
String Constants:
87
Escape sequences are used to represent certain special characters within string literals and
character literals.The following escape sequences are available (extra escape sequences may be
provided with implementation-defined semantics):
Escape
Description
sequence
\' single quote
\" double quote
\? question mark
\\ backslash
\a audible bell
\b backspace
\f form feed - new page
\n line feed - new line
\r carriage return
\t horizontal tab
\v vertical tab
a) data type:-
C data types are defined as the data storage format that a variable can store a data to perform a
specific operation. Data types are used to define a variable before to use in a program. Size of
variable, constant and array are determined by data types.
C – data types:
88
4 Void data type Void
5. float
6. double
1. float:
2. double:
• Double data type is also same as float data type which allows up-to 10 digits after decimal.
• The range for double datatype is from 1E–37 to 1E+37.
89
datatype will vary depend on the CPU processor (8,16, 32 and 64 bit)
Enumeration data type consists of named integer constants as a list. It start with 0 (zero) by default
and value is incremented by 1 for the sequential identifiers in the list.
syntax:
90
/* Feb and Mar variables will be assigned to 2 and 3 respectively by default */
3. Derived data type :
Array, pointer, structure and union are called derived data type in C language.
Void is an empty data type that has no value. This can be used in functions and pointers.
Conditional operators return one value if condition is true and returns another value is condition
is false. This operator is also called as ternary operator. ? : is a ternary operator in that it takes
three values. The first argument is a comparison argument, the second is the result upon a true
comparison, and the third is the result upon a false comparison
.
Syntax : (Condition? true_value: false_value);
Example program
#include <stdio.h>
int main()
{
int x=1, y ;
y = ( x ==1 ? 2 : 0 ) ;
printf("x value is %d\n", x);
printf("y value is %d", y);
}
Output:
x value is 2
y value is 2
91
UNIT – II
Example:
char c;
c=getchar();
92
String input function
gets() function
It is used to read a string of characters including blank space from the standard input device.
Syntax:
gets(st)
‘st’ – is the character array
It is used to read a string of characters and stores the string into the char array ‘st’.
It appends the null character automatically to the end of the string
Example
#include<stdio.h>
void main()
{
char name[20];
This function is used to enter any combination of numerical values, single character values
and strings.
scanf(“format string”, & var1,&var2,…,&varn);
“format string” contains
%w datatype
%-conversion specification indicator
w-width of input(optional)
datatype-conversion character or type of data given to the variable
&-address operator,this evaluates the address of the variable.
var1,var2,….varn- variable names
93
conversion character
%c - single character
%d – decimal integer
%s- string
%f – float value
%g – float value
%e-float value with exponent
Example:
scanf(“%s %d %f”,&bookname,&qty,&price);
programming in C
3
600.00
Output functions:
Single character output function
putchar() function
This function is used to display or write a single character on to standard output device.
Syntax:
putchar( variable name);
where variable name should be a character type variable.
string output functions
puts() function
It is used to display a string of characters including blank spaces to the standard output
device.
syntax:
puts(st)
‘st’ – is the character array
94
This function automatically sends the new line character to the terminal after the string has
been printed.
Example:
#include<stdio.h>
void main()
{
char name[20];
puts(“enter the name”);
gets(name);
puts(name);
}
printf() function:
This function is used to display any combination of numerical values, single character
values and strings.
printf(“format string”, var1,var2,…,varn);
“format string” contains
%wp datatype
%-conversion specification indicator
w-width of input(optional)
p-no of digits after the decimal point or no of charactets to be printed on the VDU.
datatype-conversion character or type of data given to the variable
var1,var2,….varn- variable names
Example
printf(“%s\t %d\t %f”,bookname,qty,price);
95
Control statements in ‘C’ are
1. if statement
2. switch statement
1. if statement:
The if statement can be of different forms:
➢ simple if statement
➢ if..else statement
➢ if..elseif ladder
➢ nested if..else statement
➢ simple if statement:
It is used to execute or skip one statement or group of statements for a particular
condition.
Syntax:
if(testcondition)
{
Statement block;
}
next statement;
working principle:
when this statement is executed, the system first evaluates the value of the test condition.
If the value is true then the statement block and the next statement get executed
sequentially.If the value is false then the statement block is skipped and the execution starts
from the next statement.
96
Flow diagram
Example:
#include<stdio.h>
void main()
{
int n;
printf(“enter the value for n”);
scanf(“%d”,&n);
if(n<0)
printf(“the given no is a negative”);
}
➢ Nested if..else statement
This is statement is formed by joining if..else statemens either in the if block
or in the else block or both in order to check a series of decisions in a situation.
Syntax:
if(testcondition-1)
{
if(testcondition-2)
{
Statement block-1;
97
}
else
{
Statement block-2;
}
}
else
{
Statement block-3
}
Next statement;
Working principle:
The system first evaluates the value of test condition-1. If it is false, the control is
transferred to statement block-3.
If the result is true, test condition-2 is evaluated. If the result is true, statement
block1 is executed and the control is transferred to the next statement. Else , statement
block-2 is executed and the control is transferred to the next statement.
Flow diagram:
98
Example:
/*Biggest or Largest of 3 given numbers using nested if */
#include<stdio.h>
void main()
{
int a,b,c;
printf(“\nEnter a,b,c\n”);
scanf(“%d %d %d”,&a,&b,&c);
Else
printf(“c=%d\n”,c);
}
else
99
{
if(c>b)
printf(“c=%d\n”,c);
else
printf(“b=%d\n”,b);
}
}
OUTPUT:
Enter a,b,c;
50 100 70
Biggest value is b=100
2. Switch statement:
Switch statement tests the value of a given variable (or expression) against a list of
case values and when a match is found, a block of statements associated with that case is
executed.
Syntax:
switch(expression)
{
case label1:
Statement Block-1;
break;
case label2:
Statement Block-2;
break;
…
case labeln:
Statement Block-n;
break;
100
default:
default block statement;
}
next statement
When this statement is executed, the system first evaluates the value of the expression. Then the
value is successfully compared with the cases such as case label1,case label2,…,case labeln. If a
case label matches with the value, then the corresponding statement block is executed. Then the
control is transferred to the next statement.If none of the cases matches with the value, the default
statement block is executed.
Example:
#include<stdio.h>
void main()
{
int choice;
printf(“\nEnter ur choice\n”);
scanf(“%d”,&choice);
switch(choice)
{
case 1:
printf(“\nSunday”);
break;
case 2:
printf(“\nMonday”);
break;
case 3:
printf(“\nTuesday”);
break;
case 4:
101
printf(“\nWednesday”);
break;
case 5:
printf(“\nThursday”);
break;
case 6:
printf(“\nFriday”);
break;
case 7:
printf(“\nSaturday);
break;
default:
printf(“\n Enter ur choice as 1-7\n”));
}
printf(“End of the program”);
}
if the result is false, then exp3 is evaluated become s the value of the expression
Example:
a=10;
b=15;
102
x=(a>b)?a:b;
OUTPUT:
x=b or x=15
4.goto statement:
This statement is used to branch the program unconditionally from one point to another in
a program.
It requires a label in order to identify the place where to move.
Syntax:
Goto label;
---------
--------
Label:
Statement;
The label can anywhere in the program either before or after the goto statement.
Example:
#include<stdio.h>
void main()
{
int n;
printf(“\nEnter n”);
scanf(“%d”,&n);
if(n%2==0)
goto L1;
else
goto L2;
L1:
printf(“\nthe given number is even”);
L2:
103
printf(“\nthe given number is odd”);
}
4)Write a ‘C’ program to calculate the roots of a quadratic equation
AX2 + BX + C = 0-(Apr’15,NO’13)
/* program to calculate the roots of a quadratic equation AX 2 + BX + C = 0*/
#include<stdio.h>
#include<math.h>
void main()
{
int a,b,c,r;
float r1,r2;
printf(“\nEnter the value for a,b,c:\n”);
scanf(“%d%d%d”,&a,&b,&c);
r=b*b-4*a*c;
if(r==0)
{
printf(“The two roots are real and equal”);
r1=-b/(2.0*a);
r2=-b/(2.0*a);
printf(“\nRoot1=%f Root2=%f”,r1,r2);
}
else if(r>0)
{
printf(“The two roots are real and unequal”);
r1=(-b+sqrt(r))/(2.0*a);
r2=(-b-sqrt(r))/(2.0*a);
printf(“\nRoot1=%f Root2=%f”,r1,r2);
104
}
else
{
r1=-1.000000 r2=-1.000000
105
Exit controlled statement
iii) Do-while statement
Working principle:
if the test condition is true, the body of the loop will be executed, then the control is
transferred to next statement.
if the test condition is false, the block of code is never executed, then the control is
transferred to next statement.
FLOW DIAGRAM:
Example:
#include<stdio.h>
void main()
{
106
int i=0,n,sum=0;
printf”\nEnter the value of n\n”);
scanf(“%d”,&n);
while(i<=n)
{
sum=sum+i;
i++;
}
printf(“\nThe sum is %d”,sum);
}
OUTPUT:
Enter the value of n 3
The sum is 6
ii)for loop:
It is used to execute a statement or group of statements repeatedly for a known number of
time.
syntax:
for (intialization; condition; increment or decrement)
{
body of the loop
}
next statement;
intialization : intial value to the loop variable or index variable
condition : conditional expression that specifies the condition that will terminate the iteration
process and the iteration stops when this condition returns ‘false’ value.
increment or decrement statement: an assignment statement that may be an increment or
decrement value of the index variable.
Working principle:
When the for statement is executed, the value of the control variable is initialized and tested
with the test condition.
If the condition is true, the body of the loop is executed and control is transferred to the for
statement. The value of control variable is then incremented or decremented.
107
If the condition is false, then the control is transferred to the next statement.
Flow Diagram:
Example:
#include<stdio.h>
void main()
{
int i=0,n,sum=0;
printf(“Enter the value for n\n”);
scanf(“%d”,&n);
for(i=1;i<=n;i++)
{
sum=sum+i;
}
printf(“the sum =%d”,sum);
}
OUTPUT:
Enter the value of n
3
108
Sum=6
do-while statement
syntax:
do
{
body of the loop
} while (condition);
next statement;
working principle:
when this statement is executed, first its body of the loop is executed at least once before
checking the condition. Then the condition will be checked.
If the test condition is true, the body of the loop is executed repeatedly until the condition
becomes false, then the control is transferred to next statement.
If the test condition is false, the block of code is executed atleast once, then the control is
transferred to next statement.
Flow Diagram:
Example:
#include<stdio.h>
void main()
{
109
int i=0,n,sum=0;
printf(“Enter the value of n\n”);
scanf(“%d”,&n);
do
{
sum=sum+i;
i++;
}while(i<=n);
printf(“The sum is: %d”,sum);
}
OUTPUT:
Enter the value of n
3
The sum is 6
6)Explain the various branching statements in ‘C’ with examples.( Nov.2012)
There are two types of branching statements in ‘C’,
i. Simple branching
i.Simple branching:
a.simple if statement
it is used to execute or skip one statement or group of statements for a particular condition.
Syntax:
if(testcondition)
{
Statement block;
}
110
next statement;
working principle:
when this statement is executed, the system first evaluates the value of the test condition.
If the value is true then the statement block and the next statement get executed
sequentially.If the value is false then the statement block is skipped and the execution starts
from the next statement
Flow diagram:
Example:
#include<stdio.h>
void main()
{
int n;
printf(“enter the value for n”);
scanf(“%d”,&n);
if(n<0)
printf(“the given no is a negative”);
}
ii.Switch statement:
111
Switch statement tests the value of a given variable (or expression) against a list of case
values and when a match is found, a block of statements associated with that case is
executed.
Syntax:
switch(expression)
{
case label1:
Statement Block-1;
break;
case label2:
Statement Block-2;
break;
case labeln:
Statement Block-n;
break;
default:
default block statement;
}
next statement
FLOW DIAGRAM:
112
WORKING PRINCIPLE:
When this statement is executed, the system first evaluates the value of the expression. Then the
value is successfully compared with the cases such as case label1,case label2,…,case labeln. If a
case label matches with the value, then the corresponding statement block is executed. Then the
control is transferred to the next statement.
If none of the cases matches with the value, the default statement block is executed.
Example:
#include<stdio.h>
void main()
{
int choice,a,b,c;
printf(“\nEnter a and b\n”);
scanf(“%d %d”,&a,&b);
printf(“\nEnter ur choice:1- ADDITION,2-SUBTRACTION,3-MULTIPLICATION,4-
DIVISION\n”);
scanf(“%d”,&choice);
switch(choice)
113
{
case 1:
printf(“\nADDITION PERFORMED\n”);
c=a+b;
break;
case 2:
printf(“\nSUBTRACTION PERFORMED\n”);
c=a-b;
break;
case 3:
printf(“\NMULTIPLICATION PERFORMED\n”);
c=a*b;
break;
case 4:
printf(“\NDIVISION PERFORMED\n”);
c=a/b;
break;
default:
7) What are the various forms of ‘if’ statement? Explain any two of them with syntax and
examples.( Nov.2015)
The various forms of if statement are,
a. simple if statement
b. if..else statement
114
c. if..elseif ladder
d. nested if..else statement
a.simple if statement
it is used to execute or skip one statement or group of statements for a particular condition.
Syntax:
if(testcondition)
{
Statement block;
}
next statement;
working principle:
when this statement is executed, the system first evaluates the value of the test condition.
If the value is true then the statement block and the next statement get executed
sequentially.If the value is false then the statement block is skipped and the execution starts
from the next statement.Flow diagram are
Example:
#include<stdio.h>
void main()
{
int n;
115
printf(“enter the value for n”);
scanf(“%d”,&n);
if(n<0)
b.if..else statement
It is used to execute one group of statements if the test condition is true and the other group
of statements if the test condition is false.
Syntax:
if(testcondition)
{
Statement block1(true block);
}
else
{
Statement block2(false block);
}
next statement;
working principle:
when this statement is executed, the system first evaluates the value of the test condition.
If the value is true then the true block statement and the control is transferred to the next
statement
If the value is false then the statement block-2 is executed and the execution starts from the
next statement.
Flow Diagram
116
Example:
/*Find the given number is odd or even*/
#include<stdio.h>
void main()
{
int n;
printf(“\nenter the value for n”);
scanf(“%d “,&n);
if(n%2==0)
printf(“\nThe given number is EVEN”);
else
printf(“\nThe given number is ODD”);
}
117
This statement is used to take multi-way decision.
This statement is formed by joining if..else statements in which each else statement contains
another if ..else statement.
Syntax:
if(testcondition-1)
{
Statement Block-1;
}
else if(testcondition-2)
{
Statement Block-2;
}
……..
……..
……..
else if(testcondition-n)
{
Statement Block-n;
}
else
Default statement;
Next statement;
118
Flow Diagram:
working principle:
The system executes this statement from top to bottom. If the test condition is true, then the
statement block associated with it is executed. Then the control is transferred to the next statement.
If all the test conditions are found to be false, then the final else part containing the default
statement will be executed.
Example:
#include<stdio.h>
void main()
{
int day;
printf(“\nEnter a number between 1 and 7\n”);
scanf(“%d”,&day);
if(day==1)
{
printf(“\nSunday”);
else if(day==2)
printf(“\nMonday”);
else if(day==3)
119
printf(“\nTuesday”);
else if(day==4)
printf(“\nWednesday”);
else if(day==5)
printf(“\nThursday”);
else if(day==6)
printf(“\nFriday”);
else if(day==7)
printf(“\nSaturday);
else
printf(“\n Give a number between 1 and 7\n”));
}
printf(“End of the program”);
}
OUTPUT:
Enter a number between 1 and 7:6
Friday
Enter a number between 1 and 7:8
120
UNIT – III
1.What are multifile programs?Explain with example.NOV’13
More than one source files may be compiled separately and linked to form an executable object
code.Because any changes in one file does not affect other files.
Multiple source files share a variable declared as external variable. Variables are shared by two or
more files are global variables and therefore must declare them in one file and then explicitly
define with keyword Extern in other files.
The extern tells the compiler that the variable type and name have already declared elsewhere and
no need to create storage space for them.Because it was declared as global variable and extern
declaration is secondary reference.
Example:
File1.c
int m
main( )
int i;
function1( )
int c;
File2.c
Extern int m;
function2( )
Int i;
121
Function3( )
int j;
1.Automatic
2.External
3.Register
4.Static
Automatic variable are declared inside a function in which they are local or private to the function
with keyword Auto. Hence it is also known as local or internal variables.They are created when
function is called and destroyed automatically when function is exited.
Example :
main( )
int a=10;
func1( );
Printf(“\n a = %d”,a);
Printf(“\n b = %d”,b);
Void func1( )
Auto b=20;
Printf(“\n”,b = %d”,b);
122
Output:
b = 20
b=0
a = 10
External variables are declared outside a fuction with keyword Extern and are active throughout
the program.Hence it is also known as global variables.
Example :
Extern int v;
main( )
V=5;
Func1( );
Printf(“\n v = %d”,v);
Void func1( )
V=10;
Printf(“\n”,v = %d”,v);
Output: v = 5
v=10
Static Variable retain its value till the end of the program.It is declared using keyword static. A
static variable may be either an internal type or an external type.
Internal Static variable are those declared and initialized only once inside a function.Its
scope is only with in the function and it is never initialized again.
External Static variable is declared outside of all functions and used in all funtions.
123
Example:
main( )
int i;
for(i=1;i<=2;i++)
func1( );
void func1( )
x=x+1;
printf(“x = %d”,x);
Output:
x=1
x=2
Register variables which are stored in the register are called register variable.
Example:
void main( )
printf(“%d”,i);
124
}
Output: i = 30
A function definition also known as function implementation includes the following elements
1.Return type.
2.function name.
3.list of parameters.
2.function statements.
3.return statements.
Return type: It is the data type of the value the function returns to the program calling the
function.If the function does not return any value specify the return type as void.
Funtion name: The name of the function is any identifier and follows the same rule of formation
of other variable names in c.
Parameters list: when function invoked values are passed to the parameter by the calling
function.They are also referred as formal parameters.The parameters are also known as arguments.
Function body: The function body contains declaration and statements for the required task.The
body enclosed in braces,contains three parts,
125
2.Function statements that perform the task of the function.
Example :
main( )
int x,y;
scanf(“%d%d”,&x,&y);
sum(x,y);
printf(“Sum = %d”,a+b);
A function depending on whether arguments are present or not and whether a value is returned or
not it is categorized in to four types.
1.No arguments and no return values: When function has no arguments it does not receive any
data from calling function.similarly it does not return any data from the called function.No data
transfer between calling function and the called function.
126
Function1( ) No input
{ Function2( )
{
Function2( )
No output
}
}
Example:
void add( );
main()
add( );
void add( )
int a,b;
scanf(“%d%d”,&a,&b);
printf(“addition=%d”,a+b);
2.With arguments and no return values: When function has arguments it receive data from
calling function.But it does not return any data from the called function.
Example:
void add(int,int);
main()
127
printf(“adding two values”);
scanf(“%d%d”,&a,&b);
add( a,b);
printf(“addition=%d”,x+y);
Function2( )
No output
} }
The arguments a and b are the actual arguments send the values from calling function to the formal
arguments x and y which is in the function defintion.The actual and formal arguments should
match in number,type and order.
3. With arguments and one return values: When function has arguments it receive data from
calling function. similarly it return only one data .
Function2( )
Function result Return( )
} }
Example :
128
int add( int a ,int b);
main()
int a,b,c;
scanf(“%d%d”,&a,&b);
c=add( a,b);
printf(“value of c”,c);
int c;
c=a+b;
return c;
4.No arguments and return values: When function has no arguments it does not receive any data
from calling function.It return data from the function.
Function1( ) No input
{ Function2( )
{
Function2( )
Function
} result
}
Example :
int add( );
main()
129
int c;
c=add( );
int add( )
int a,b;
scanf(“%d%d”,&a,&b);
c=a+b;
return c;
5.Function with return multiple values: This is a function return multiples data . If need to return
more than two variables then pass the variables by reference and returned through pointer.They
are not really retuned,but the effect is similar.
Function1( ) Function2( )
{ arguments {
Function2( )
datas Return( )
} }
Example :
#include<stdio.h>
void func(int *,int *);
int main()
{
int a=20,b=30;
130
func(&a,&b);
printf("%d %d\n",a,b);
return 0;
}
void func(int *x,int *y)
{
*x=*x-10;
*y=*y-10;
}
Output: 10 20
a) Call by value
b) Call by reference
Call by value:
In this calling technique pass the values of arguments which are stored or copied into the formal
parameters of functions. Hence, the original values are unchanged only the parameters inside
function changes.
void calc(int x);
int main()
{
int x = 10;
calc(x);
printf("%d", x);
}
void calc(int x)
{
x = x + 10 ;
}
Output : 10
131
In this case the actual variable x is not changed, because pass argument by value, hence a copy
of x is passed, which is changed, and that copied value is destroyed as the function ends(goes out
of scope). So the variable x inside main() still has a value 10.
But can change this program to modify the original x, by making the function calc() return a value,
and storing that value in x.
int calc(int x);
int main()
{
int x = 10;
x = calc(x);
printf("%d", x);
}
int calc(int x)
{
x = x + 10 ;
return x;
}
Output : 20
Call by reference:
In this, pass the address of the variable as arguments. In this case the formal parameter can be
taken as a reference or a pointer, in both the case they will change the values of the original
variable.
void calc(int *p);
int main()
{
int x = 10;
calc(&x); // passing address of x as argument
132
printf("%d", x);
}
void calc(int *p)
{
*p = *p + 10;
}
UNIT – IV
133
1.Distinguish between single dimensional and multidimensional arrays with suitable
examples.Nov’15
1. A list of items can be given in one variable 1. Three or more dimensional arrays are called
name using only one subscript and such a multidimensional arrays.
variable is called one dimensional arrays.
3. Example: Example:
int group[10]; int survey[3][5][12];
declares the group as an array to contain a Survey is a three dimensionsal array declared to contain
maximum of 10 integer values. 180 integer type values.
4. The declaration will reserve contiguous 4.Three-dimensional array can be represented as a series of
memory locations capable of storing an two dimensional arrays as shown below:
character type as shown below
‘W’ Year 1
‘E’ Month 1 2 …………….. 12
‘L’ City
1
‘C’
.
‘O’ .
‘M’ .
‘E’ .
‘\O’ .
5
5.Only one subscript is enough when 5.Many subscripts can be used,depend upon on the need of the
declaring the array dimension of the array.
134
2.Distinguish between structure and the union?Apr’14
STRUCTURE UNION
1.Structure is a collection of data elements 1.Union are derived datatype.union is similar to
of different type. structure but use the same location for all the members
of union.
2. The general format of structure 2. union tag-name
definition is {
struct tag-name data type member1;
{ data type member2;
data type member1; ------------ --------
data type member2; ------------ ---------
------------ -------- }
------------ ---------
};
3. Example: 3. Example:
struct book union item
{ {
char title[20]; int m;
char author[15]; float x;
int pages; char c;
float price; }code;
};
4. The above declaration a variable code 4. The above declaration contains a variable code of
of type structure book which contains four type union item which contains three members with
members with different data type.All the different data type. However only one of them can be
members can be used at a time. used at a time.
5.In the structure each of the members 5.In union whereas all of the members uses a single
use memory separately for all the shared memory location which is equal to the size of
members its largest data member.
135
3.How to pass a structure to a function?Explain with an example.APR’13
There are three methods to pass structure from one function to another.
1.To pass each member of the structure as an actual argument of the function call.The actual
arguments are then treated independently like ordinary variables.
2.Passing of a copy of the entire structure to the called function.Since the function working on a
copy of structure any changes to structure members with in function will not reflected in orginal
structure in the calling function.
3.To pass the structures as an argument the address of the structure is passed to the called
function.The function can access indirectly the entire structure and work on it.
The general format for sending a copy of structure to the called function is
Function-name(structure-variable-name);
136
{
……….
……….
return(expressions);
1.The called function must be declared for its type,appropriate to the data type it is return.
2.The structure variable used as actual argument and formal argument in the called function of
same struct type.
3.The return statement is necessary only when function is returning some data to the calling
function
Example :
#include<stdio.h>
#include<conio.h>
struct student
{
char name[10];
int roll;
};
void show(struct student st);
main()
{
struct student std;
clrscr();
printf("\nEnter student record\n");
printf("\nstudent name\t");
scanf("%s",std.name);
printf("\nEnter student roll\t");
137
show(std);
getch();
}
The function largest is defined with two arguments the array name and size of the array to specify
the number of elements in the array.
float array[ ];
The square brackets informs that it is not necessary to specify the size of the array
main()
int n;
int i;
138
for(i=0;i<n;i++)
scanf(“%f”,a[i]);
Dont't return an array from functions, rather return a pointer holding the base address of the array
to be returned. But must, make sure that the array exists after the function ends.
int* sum (int x[])
{
//statements
return x ;
}
int i,j,sum=0;
for(i=0;i<m;i++)
for(j=1;j<n;j++)
Scanf(“%d”,x[i][j]);
Sum =sum+x[i][j];
139
printf(“Average=%d”,sum);
getch( );
main()
Int m,n;
Two-dimensional (2D) arrays are indexed by two subscripts,one for the row and other for the
column.The simplest form of the multidimensional array is the two-dimensional array.
Example :
int a[3][4];
The above array can also be declared and initialized together. Such as,
int arr[][3] = {
{0,0,0},
{1,1,1}
};
Example:
#include<stdio.h>
#include<conio.h>
void main()
140
{
int arr[3][4];
int i,j,k;
printf("Enter array element");
for(i=0;i<3;i++)
{
for(j=0; j < 4; j++)
{
scanf("%d",&arr[i][j]);
}
}
for(i=0; i < 3; i++)
{
for(j=0; j < 4; j++)
{
printf("%d",arr[i][j]);
}
}
getch();
}
141
UNIT – V
1.Write a C program to sort a list of strings using pointers. NOV’13
(OR)
Write a C program to arrange the names in alphabetical order using pointer. APR’14
#include<stdio.h>
#include<string.h>
void main()
int i, j, n;
scanf("%d", &n);
gets(str[i]);
strcpy(temp, str[j]);
142
}
puts(str[i]);
2. Write a C program to sort the given set of n numbers using pointers. APR’12
#include <stdio.h>
#include <conio.h>
void main()
int *arr,i,j,tmp,n;
clrscr();
scanf("%d",&n);
for(i=0;i<n;i++)
scanf("%d",arr+i);
for(i=0;i<n;i++)
for(j=i+1;j<n;j++){
tmp = *(arr+i);
*(arr+i) = *(arr+j);
*(arr+j) = tmp;
143
}
printf("\n\nAfter Sort\n");
for(i=0;i<n;i++)
printf("%d\n",*(arr+i));
getch();
3. Write a C program to prepare pay bill for a company using files. NOV‘15
#include<stdio.h>
#include<stdio.h>
#include<conio.h>
#include<string.h>
Void main()
char name[20],design[20];
clrscr();
fp1=fopemn(“emp.dat”,”w”);
scanf(“%d”,&n);
for(i=0;i<n;i++)
144
scanf(“%s%s”,name,design);
fprintf(fp1,”\n%s %s”,name,design);
fclose(fp1);
fp1=fopen(“emp.dat”,”r”);
fp2=fopen(“empsal.dat”,”w”);
for(i=0;i<n;i++)
fscanf(fp1,”%s%s”,name,design);
if(strcmp(design,”manager”)==0)
Basicpay=15000;
HRA=3000;
DA=2000;
Basicpay=7000;
HRA=2000;
DA=1000;
Else
Basicpay=2000;
HRA=300;
145
DA=200;
totpay=basicpay+HRA+DA;
fpringf(pf2,”\n%s\t%s\t%d”,name,design,totpay);
fclose(fp1);
fclose(fp2);
getch();
Output:
Chandru manager
Charles cleark
Selvaam office
4. Write notes on :
(a) Operations in pointers.
(b) File handling functions in C. APR’16
(OR)
List and explain the important file handling functions in C with examples. APR’13
The arithmetic operations on pointer variable effects the memory address pointed by pointer.
Pointer Arithmetic Operations are
146
➢ Subtracting a number form a pointer.
➢ Incrementing a pointer.
➢ Decrementing a pointer.
Incrementing a Pointer
2. Incrementing Pointer Variable Depends Upon data type of the Pointer variable
ptr=ptr+1;
o/p
147
• This differs from compiler to compiler as memory required to store integer vary compiler
to compiler
"Incrementing a pointer increases its value by the number of bytes of its data type"
Decrementing a Pointer
Example :
Explanation :
This differs from compiler to compiler as memory required to store integer vary compiler to
compiler
148
Pointer Program : Difference between two integer Pointers
#include<stdio.h>
int main()
printf("\nDifference : %d",ptr2-ptr1);
return 0;
Output :
Difference : 250
Explanation :
Ptr1 and Ptr2 are two pointers which holds memory address of Float Variable.
Ptr2-Ptr1 will gives us number of floating point numbers that can be stored.
= 1000 / 4
= 250
we can add any integer number to Pointer variable. It is perfectly legal in c programming to add
integer to pointer variable.
int *ptr , n;
149
ptr = &n ;
ptr = ptr + 3;
#include<stdio.h>
int main()
ptr=ptr+3;
return 0;
Output :
Explanation of Program :
this line will store 1000 in the pointer variable considering 1000 is memory location for any of the
integer variable.
Formula :
= 1000 + 3 * (2)
= 1000 + 6
= 1006
we have subtracted “n” from pointer of any data type having initial addess as “init_address” then
after subtraction we can write
150
ptr = initial_address - n * (sizeof(data_type))
int *ptr , n;
ptr = &n ;
ptr = ptr - 3;
#include<stdio.h>
int main()
ptr=ptr-3;
return 0;
Output :
Formula :
= 1000 - 3 * (2)
= 1000 - 6
= 994
Subtracting Pointers
We can take difference between two pointer which returns the number of bytes between the address
pointed by both the pointers.
151
For example, if a pointer 'ptr1' points at memory location 10000 and pointer 'ptr' points at memory
location 10008, the result of ptr2 - ptr1 is 8.
1)fopen()
3) fseek()
4) fclose()
fopen()
FILE *fp;
Fp=fopen(“file name”,”mode”);
The fopen() function is used to open a file and associates an I/O stream with it. This function takes
two arguments. The first argument is a pointer to a string containing name of the file to be opened
while the second argument is the mode in which the file is to be opened. The mode can be :
‘r’ : Open text file for reading. The stream is positioned at the beginning of the file.
152
‘r+’ : Open for reading and writing. The stream is positioned at the beginning of the file.
‘w’ : Truncate file to zero length or create text file for writing. The stream is positioned at the
beginning of the file.
‘w+’ : Open for reading and writing. The file is created if it does not exist, otherwise it is truncated.
The stream is positioned at the beginning of the file.
‘a’ : Open for appending (writing at end of file). The file is created if it does not exist. The stream
is positioned at the end of the file.
‘a+’ : Open for reading and appending (writing at end of file). The file is created if it does not
exist. The initial file position for reading is at the beginning of the file, but output is always
appended to the end of the file.
The fopen() function returns a FILE stream pointer on success while it returns NULL in case of a
failure.
For eg,
FILE *p1,*p2;
P1=fopen(“data”,”r”);
P2=fopen(“results”,”w”);
size_t fwrite(const void *ptr, size_t size, size_t nmemb, FILE *stream);
The functions fread/fwrite are used for reading/writing data from/to the file opened by fopen
function. These functions accept three arguments. The first argument is a pointer to buffer used
for reading/writing the data. The data read/written is in the form of ‘nmemb’ elements each ‘size’
bytes long.
In case of success, fread/fwrite return the number of bytes actually read/written from/to the stream
opened by fopen function. In case of failure, a lesser number of byes (then requested to read/write)
is returned.
fseek()
The fseek() function is used to set the file position indicator for the stream to a new position. This
function accepts three arguments. The first argument is the FILE stream pointer returned by the
153
fopen() function. The second argument ‘offset’ tells the amount of bytes to seek. The third
argument ‘whence’ tells from where the seek of ‘offset’ number of bytes is to be done. The
available values for whence are SEEK_SET, SEEK_CUR, or SEEK_END.
fclose()
The fclose() function first flushes the stream opened by fopen() and then closes the underlying
descriptor.
5. Discuss in detail, opening and closing a data file with suitable examples. APR’15
A file represents a sequence of bytes, regardless of it being a text file or a binary file.
There are large numbers of functions to handle file I/O in C language. In this tutorial, you will
learn to handle standard I/O(High level file I/O functions) in C.
Text file
Binary file
We must open the file before we can write information to a file on a disk or read it. Opening a file
establishes a link between the program and the operating system. The link between our program
and Data Files :: the operating system is a structure called FILE which has been
defined in the header file “stdio.h”. When we use a command to open a file, it will return a pointer
to the structure FILE. Therefore, the following declaration will be there before openingthe file,
FILE *fp each file will have its own FILE structure. The FILE structurecontains information about
the file being used, such as its current size, its location in memory etc. Let us consider the following
Syntax:
Fp=fopen|(“filename”,”mode”);
The fopen() function is used to open a file and associates an I/O stream with it. This function takes
two arguments. The first argument is a pointer to a string containing name of the file to be opened
while the second argument is the mode in which the file is to be opened. The mode can be :
‘r’ : Open text file for reading. The stream is positioned at the beginning of the file.
‘r+’ : Open for reading and writing. The stream is positioned at the beginning of the file.
154
‘w’ : Truncate file to zero length or create text file for writing. The stream is positioned at the
beginning of the file.
‘w+’ : Open for reading and writing. The file is created if it does not exist, otherwise it is truncated.
The stream is positioned at the beginning of the file.
‘a’ : Open for appending (writing at end of file). The file is created if it does not exist. The stream
is positioned at the end of the file.
‘a+’ : Open for reading and appending (writing at end of file). The file is created if it does not
exist. The initial file position for reading is at the beginning of the file, but output is always
appended to the end of the file.
The fopen() function returns a FILE stream pointer on success while it returns NULL in case of a
failure.
Eg,
FILE *fp;
fp=fopen(“Sample.C,” “r”);
fp is a pointer variables. fopen() will oepn a file “sample.c” in ‘read’ mode, which tells the C
compiler that we would be reading the contents of the file.
2.Reading A file:
To read the file’s contents from memory there exists a function called
s=fgetc(fp);
fgetc() reads the character from current pointer position, advances the pointer position so that it
now points to the next character, and returns the character that is read, which we collected in the
variable s. This fgetc() is used within an indefinite while loop, for end of file.
While reading from the file, when fgetc() encounters this Ascii special character, instead of
returning the characters that it has read, it returns the macro EOF. The EOF macro has been defined
in the file
“stdio.h”.
When we finished reading from the file, there is need to close it.
155
3.Writing a file:
The function fputc() writes the character value of the argument c to the output stream referenced
by fp. It returns the written character written on success otherwise EOF if there is an error. You
can use the following functions to write a null-terminated string to a stream
The function fputs() writes the string s to the output stream referenced by fp. It returns a non-
negative value on success, otherwise EOF is returned in case of any error. You can use int
fprintf(FILE *fp,const char *format, ...) function as well to write a string into a file
4.Closing a file:
statement:
fclose(fp);
When an array is passed to function an argument only the address of the element of the array is
passed. When we pass addresses to a function the parameters receiving the address should be
pointers. The process of function using pointers to pass the addresses of variable is known as call
by reference.
Eg,
Void main()
Int x;
X=20;
156
Change(&x);
Printf(“\n X=%d”,X);
Change(int *p)
*p=*p+10;
Output:-
X=30
Array hold an integer , float, character elements , the array can store pointers. Since a pointer
always contains an address , an array of pointers would be nothing but a collection of address. The
address present in the array of pointers can be addresses of isolated variable or address of array
elements or any other address.
Eg,
char *name[3]={
"Adam",
"chris",
"Deniel"
};
char name[3][20]= {
"Adam",
"chris",
"Deniel"
157
};
158