Professional Documents
Culture Documents
ON
COMPUTER PROGRAMMING
2018 – 2019
SYLLABUS
I B. Tech – I Semester: Common for All Branches
2 2 - 3 30 70 100
Practical Classes:
Contact Classes:34 Tutorial Classes:34 Total Classes:68
Nil
Objectives:
Statements: Selection Statements, Iteration Statements, Jump statements: Break, Continue, goto,
Arrays: Accessing Array Elements, Single & Multi Dimensional Arrays.
Strings: Declaring, Initialization of a String, Reading and Writing Strings, String manipulation
functions from the standard Library, String I/O Functions: gets(), puts().
Pointers: Pointer Variables, Pointer Expressions, Pointers And Arrays, Pointers to Strings. Problems
with Pointers.
Functions: Definition, Function Call- Call by Value, Call by Reference, Storage Class Specifiers,
Understanding the scope of Functions with its Types, the Return Statement, Recursion, C’s Dynamic
Allocation Functions.Command Line Arguments.
Structures and Unions: Accessing structure members, Array of structures, Passing Structures to
Functions, Structure Pointers, Structures within Structures, Bit Fields, Enumerations, Typedef.
Streams and File, File System Basics: File pointer, opening a file using fopen(), closing a file, getc(),
putc(), fclose(), feof(), fputs, fgets(), ferror(), fread(), fwrite(), fseek(), Formatted Console I/O:
fprintf, fscanf, the Preprocessor Directives: #define and #include.
Text Books:
1. https://www.tutorialspoint.com/cprogramming/
2. www.studytonight.com/c/
3. fresh2refresh.com/c-programming/
4. www.cprogramming.com/tutorial/c/
E-Text Books:
1. bookboon.com/en/c-cpp-csharp-ebooks
2. electronicsforu.com › Resources › Cool Stuff
3. https://en.wikibooks.org/wiki/C_Programming
4. www.e-booksdirectory.com › Computers & Internet
Introduction to Computers:
Definition of Computers:
The word computer has been derived from the word “Compute” which means to
calculate.
It is an electronic device which inputs the data, stores the data, processes the data
and gives the result accurately at a very high speed according to the instructions
provided.
Characteristics of computers:
The following are the some of the characteristics of a typical computer.
Speed:
Computer operates at very high speed.
Even the speed of slowest personal computer is very high as compared to that of a
human being.
There are several different types of computers they have different speeds ranging
from high to very very high.
The speed of the computer is specified in “Million Instructions Per Second” {MIPS}
Accuracy:
It performs with a degree of high consistent accuracy.
The degree of accuracy of a particular computer depends upon its design.
Each and every calculation is performed with same accuracy.
Errors may occur in computer due to either undetected error in the design (or) it they
aren‟t programmed properly.
Storage and Retrieval of data:
A computer can store huge amount of data in its memory.
We can store any type of data such as letters, pictures, sounds etc in a computer.
We can also retrieve the stored data from the computer as per the user requirement.
The information can be stored in computers memory for several years.
Resource Sharing:-
CPU
ALU
ALU
Input MU Output
CU
Input Unit:
Computers need to receive data and instructions in order to solve any problem.
The input unit consists of one or more input devices like keyboard, mouse,
joystick etc.
Regardless of the type of the input device used in a computer system, all input
devices perform the following functions.
o Accept the data
o Convert data to computer understandable form.
o Supply converted data for further processing.
CPU:
CPU stands for “Central Processing Unit.”
CPU is like a computer Brain. It performs the following operations.
o It performs all calculations.
o It takes all decisions.
o It controls all units of computer.
Control unit, Memory unit and Arithmetic logic unit of the computers are together
known as central processing unit.
Memory Unit:
Memory Unit of the computer holds data and instructions that we enter through
the input unit.
INTRODUCTION TO PROGRAMMING:
As programmer prefer to write their programs in one of the High Level Languages
{HLL} because it is much easier to understand the code easily.
However, the computer doesn‟t understand any language other than “Binary
Language.” It becomes necessary to process a HLL program me so as to make it
understandable to the computer.
The system program which performs the above job is called language processors.
Assembler, Interpreter and Compliers are some of the language processors.
Assembler:
The code written by the user in order to perform a task is called source code.
ALGORITHM:
Algorithm is a very popular technique used to obtain solution for a given problem.
Definition: - An algorithm is defined as a finite set of steps for solving a problem.
Procedure for writing an algorithm:-
An Algorithm is a well organized and textual computational module
that receives one or more input values and provides one or more output values.
These well defined steps are arranged in a sequence that processes given input
into output.
The steps of the algorithm are written using English like statements which are
easy to understand.
This will enable the reader to translate each step into a program.
Every step is known as instruction.
If the procedure is lengthy then sub divided the procedure into small parts as it
make easy to solve the problem.
Analyzing an Algorithm:-
When one writes an algorithm, it is essential to know how to analyses the
algorithm.
Analyzing the algorithm refers to calculating the resources such as usage of
computer memory, processing time and so on …..
Time is most important resource because the program developed should be
faster in processing.
The analysis can also be made by reading the algorithm for logical accuracy,
tracing the algorithm and checking with the data.
Sequence
The steps described in an algorithm are performed successively one by one without
skipping any step.
The sequence of steps defined in an algorithm should be simple and easy to
understand.
Example:
// adding two timings
Step 1: start
Step 2: read h1, m1, h2, m2
Step 3: m=m1+m2
Step 4: h= h1 + h2 + m/60
Step 5: m=m mod 60
Step 6: write him
Step 7: stop
Selection
We understand that the algorithms written in sequence fashion are not reliable.
There must be a procedure to handle operation failure occurring during execution.
The selection of statements can be shown as follows
if(condition)
Statement-1;
else
Statement-2;
The above syntax specifies that if the condition is true , statement-1 will be
executed otherwise statement-2 will be executed.
Iteration
In a program, sometimes it is very necessary to perform the same action for a
number of times.
If the same statement is written repetitively, it will increase the program code.
To avoid this problem, iteration mechanism is applied.
The statement written in an iteration block is executed for a given number of times
based on certain condition.
Example:
Step 1 : start
Step 2 : read n
Step 3 : repeat step 4 until n>0
Step 4 : (a) r=n mod 10
(b) s=s+r
(c) n=n/10
Step 5 : write s
Step 6 : stop
FLOWCHART
Introduction:-
A flowchart is an alternative technique for solving a problem.
Instead of descriptive steps, we use pictorial representation for every step.
Definition:-
Flowchart is a diagrammatic or pictorial representation of various steps
involved in the Algorithm.
Start/Stop
Decision
Connector
Process
Input/output
Loop
Predefined Process
System Requirements
Problem should be explained clearly with required input/output
and objectives of the problem. It makes easy to understand the problem to be solved.
Thus system requirement is always the first step towards development of a program.
Analysis
Analysis is the first technical steps in the program development process. To
find a better solution for a problem analyst must understand the problem statement
objectives and required tools for it.
Design
Designing phase will begin after the software analysis process. It is a multi
step process. Mainly it focuses on data, architecture, user interfaces, and program
components.
The importance of the designing is to get the quality of the product.
Developing code
New system will be implemented based on the designing part. It
includes coding and building of ne software using a programming language and
software tools.
INTRODUCTION TO C LANGUAGE
Documentation Section
Preprocessor Directives
Global Declarations
Other functions as required
int main ()
{
Local Declarations;
Statements;
Documentation Section:
In general documentation section consists of information about the program. It
contains details like author of the program, task of the program, date compiled, date
written ,etc .
All the above information is placed as comments.
Preprocessor Directives:
This section provides the instructions to the compiler about library functions by
linking to various header files.
Eg: #include <stdio.h>
#include <conio.h>
#define PI 3.14
Global Declaration:
When a variable is declared inside a function the variable scope is within that
function only. These variables are called local variables.
If we want to make a variable available throughout the program irrespective of the
function then the variable is declared as global.
Any variable declared above the main function is considered as “global variables”.
main ():
Every „C‟ program execution starts at main().
Every program must include main().
The entire „c‟ program instructions are divided in to two parts namely
o Declarations
o Executable statements
Local Declarations:
Any variable which is used in the program should be declared first. „C‟ program
doesn‟t allow to declare the variables at the middle of the program.
Statements:
It contains various executable statements that perform a specific task.
The above two parts must be placed in a pair of braces ({ and }).
Note that each and every statement in a „c‟ program must end with semicolon
except the pre-processor statements.
C LANGUAGE ELEMENTS
Do if static While
Variable:
A variable is an identifier that is used to represent a data item.
The data may be numerical quantity (or) a character constant.
The data item must be assigned a value to the variable at some point in the
program. Then data item can be accessed by referring to the variable name
In other words, a variable is an identifier which changes its value during the
execution of the program.
Rules for Constructing a Variable:
A variable name is a combination of alphabets, digits and underscore.
Other than the underscore no special characters is allowed.
The first character in the variable name must be an alphabet.
The variable name should not be of keyword.
Declaration of a Variable:
Any variable which is used in the program should be declared first. A declaration of
a variable specifies two things:
o It tells the compiler about the name of the variable.
o It specifies about the type of data that a variable can hold.
Syntax: data type variable 1, variable 2 , . . . . . . . . variable;
Eg: int a, b, c;
The above declaration results in declaring the variables a, b, c as integer data type.
DATA TYPES
Data Types
Functions
Charater
Enum Structures
Float
Pointers
Double
Unions
Primary
Data Type Size (in bytes) Range
int 2 -32768 to 32767
unsigned int 2 0 to 65535
signed 2 -32768 to 32767
short 2 -32768 to 32767
unsigned short 2 0 to 65535
signed short 2 -32768 to 32767
long 4 -2147483648 to 2147483647
unsigned long 4 0 to 4294967295
signed long 4 -2147483648 to 2147483647
char 1 -128 to 127
unsigned char 1 0 to 255
signed char 1 -128 to 127
float 4 3.4E-38 to 3.4E +38
double 8 1.7E -308 to 1.7E +308
long double 10 34E -4932 to 34E +4932
Note:
Float is a single precision value. {After decimal 7 digits has been considered}
Double is a double precision value. {After decimal 14 digits has been considered}
In-Built data Types are supported by „C‟ compiler by default.
Description: It is used to store real number, with single precision floating point number
(precision of 6 digits after decimal points.)
Storage space: 4 bytes.
Format: %f
Range of values: -3.4*1038 to +3.4*1038.
Description: It stores real numbers with double precision. The use of double doesn't
guarantee to double the number of significant digits in our result, but it improves the
accuracy of the arithmetic and reduces the accumulation of rounding errors.
Storage Space: 8 bytes.
Format: %ld
Range of values: -1.7*10308 to +1.7*10308.
void:
It is a special data type used for
o To specify that a function doesn‟t returns any value.
o To specify a function takes no arguments.
o To create generic pointers.
Eg: 1. void print (void)
3. void *ptr
Constants:
These are fixed values that will not change during the execution of program.
Constants
Numeric character
Integer Constant:
An integer constant is an integer valued numbers.
Character Constants:
Arithmetic Operators:
Arithmetic operators are basic and common operations performed using and
computer language.
There are five arithmetic Operators available in „C‟. They are
+ Addition a+b
- Subtraction a-b
* Multiplication a*b
/ Division a/b
% Modular Division a%b
Write a program to use various relational operators and display their return
values?
#include<stdio.h>
#include<conio.h>
void main()
{
clrscr();
printf("\condition\t:Return values\n");
printf("\n10!=10\t\t:%5d",10!=10);
printf("\n10==10\t\t:%5d",10==10);
printf("\n10>=10\t\t:%5d",10>=10);
printf("\n10<=100\t\t:%5d",10<=100);
Logical Operator:
When we want to take a decision basing on 2 (or) more conditions then we will use
logical operators.
There are three logical operators available in „C‟
Operator purpose
&& Logical AND
|| Logical OR
! Logical NOT
Truth Table:
A B A&B
T T T
T F F
F T F
F F F
Logical Or: (||)
Logical Or results in true if either of the conditions is true.
The result is false if all the conditions are false.
Truth Table:
A B A||B
T T T
T F T
F T T
F F F
Logical not: (!)
Truth Table:
A !A
T F
F T
Examples:
8>6&&6<10 true (1)
9>4||7<3 true (1)
8! =8 false (0)
10! =9 true (1)
#include<stdio.h>
#include<conio.h>
void main()
{
clrscr();
printf("condition : Return values\n");
printf("\n9>5&&8<10:%5d",9>5&&8<10);
printf("\n10<9&&3>7:%5d",10<9&&3>7);
printf("\n9>6||6<2 :%5d",9>5||8<3);
printf("\n8!=8 :%5d",8!=8);
printf("\n9!=10 :%5d",9!=10);
getch();
Assignment Operators:
This operator is used to assign a constant value (or) the result of an expression to a
variable.
Explanation:
In above expression-1, c= ++a two operations namely assignment and increment
are involved. Since the operator ++ is used as prefix, first we perform incrimination
i.e., a=a+1 and then this value is assigned to „C‟.
In the expression-2, c= a++ two operations namely assignment and increment are
involved. Since the operator ++ is used as postfix, first we assign the value of „a‟ to
„c‟. i.e., c=a => a=5 and then the value of „a‟ is incremented i.e., a=a+1=6
Bitwise Operators:
Bitwise operators are one of the salient features of „C‟ language.
These are specially designed to manipulate the data at Bit level.
The Bitwise operators are not applicable for float (or) Double data type.
The following are the some of the Bit wise operators available in „C‟ language.
Operator Meaning
Special Operators:
In addition to the above operators „C‟ language supports some special operators
like comma operator, parenthesis for grouping expression, membership operators.
Comma Operator:
This operator is used to link the related expression together the
expression is separated by the, operator.
e.g.: a=(x=6,y=7,x+y);
This expression first assigns 6 to x and 7 to y then assigns (6+7) to a.
Size of Operator:
The size of operator returns a number of bytes the operand occupies in memory.
The operand may be a variable, a constant or a data type qualifier. It is a compile
time operator.
Syntax: sizeof(operand)
e.g.: y=sizeof(int); here value of y will be 2bytes
z=sizeof(a);her value of z depends on data type of a
Member operator:
These are used to access member of structures and unions.
e.g.:
var member 1;
When var is a structure variable.
var member 2;
When var is pointer to structure variable.
Type Conversion:
In some situations, some variables are declared as integers and while performing
an operation on these variables we require the result as floating point type. In such
situations we use type conversion.
The type conversion is used to convert the set of declared data types to some other
required types.
Conversion can be carried out in 2 ways
o Converting by using assignment (Implicit casting).
o Using cast operator (Explicit casting).
Converting by Assignment:
The usual way of converting a value from one data type to another is by using
the assignment operator.
int a;
float b;
a=b;
In this method, if a larger data type value is assigned to smaller data type then the
value will be truncated {cut off}. This method is called “Narrowing”.
Cast Operator:
The cast operator is a technique to forcefully to convert one data type to another.
The operator used to force this conversion is known as “Cast Operator” and the
process is known as type casting.
Expressions:-
Primary Expressions
In C, the operand in the primary expression can be a Name, a Constant, or an
Parenthesized Expression. Name is any identifier for a variable. A constant is the one
whose value cannot be changed during program execution. Any value enclosed within
parenthesis must be reduced to single value. A complex Expression can be converted
into primary expression by enclosing it with parenthesis. The following is an example
(3*5+8) ; (c=a=5*c);
Postfix Expressions
The postfix expression consists of one operand and one operator.
Example: A Function Call, The function name is operand and parenthesis is the
operator.
The other examples are post increment and post decrement. In post increment
the variable is increased by 1, a++ results in the variable increment by 1.
Similarly in post decrement, the variable is decreased by 1, a--results in the
variable decreased by 1.
Prefix Expressions
Prefix Expressions consists of one operand and one operator, the operand
comes after the operator.
Examples of prefix expressions are prefix increment and prefix decrement i.e.,
++a,--a.
The only difference between postfix and prefix operators is, in the prefix operator, the
effect take place before the expression that contains operators is evaluated. It is other
way in case of postfix expressions
Unary Expressions
Simple if statement.
Syntax:
if (condition is true)
{
Statement;
}
#include<stdio.h>
#include<conio.h>
void main( )
{
int m,n;
clrscr( );
printf(“Enter any two number:\n”);
scanf(“%d %d”,&m,&n);
if(m-n==0)
printf(“ the entered numbers are equal \n”);
getch( );
}
Output:
Enter any two number 50 50
You have entered numbers are equal
if – else statements.
The if-else statement is an extension of the if statement. The if-else
statement takes care of true as well as false conditions. It has two blocks.
#include<stdio.h>
#include<conio.h>
void main( )
{
int age;
clrscr( );
printf(“Enter candidate age :\n”);
scanf(“%d”,&age);
Enter age: 16
Not Eligible for voting
2. Write a program to determine whether a given value is positive or negative?
#include<stdio.h>
#include<conio.h>
void main()
{
int num;
clrscr();
printf("Enter a number");
scanf("%d",&num);
if(num>0)
{
printf("\n%d is a positive number",num);
}
else
{
printf("%d is a negative number",num);
}
getch();
Output:
Enter a number -9
-9 is a negative number
Enter a number 67
67 is a negative number
Syntax:
if(condition)
{
if(condition)
{
Statement-A;
}
else
{
Statement-B;
}
}
else
{
Statement-C;
}
Statement-x;
#include<stdio.h>
#include<conio.h>
void main()
{
int x,y,z;
clrscr();
printf("\nEnter the values of x,y,z");
scanf("%d %d %d",&x,&y,&z);
printf("\n Largest out of three numbers is:");
if(x>y)
{
if(x>z)
{
printf("x=%d\n",x);
}
else
{
Syntax:
if(condition-1)
Statement-1;
else if(condition-2)
Statement-2;
else if(condition-3)
Statement-3;
else if(condition-n)
Statement-n;
else
Default statement;
Statement-x;
AVERAGE RESULT
< 40 FAIL
>=40 & <50 THIRD CLASS
>=50 & <60 SECOND CLASS
>=60 & <75 FIRST CLASS
>=75 & <100 DISTINCTION
#include<stdio.h>
#include<conio.h>
void main()
{
int sum=0,tel,eng,math,hin,pys,chem;
float avg;
clrscr();
printf("\n Enter marks\nTelugu:\nEnglish:\nMaths:\nHindi:\nPhysics:\nChemistry:\n\n");
scanf("%d%d%d%d%d%d",&tel,&eng,&math,&hin,&pys,&chem);
Total: 478
Average: 79.00
Result: Distinction
Case control or switch statement
The Case control statements allow the computer to take
decision as to be which statements are to be executed next.
Write a program to convert years into Minutes, Hours, Days, Months, and
Seconds using switch statements.
#include<stdio.h>
if(ch>0&&ch<6)
{
printf("Enter years:");
scanf("%ld",&yrs);
}
mon=yrs*12;
ds=mon*30;
ds=ds+yrs*5;
hrs=ds*24;
min=hrs*60;
se=min*60;
switch(ch)
{
case 1:
printf("\n MINUTES:%ld",min);
break;
case 2:
printf("\n Hours:%ld",hrs);
break;
case 3:
printf("\nDays:%ld",ds);
break;
case 4:
printf("\n Months:%ld",mon);
break;
case 5:
printf("\n seconds:%ld",se);
Output:
[1]MINUTES
[2]HOURS
[3]DAYS
[4]MONTHS
[5]SECONDS
[0]EXIT
Enter your choice: 2
Enter years: 1
Hours: 8760
Iteration Control Statements also called as Repetition or Loop Control Statements. This
type of statements helps the computer to execute a group of statements repeatedly.
This allows a set of instruction to be performed until a certain condition is reached.
What is a loop?
A loop is defined as a block of statements which are repeatedly executed
for certain number of times.
There are three types of loops in C:
1. for loop
2. while loop
3. do-while loop
Syntax:
for (variable initialize; check condition; modify counter)
{
statements 1;
-----------;
-----------;
statements n;
}
Explanation:
1. The initialization is usually an assignment that is used to set the loop control variable.
2. The condition is a relational expression that determines when the loop will exit.
3. The modify counter defines how loop control variables will change each time the loop
is repeated.
These three sections are separated by semicolon (;).
The for loop is executed as long as the condition is true. When, the condition
becomes false the program execution will resume on the statement following the
block.
Advantage of for loop over other loops:
All three parts of for loop (i.e. counter initialization, check condition,
modification
of counter) are implemented on a single line.
#include<stdio.h>
#include<conio.h>
void main( )
Output:
CREC1
CREC2
CREC3
CREC4
CREC5
Explanation of the program:
The o/p will be C R E C 1 time, 2times till 5 times.
#include<stdio.h>
#include<conio.h>
void main()
{
int i,c=0;
clrscr();
for(i=0;i<=15;)
{
i++;
printf("%3d",i);
i=i+1;
printf("%3d",i);
c++;
}
printf("\n The body of the loop is executed for %d times",c);
getch();
}
while loop
It is a primitive type looping control because it repeats the loop a fixed no. of
time. It is also called entry controlled loop statements.
Syntax:
while (test condition)
{
body of loop
}
Explanation:
The test condition is evaluated if the condition is true, the body of loop will be
executed.
#include<stdio.h>
void main()
{
int n,d,x=1;
int i;
clrscr();
printf("Enter the number of digits:-");
scanf("%d",&d);
printf("\nEnter the number which is to be reversed:");
scanf("%d",&n);
printf("\n the reversed number is :-");
while(x<=d)
{
i=n%10;
printf("%d",i);
n=n/10;
x++;
}
getch();
}
syntax:
do
{
body of loop;
}
while (test condition);
Explanation:
It first executes the body of the loop, and then evaluates the test condition.
If the condition is true, the body of loop will executed again and again until the condition
becomes false.
#include<stdio.h>
#include<math.h>
void main()
{
int y,x=1;
clrscr();
printf("\nPrint the numbers and cubes");
printf("\n");
do
{
y=pow(x,3);
printf("%5d %27d\n",x,y);
x++;
}
while(x<=10);
getch();
}
Output:
Note: We should try to avoid using goto as far as possible because, it is not good for
readability of the program or to improve the program execution speed.
To Process such large amounts of data, we need a powerful data type that
would facilitate efficient storing, accessing and manipulation of data items. Array is a
secondary or Derived Data type
At some important areas the concept arrays are used
To maintain list of employees in a company.
In pharmacy to maintain list of Drugs‟ and their cost.
To maintain test scores of a class of students.
Def: An array is a collection of elements of the same data type and it can be referred
with a single name.
OR
Def: An array is fixed –size sequence collection of elements of the same data type.
Array Declaration:
Arrays are defined in the same manner as ordinary variables, except that
each array name must be accompanied by the size specification.
The general form of array declaration is:
Syntax:
data type array –name [size];
Data type specifies the type of array; size is a positive integer number or symbolic
constant that indicates the maximum number of elements that can be stored in the
array.
E.g. float kick [50];
This declaration declares an array named height containing 50 elements of type
float.
Here 50 is an integer enclosed in brackets is the array subscript, and its value
range from zero to one less than the number of memory cells in the array.
Above statement instructs the compiler to associate 50 memory cells with the
name kick, these cells will be adjacent to each other in memory. The memory
format as fallows
Initialization of Arrays:
The elements of array are initialized in the same way as the ordinary
variables.
Syntax:
data type array-name [size]={list of elements};
From the above statements the array -name „y‟ elements are stored in memory as
follows.
Compiler will allocates two bytes of space for each array elements, totally 4 bytes of
space is allocated for array name y.
Array Subscripts:
#include<stdio.h>
#include<conio.h>
void main()
{
int marks[50],i,sum=0,average,count=0;
clrscr();
printf("Enter the Student marks");
for(i=0;i<5;i++)
{
scanf("%d",&marks[i]);
sum=sum+marks[i];
}
average=sum/5;
for(i=0;i<5;i++)
if(marks[i]>average)
count++;
printf("No of students who scored more than average marks:%d",count);
getch();
}
Output:
Enter the Student marks:
96 56 86 76 36
No of students who scored more than average marks: 3
An array can be of
1. One dimensional array.
2. Two dimensional arrays.
3. Multi dimensional arrays.
Write a program to print space required for storing them in memory using arrays.
#include<stdio.h>
void main()
{
int i[9];
char j[95];
long l[7];
clrscr( );
printf("%d location for i\n",sizeof(i));
printf("%d location for j\n",sizeof(j));
printf("%d location for l\n", sizeof(l));
getch( );
}
Output:
18 locations for i
95 locations for j
28 locations for l
Write a program to arrange the numbers in increasing and decreasing order using
loops.
#include<stdio.h>
#include<math.h>
void main()
{
int i,j,sum=0,a[10];
clrscr();
printf("Enter ten numbers");
for(i=0;i<10;i++)
{
scanf("%d",&a[i]);
sum=sum+a[i];
Syntax:
datatype array-name [row- size] [column- size];
For example a two dimensional array consisting of 5 rows and 3 columns. So the
total number of elements which can be stored in this array are 5*3 i.e. 15
Syntax:
Data-type array-name [row-size] [column-size] = {{row1 list}, {row2 list},
…………. {row n
list}};
Output:
<----------ADDITION OF TWO MATRICES------------>
1 2 3
4 5 6
7 8 9
1 2 3
4 5 6
7 8 9
2 4 6
8 10 12
14 16 18
STRINGS
From above statement “name” is char type and size is 7, but assigned
string “TITANIC” has 6 characters 7 th is null characters. That is you must leave an extra
space for null characters, when we deal with character strings.
The „c‟ compiler inserts the null (\0) character automatically at the end of the string
so initialization of null character is not essential.
Output:
The scanf( ) and printf( ) functions are used to read and print string
respectively for formatted input and output.
scanf( ) function:
The familiar input functions scanf() can be used with „%s‟ format specification to
be read in a string of characters.
Syntax:
char name [25]= {“POKIRI”};
scanf (“% s”, name);
To read string, ampersand (&) is not required before the string variable. The
name of the string itself acts as a base address.
To eliminate the disadvantage of using a „scanf‟ function to read a line we use
getchar() or gets( )functions.
getchar( ): This function reads string character by character until terminating
condition is satisfied .
gets( ): This function reads the entire line of text.
E.g:
char m[30];
gets(m);
The commonly used output function is printf().The function can also be used for
writing string, but „% s‟ should be used as format specification.
E.g.:
char name [30] =”chadalawada”;
printf (“%s”, name);
Here the output produced will be chadalawada.
We are going to use as output functions puts (),putchar().
Puts( ):
This function prints line on the screen.
Syntax:
char name [30] =”chadalawada”;
puts(name);
#include<stdio.h>
#include<conio.h>
#include<string.h>
void main( )
{
char a[10];
clrscr();
gets(a);
printf("\n");
puts(a);
printf("%0.5s\n",a);
printf("%0.3s\n",a);
printf("%-7.4s\n",a);
printf("%+7.4s\n",a);
getch();
}
Output:
TITANIC
1. strlen( ):
Determines the length of string that is it counts the no. of characters in a given
string.
Syntax:
strlen (string);
#include<stdio.h>
2. Strcpy ( ):
This function copies the contents of one string to another.
Syntax:
Strcpy(string1,string2);
#include<string.h>
void main()
{
char a[10],b[10];
clrscr();
printf("Enter the string A:");
gets(a);
printf("Enter the String B:");
gets(b);
strcpy(a,b);
printf("After string copy a=%s\n",a);
printf("After string copy b= %s",b);
getch();
}
3. Strncpy ( );
This function performs same as strcpy( ).The only difference is that this
function copy string to string with specified length.
Syntax:
strncpy(string1,string2,n);
Output:
4. Strcat ( )
This function appends the target string to source string. Concatenation of
two strings can be done using this function.
Output:
Syntax:
Strncat(string1,string2,n);
Where,‟n‟ is the number of character to append.
#include<string.h>
void main()
{
char x[10],y[10];
int n;
clrscr();
printf("Enter the string x and y ");
scanf("%s %s",x,y);
Output:
Enter the string x and y TIRUPATHY TIRUMALA
Enter the length 4
TIRUPATHYTIRU
6.Strcmp ( )
This function compares two strings with case. The characters of the strings
must be in lower case (or) uppercase .If the strings are same it returns “Zero”, other
wise 1(non zero).
Syntax:
Strcmp(string1,string2);
#include<string.h>
void main()
{
char a[10];
char b[10];
int d;
clrscr();
printf("Enter the string a:");
scanf("%s",a);
printf("Enter the string b:");
scanf("%s",b);
d=strcmp(a,b);
if(d==0)
printf("Two Strings are identical ");
else
printf("Different");
Output:
Enter the string a: Rajesh
Enter the string b: Ramu
Different
POINTERS
Def:
pointer is a variable which stores address of another variable.
Or
Pointer is variable which stores address of a variable.
Or
A pointer is a memory variable that stores a memory address.
Pointers are widely used in programming; they are used to refer to memory location of
another variable without using variable identifier itself.
To declare pointer variable we need to use * operator (indirection/dereferencing
operator) before the variable identifier and after data type.
Pointer can only point to variable of the same data type.
The pointer variable is needed to store the memory address of any variable.
The pointer is denoted by (*) asterisk symbol.
It is also called “Indirection/Deference operator”.
By using pointer variable always we can store address only, not values i.e.
directly we don‟t assign a value to pointer variable.
By using ordinary variable only we can directly assign a value.
Declaration and Initialization
Pointer variables are declared in the same way as normal variables. But pointers
must declared along „*‟ operator.
Syntax:
Data type * variable –name;
E.g.:
int * n;
Hear n is a pointer variable of type variable of type integer, and it tells to
compiler that it holds the address of any integer variable only.
#include<stdio.h>
#include<conio.h>
main()
{
int u=3;
int v;
int *pu;
int *pv;
clrscr();
pu=&u;
v=*pu;
pv=&v;
printf("\n u=%d &u=%u pu=%u *pu=%d",u,&u,pu,*pu);
printf("\n\n v=%d &v=%X pv=%X *pv=%d ",v,&v,pv,*pv);
getch();
}
Output:
Output:
Addition a+b= 35
sub a-b=15
Product a*b=250
Division a/b=2
a mod b=5
Array name by itself is an address or pointer. it points to the address of the first element
(0th element of array).The element of the array together with their addresses can
displayed by using array name itself. Array elements are always are always stored in
contiguous memory locations.
in the above figure we have taken 3 array elements i.e array[3]={0,1,2}, in the second
line we have directly assigned array to the pointer variable without using ampersand
operator.
*ptr is pointing to array[0] th element and by incrementing the pointer variable we can
access the array[1],array[2] elements.
Here is an example program to explain the one dimensional array
Therefore if x is a one dimensional array, then the address of the first element can be
expressed as either &x[0] or simply as x.
The address of the second array element can be written as either &x[1]or as (x+1), and
so on…
In general the address of array element (i+1) can be expressed as either &x[i] or as
(x+i). thus we have two different ways to write the address of any array element.
#include<stdio.h>
#include<conio.h>
void main()
{
static int x[10]={10,11,12,13,14,15,16,17,18,19};
int i;
clrscr();
for(i=0;i<=9;i++)
{ /* dispaly an array eleemnt */
printf("\n i=%d x[i]=%d *(x+i)=%d\n",i,x[i],*(x+i));
/* display the corresponding array address*/
printf(" &x[i]=%X x+i=%X ",&x[i],(x+i));
}
getch();
}
This program defines a one dimensional, 10- element integer array x, whose elements
are assigned the values 10,11,12,13,…19.here the value of each element is specified in
two different ways as x[i] and as *(x+i), in order to illustrates their equivalence .
Similarly the address of each array element is specified in two different ways as &x[i]
and as (x+i).
The output clearly illustrates the distinction between x[i], which represents the value of
the ith array element , and &x[i], which represent its address.
Similarly the value of the ith array element can be represented by either x[i] or *(x+i),
and the address of the ith element can be represented by either &x[i] or x+i
Pointer to Strings
In this example
#include<stdio.h>
int main()
{
int i;
for(i=0;i<4;i++)
printf("String %d : %s\n",i+1,(*ptr)[i]);
return 0;
}
Output :
String 1 = C
String 2 = C++
String 3 = Java
String 4 = VBA
Problems with pointers
When a pointer is used incorrectly, or contains the wrong value, it can be a very difficult
to bug to find. To help you avoid them, a few of the more common errors are discussed
here.
Syntax:
Return-type func-name(datatype arg1,datatype arg2 ,………..datatype argn)
{
Local variables;
Executable_stmt 1;
Executable_stmt 2;
----------------
-----------------
V. SambaSiva., Assistant Professor, Department of CSE, CREC. 80
return (expression);
}
e.g:
int sum(int a, int b)
{
int s;
s=a+b;
return(s);
}
Func- name:
Each function is recognized by its name. In the given examples „sum‟ is a
function name. It follows of an identifier.
Arguments:
The arguments in function are always variables. They can be declared in
two ways as shown in format and format 2.
Return statement:
It can be written in two ways depending on the requirements.
return (expression);
Or
return;
return (expression):
This statement returns the value of expression to be called function.
E.g: return (a, b)
return (a);
return:
This specifies returns control to calling function but not return any value. There
can be any number of return statements in the program but each statement can return
only one value.
If no value is returned to the calling function then the return type is declared as
void.
Function call:
The statement which is used to call a function is called as “function
call”.
Function declaration:
All identities in „c‟ need to be declared before they are used .This is
true for functions as well as variables, for function the declaration needs to be done
before the function call.
e.g:
void main()
{
void greet ();
greet ();
}
void greet ( )
{
printf(“Happy New Year”);
}
Actual Parameters:
The parameters which are passed in function call are known as
actual parameters. They are defined in calling function and they can be expressions,
constants or variables.
Formal parameters:
The parameters which are used in function defined are called formal
functional parameters.
Formal parameters can only be variables. They can not be expressions or
constants.
The value of actual parameters is passed to formal parameters.
Void main( )
{
Statements;
function (a1,a2,………..an);
Statements;
Call by values:
The process of passing the actual values of variables is known as “call by
values”.
#include<stdio.h>
int sum(int,int);
void main()
{
int a=10,b=20,c;
c=sum(a,b);
printf("sum of 2 no is %d",c);
}
int sum(int x,int y)
{
int z;
z=x+y;
return(z);
}
Call by reference:
The process of calling a function using pointers to pass the address of
variables is known as “call by reference”.
#include<stdio.h>
void main()
{
int x,y;
int swap(int,int);
printf(“enter x,y values\n”);
scanf(“%d%d”,&x,&y);
Example program.
#include<stdio.h>
void fun();
void main()
{
auto int a,b;
a=5;
#include<stdio.h>
void main()
{
register int j=1;
do
{
printf("%d",j);
j++;
}
while(j<=10);
}
Output:
1 2 3 4 5 6 7 8 9 1
Example program
#include<stdio.h>
void main()
{
static int b;
int a;
clrscr();
printf("a=%d,b=%d",a,b);
getch();
}
Output:
a=2654 b=0
To define a variable as extern storage class the key word extern is used.
#include<stdio.h>
void sum( );
void main()
{
sum( );
getch();
}
void sum()
{
int a=10,b=20,c;
c=a+b;
#include<stdio.h>
int sum();
void main()
{
int z;
clrscr();
z=sum();
printf("sum of 2 numbers is %d",z);
getch();
}
int sum()
{
Output:
1 2 3 4 5 6 7 8 9 10
„C‟ gives us two choices when we want to reserve memory for an object.
In static memory allocation memory is allocated to the variable and arrays at compile
time. The no. of bytes required cannot be changed during run time.
Allocation memory to the objects at the run time is called Dynamic memory allocation.
To access the dynamic data pointers are used.
malloc( )
Malloc function is to allocate a block of memory and it returns void
pointers to the address of first byte the memory.
Calloc()
Calloc function is used to allocate memory dynamically for arrays.The only
difference between calloc and malloc doesn‟t.
All the programs we have written have been coded with no parameters for main.
#include<stdio.h>
#include<string.h>
#include<stdlib.h>
Output:
Structures
You are aware that a variable store a single value of a datatype.Arrays can store many
values of similar data type.In real life we need to have different data types for example
to maintain employees information we should have information such as name, age,
qualification, salary etc.
Here, to maintain the information of employees is dissimilar data types are
required. To handle such kind of data „C‟ provides a derived data type known as
“Structure”.
Declaration of Structure:
Structure can be declared as given below.
Syntax:
Struct <Structure-name>
{
Data type1 member 1;
Data type1 member 2;
---------------------------
Data type member n;
};
Struct <structure-name> variable;
Structure declaration always starts with struct keyword, Here Structure-name
is known as tag.
The struct declaration is enclosed with in a, pair of curly braces.
Each member of structure may belong to different types of data.
The individual members can be ordinary variables, arrays, pointers or other
structures.
E.g.:
Struct kick
{
Char m;
Int a, b, c;
Float d;
};
Struct kick p;
In the above declaration kick is the structure- name.
It contains five members. The p is a variable of kick. They have members called
m, a, b, c, d.
4,6,8,5.5,h
Write a program to display student details
#include<stdio.h>
#include<conio.h>
void main()
{
struct student
{
char name[30];
char course[40];
int age;
int year;
};
struct student s= {"yuva","cse",20,2010};
printf(" %s %s %d %d \n",s.name,s.course,s.age,s.year);
getch();
}
Array of structures
The Structures that we have defined can only contain one record. In
practical applications. There may be a number of records that need to be stored and
manipulated.
Array of structures can be declared as follow.
Syntax:
struct student
{
int rno;
char name [10];
float attd;
};
struct student s [60];
The members of the structure variable are referred and accessed as follows.
( s[i].rno,s[i].name,s[i].attd )
Write a program to enter the details of student rollno, name, and marks.
#include<stdio.h>
#include<conio.h>
void main()
{
int num,i=0;
struct student
{
char name[20];
int rollno;
int marks;
};
struct student s[10];
clrscr();
printf(" Enter the number of students:");
scanf("%d",&num);
Output:
Enter the number of students: 2
Enter the details for 1 student
Name: Rita
Roll No: 639
Total Marks: 66
Enter the details for 1 student
Name: Mita
Roll No: 639
Total Marks: 88
Press R to display the student details
Student 1
Name: Rita
Roll No: 639
Total Marks: 66
Student 2
Name: Mita
Roll No: 739
Total Marks: 88
Syntax:
struct book
{
Char name [18];
Char author [19];
int pages;
};
struct book *ptr;
*ptr is pointer to structure book. The syntax for using pointer with member is as given
below.
Write a program to declare pointer to structure and display the contents of the
structure.
#include<stdio.h>
void main()
{
struct book
{
char name[35];
char author[35];
int pages;
};
struct book bk={ "Java","James",999};
struct book *ptr;
ptr=&bk;
clrscr();
printf("%s by %s of %d pages",ptr->name,ptr->author,ptr->pages);
getch( );
}
Structure variables also can be passed to the function by value or address. The syntax
of the same is as under.
Syntax:
Struct books
{
Char name[33];
Char author[44];
Int pages;
};
Void main()
{
---------
jack(&b1);
---------
}
Jack(struct book *b2)
{
--------;
--------;
}
Write a program to pass structure elements to function print () and print the
elements.
#include<stdio.h>
#include<conio.h>
#include<string.h>
struct boy
{
Output:
Ricky 34 66
Pointer to Structure
We know that pointer is a variable that holds the address of
another data variables .The variable may be of any data type i.e. int, float, or double. In
the same way we can also define pointer to structure. Here, starting address of the
member variables can be accessed. Thus, such pointers are called structure pointers.
Syntax:
struct book
{
Char name [18];
Char author [19];
int pages;
};
struct book *ptr;
*ptr is pointer to structure book. The syntax for using pointer with member is as given
below.
#include<stdio.h>
void main()
{
struct book
{
char name[35];
char author[35];
int pages;
};
struct book bk={ "Java","James",999};
struct book *ptr;
ptr=&bk;
clrscr();
printf("%s by %s of %d pages",ptr->name,ptr->author,ptr->pages);
getch( );
}
Output:
We can take any data type for declaring structure members like int, float, char etc. In
the same way we can also take object of one structure as member in another structure.
Thus, structure with in structure can be used to create complex data applications.
Syntax:
Struct time
{
int second;
int minute;
int hour;
};
Struct t
{
int carno;
#include<stdio.h>
#include<conio.h>
void main()
{
struct name
{
char first[10];
char second[10];
char last[10];
};
struct bdata
{
int day;
int month;
int year;
};
struct data
{
struct name nm;
struct bdata bt;
};
struct data r1;
clrscr();
printf("\n Enter the name (first /second/last)\n");
scanf("%s %s %s",r1.nm.first,r1.nm.second,r1.nm.last);
printf("\n enter Birth date day/month/year)\n");
scanf(" %d %d %d ", &r1.bt.day,&r1.bt.month,&r1.bt.year);
printf("Name: %s %s %s \n",r1.nm.first,r1.nm.second,r1.nm.last);
printf("Birth date : %d %d %d",r1.bt.day,r1.bt.month,r1.bt.year);
getch();
}
Output:
By using typedef we can create new data type. The statement typedef is to used while
defining new data type.
Syntax:
typedef data_type data_name;
Here type is a data type and data name is the user defined name for that type.
E.g:
typedef int hours;
Here, hours is another name for int and now we cam use hours instead of int in the
program as follows.
hours hrs;
Write a program to create user-defined data type hours on int data type and use it
in the program.
#define h 60
Void main ( )
{
typedef int hours;
Hours hrs;
clrscr( );
printf(“Enter hours”);
scanf(“%d”,&hrs);
printf(\n MINUTES=%d”,hrs*H);
printf(“\n SECONDS=%D”,hrs*H*H);
getch( );
}
Output:
Enter hours: 2
Minutes=120
Seconds = 200
Def: A bit field set of adjacent bits whose size can be from 1 to 16 bits in length.
Syntax:
Struct tag_ name
{
Data type name 1: bit _length;
Data type name 2: bit _length;
---------------------
---------------------
Data type name n: bit-length;
};
The above statement creates a user-defined data type.The keyword enum is followed
by the tag name month.
The enumerated variables are Jan, Feb, mar------ dec.
The identifiers are not to be enclosed with in quotation marks.
Note that integer constants are also not permitted.
Write a program to create enumerated data type for 12 month. Display their
values in integer constants.
Output:
Jan=0
Feb=1
Jul=6
Dec=11
Unions
Union is a variable. This is similar to the structure. It contains number of members like
structure but it holds only one object at a time.
In the structure each member has its own memory locations whereas; members
of unions have same memory locations.
It can accommodate one member at a time in a single area of storage.
The union requires bytes that are equal to the number of bytes required for the
largest members.
Def:
“A union is a collection of data items of different data type. It is similar to that of
structure”.
A union is declared as shown below
Syntax:
Union <union tag name>
{
Data type member1;
Data type member2;
----------------
----------------
Uses of unions:
1. In general, the unions are used to give the memory area occupied by the
program.
2. Unions are used when all members need not exist in the memory at the same
time.
#include<stdio.h>
#include<conio.h>
void main()
{
union student
{
int rollno;
char result;
};
union student st1,st2;
clrscr();
st1.rollno=234;
st2.result='F';
Output:
Roll no: 234
Result: F
Roll no: 26438
Result: $
We frequently use files for storing information which can be processed by our
programs. Such files are called data files. In order to store information permanently and
retrieve it, we need to use data files. Our programs are also stored in files.
Def:
File is asset of records that can be accessed through the set of library functions
Or
A file is a place on disk where a group of related data is stored
It is advantageous to use files in the following.
The streams are designed to allow the user to access the files efficiently.
A stream is file or physical device like keyboard, printer and monitor.
Data source
F
Input text stream Data
Keyboard
monitor
Files can be classified on the basis of the mode of access into two types.
1. Sequential files.
2. Random access files.
„C‟ supports both sequential and random files.
Sequential file
In this type, data are kept sequentially. If we want to read the last record of the
file we need to read all the records before that record. It takes time.
Random access files
In his type data can be read and modified randomly. In this type if we want o read
last records of the file, we can read if directly. It takes less time as compared to
sequential file.
File operations
There are three steps for file operations in „C‟.
1. Opening of file.
2. Reading or writing file.
3. Closing file.
A „C‟ language supports many more file handling functions that are available in standard
library.
File function Operation
Mode Operations
„w‟ write Creates a new file for writing or open an existing file for writing
r+ Open an existing file for reading and writing the file must exist.
Opening a file
A file has to be opened before beginning of read and write operations of file
creates a link between the operating system and the file functions.
We have to specify the name of file and its mode to the operating system.
FILE *fp;
Fp=fopen(“data.txt”,”r”);
Here fp is file pointer variable that contains address of the structure file that has
been defined in the header file “stdio.h”. The function fopen() will open a file “data.txt” in
read mode.
#include<stdio.h>
#include<conio.h>
void main()
{
Output:
Write data & to stop press „.‟
Sambasiva.
Reading a file
Once the file is opened using fopen() its contents are loaded into the memory.
The fgetc() function is used to read the contents of the file.
ch=fgetc(fp);
The file that is opened using fopen() should be closed after the work is over I,e
we need to close the file after reading and writing operation are over.
E.g.:- fclose(fp);
The following statement closes all the file associated with the file pointer fp.
E.g.:- fcloseall();
File I/o functions
getc fgets
putc fputs
fprintf()
This function is used for writing characters strings integers float etc. to the
file.It contains one more parameter that is file pointer which points the opened file.
# include<stdio.h>
void main()
{
file *fp;
char text(30);
fp=fopen (“text , fnt,””w”);
clrscr();
printf(“ enter text here:‟);
gets(text);
fprintf(fp ,“%s”,text);
fclose(fp);
}
Output:
Enter text here have a nice day.
This function reads character, Strings integer, float etc. from the file pointed by
pile pointer.
WAP to enter data into the text file and read the same use‟w” file mode.
#include <stdio.h>
void main()
{
file *fp;
char text[5];
int age;
fp=fopen(“Text.txt”,”w+”);
clrscr();
printf(“Name \t ge \n”);
scanf(“%s %d”,text,&age);
fprintf(fp,”%s %d”,text,age);
printf(“Name \t age \n”);
fscanf(“fp,”%s %d”,text,&age);
printf(“%s \t %d\n”,text,age);
Fclose(fp);
}
Output:
Name Age
Rakhi 15
Name Age
Rakhi 15
getc()
This function reads single characters from the opened file and moves the
file pointer.It returns EOF,if end of the file is reached.
#include<stdio.h>
void main()
{
file *f;
char c;
clrscr();
f=fopen(*”list.txt”,”r”);
putc()
This function is used to write a single character into a file.if an error occurs
it returns EOF.
fgetc()
#include<stdio.h>
void main ()
{
FILE *fs;
int i=0,x,y,c=0,sb=0,b=0;
clrscr();
fs=fopen(“prg2.c”,”r”);
if(s==NULL)
{
printf(“\n File opening error:”);
exit(1);
}
while((x=fgetc(fs))!=EOF)
{
switch(x)
{
case „;‟ :c++;
break;
case „{‟ : sb++;
break;
case „(„ : b++;
break;
case „#‟ : i++;
break;
}
}
fclose(fs);
printf(“\n Summary of C program \n”);
printf(“\n Total statements %d”,c+i);
printf(“\n Include statement:%d”,i);
printf(“\n Total blocks { }:%d”,sb);
printf(“\n Total brackets ():%d”,b);
fputc()
This function writes the character to the file shown by the file pointer. It also
increases the file pointer.
Example:
#include<stdio.h>
void main()
{
FILE *fp;
char c;
clrscr();
fp=fopen(“list.txt”,”w”);
if(fp==NULL)
return;
else
{
while((c=getche())!=‟*‟)
fputc(c,fp);
}
fclose(fp);
}
OUTPUT:
India is my country
fgets()
This function reads string from a file pointed by file pointer. It also copies
the string to a memory location referred by an array.
Write a program to read text from the given file using fgets()
#include<stdio.h>
#include<conio.h>
fputs()
This function is useful when we want to write a string into the opened.
#include<stdio.h>
#include<conio.h>
void main()
{
FILE *fp;
char file[12],text[50];
clrscr();
printf(“\n Enter the name of file:”);
scanf(“%s”,File);
V. SambaSiva., Assistant Professor, Department of CSE, CREC. 118
fp=fopen(file,”w”);
if(fp==NULL)
{
printf(“\n FILE cannot opened\n”);
return;
}
else
{
printf(“\n Enter text here:”);
scanf(“%s”,text);
fputs(text,fp);
}
fclose(fp);
}
OUTPUT:
Enter the name of file: data.dat
Enter the text here: Good morning.
getw()
This function returns the integer value from a file and increases the file pointer.
Example:
#include<stdio.h>
#include<conio.h>
#include<process.h>
void main()
{
FILE *fp;
int v;
clrscr();
fp=fopen("num.txt","r");
if(fp==NULL)
{
printf("\n File does not exit");
exit(1);
Output:
Enter number: 1 2 3
putw()
This function is used to write an integer value to file pointed by file pointer.
Write a program to enter integers and write them in the file using putw().
#include<stdio.h>
#include<conio.h>
#include<process.h>
void main()
{
FILE *fp;
int v;
clrscr();
fp=fopen("num.txt","w");
if(fp==NULL)
{
printf("\n File does not exit");
exit(1);
}
else
{
printf("\nEnter number:");
while(1)
{
scanf("%d",&v);
if(v==0)
{
fclose(fp);
Enter numbers: 5 6 7 3 9 0
1. File pointer.
2. Negative or positive long integer number to reposition the
file pointer.
3. The current position of file pointer.
Write a program to read the text file containing some sentence .use fseek() and
text after skipping n characters from beginning of the file
#include<stdio.h>
#include<conio.h>
#include<process.h>
void main()
{
FILE *fp;
int n,ch;
while((ch=fgetc(fp))!=EOF)
printf("%c",ch);
printf("\n How many characters including spaces would you like to skip?:");
scanf("%d",&n);
fseek(fp,n,SEEK_SET);
printf("\n information after %d bytes \n",n);
while((ch=fgetc(fp))!=EOF)
printf("%c",ch);
fclose(fp);
}
Output:
Contents of a file
My name is khan
How many characters including spaces would you like to skip? :3
Name is khan
This function is used for writing an entire structure block to a given file.
fread()
This function is used for reading an entire block from a given file.
Write a program to write and read the information about the player containing
players name, age and runs
#include<stdio.h>
#include<conio.h>
#include<process.h>
struct record
{
char player[20];
int age;
int runs;
};
void main()
{
FILE *fp;
struct record emp;
fp=fopen("record.dat","w");
if(fp==NULL)
{
printf("\ncan not open the file");
exit(1);
}
clrscr();
printf("Enter player name,age &runs scored\n");
printf("===================================\n");
scanf("%s %d %d",emp.player,&emp.age,&emp.runs);
fwrite(&emp,sizeof(emp),1,fp);
fclose(fp);
if((fp=fopen("record.dat","r"))==NULL)
{
printf("\n Error on openingfile");
exit(1);
}
printf("\nrecord entered is\n");
Sachin 25 10000
Record entered is
Sachin 25 10000
feof()
The macro feof() is used for detecting file pointer whether it is at the end of the
file or not. It returns non-zero if the file pointer is at the end of the otherwise it returns
zero.
Write a program to detect the end of file using function feof().Display the file
pointer position for detecting end of file .
#include<conio.h>
#include<stdio.h>
void main()
{
FILE *fp;
char c;
fp=fopen("text.txt","r");
c=feof(fp);
clrscr();
printf("File pointer at the beginning of the file :%d\n",c);
while(!feof(fp))
{
printf("%c",c);
c=getc(fp);
}
c=feof(fp);
printf("File pointer at the end of the file %d",c);
#define PI 3.14
Define Macros
Conditional
Compilation
Diagnostics
Line Control
Pragmas
Other Directives
Preprocessor
Output
The #include preprocessor is used to include header files to a C program. For example,
#include <stdio.h>
#include "my_header.h"
#include <stdio.h>
#define PI 3.1415
int main()
{
float radius, area;
printf("Enter the radius: ");
scanf("%d", &radius);
// Notice, the use of PI
area = PI*radius*radius;
printf("Area=%.2f",area);
return 0;
}
You can also define macros that works like a function call, known as function-like
macros. For example,
#include <stdio.h>
#define PI 3.1415
#define circleArea(r) (PI*r*r)
int main()
{
int radius;
float area;
return 0;
}
Conditional Compilation
Uses of Conditional
To use conditional, #ifdef, #if, #defined, #else and #elseif directives are used.
#ifdef MACRO
conditional codes
#endif
Here, the conditional codes are included in the program only if MACRO is defined.
#if, #elif and #else Directive
#if expression
conditional codes
#endif
#if expression
conditional codes if expression is non-zero
#else
conditional if expression is 0
#endif
You can also add nested conditional to your #if...#else using #elif
#if expression
conditional codes if expression is non-zero
#elif expression1
conditional codes if expression is non-zero
#elif expression2
conditional codes if expression is non-zero
... .. ...
else
conditional if all expressions are 0
#endif
#defined
The special operator #defined is used to test whether certain macro is defined or not.
It's often used with #if directive.
There are some predefined macros which are readily for use in C programming.