Upload
bovilla-vishnuvardhanreddy
View
67
Download
0
Embed Size (px)
Citation preview
5/11/2018 Fundamentals and C Language - slidepdf.com
http://slidepdf.com/reader/full/fundamentals-and-c-language 1/162
COMPUTER FUNDAMENTALS
What is a computer?Characteristics of ComputerHistory of ComputersAbacusPascal’s Mechanical CalculatorCharles Babbage’s Differential EngineMark IElectronic Numeric Integrator and Calculator (ENIAC)Universal Automatic Computer (UNIVAC)Computer FamiliesGenerationsBlock diagram of ComputerLooking Inside The Machine
The Input devices The Output Devices The CPUMemory Unit
The Microprocessor The Memory Unit The Secondary StorageOperating SystemBooting
Overview of Computer System
Want to Learn C Language?
What is a Computer?
Computer is an electronic device which has capability to:
Accept the data Store the data Process the data Generate the result
Data – Raw facts that computer can manipulate.The Raw facts are Letters, Numbers, Sounds or Images.
Information – Processed data.
5/11/2018 Fundamentals and C Language - slidepdf.com
http://slidepdf.com/reader/full/fundamentals-and-c-language 2/162
Instruction – Command that a computer can understand.Program – Set of Instructions.
Characteristics of Computer:
Speed – No. of instructions executed per second Speedis
Measured in MHz, MIPS, FLOPS etc.,Storage – Computer can store data temporarily andpermanently - The storage is measured in Bits, Bytes, Kilobytes, Mega bytes, Giga bytesAccuracy – Computer never goes wrongReliability – Computer doesn’t cheatVersatility – Can be used in multiple ways
History of Computers:
The evolution of computer has passed through different stagesbefore it reached the present state of development. Theevolution probably started from the 3500 BC when human beingfirst started to learn to calculate with a calculating machine namedAbacus.
Abacus:
Abacus seems to be the earliest calculating machine, which wasdeveloped by the Chinese. Abacus consists of beads, which canmove, in wires.
Pascal’s Mechanical Calculator:
Blaise Pascal, the French mathematician, laid the foundation of automatic computing. Blaise Pascal used his adding machine(1662) simply for addition and subtraction. The machine consistedof gears, wheels and dials.Charles Babbage’s Differential Engine:
Charles Babbage, a professor of mathematics at CambridgeUniversity, invented a machine called Differential Engine – whichcould evaluate accurately algebraic expressions and mathematicaltables – correct up to 20 decimal place.Mark I:In 1934 Harvard professor H. Eiken developed an automaticcalculating machine, which was called Mark-I digital computer. Itsinternal operation was automatically controlled.
Electronic Numeric Integrator and Calculator (ENIAC):
While Mark-I was the first electromechanical computer, the firstelectronic general purpose computer was built in 1946. It was abulky machine consisting of 18,000 vacuum tubes, 70,000
5/11/2018 Fundamentals and C Language - slidepdf.com
http://slidepdf.com/reader/full/fundamentals-and-c-language 3/162
resistors, 10,000 capacitors, 60,000 switches and a large sizeoccupying 1500 Sq. feet of space.
Universal Automatic Computer (UNIVAC):
In the year 1946, Eckert and Mauchly founded their own companyand began to work on the Universal Automatic Computer, orUNIVAC. In 1949.
Computer Families:
Analog: These computers recognize data as a continuous measurement of a physical property. It measured Voltage, Pressure, Speed and
Temperature is some physical properties.Digital:
These are high speed programmable electronic devices that
perform mathematical calculation compare values, and store theresult. Digital Computers are also classified according speed, size,and cost and memory capacity as given below.
Hybrid:
The both analog and digital capabilities are called HybridComputers. Robots are best example for hybrid Computers.
Digital Computers can be classified based on Size, Cost, andSpeed:
Super Computers – Most powerful:
There are the largest and fastest computers available but aretypically not used in specialized areas such as in Defence, Aircraftdesign, computer generated movies, weather search. Supercomputers can process 64 bits or more at a time. Their processingspeed ranges from 10,000 million instructions per sec (MIPS) to 1.2
billion instructions per sec. They can support 10,000 terminals at atime.
Main frame – Largest type of Computers:Mainframes are less powerful and cheaper then Super Computers.However, they are big general purpose computers capable of handling all kinds of scientific and business applications.Mainframes can process several million instructions per second.More then 1,000 remote terminal can be supported by aMainframe. Mainframes have large on-line secondary storage
capacity.Mini Computers: This type of computer performs data processingactivities in the same way as the Mainframe but on a smaller scale.
The cost of minis is lower.
5/11/2018 Fundamentals and C Language - slidepdf.com
http://slidepdf.com/reader/full/fundamentals-and-c-language 4/162
Micro computers: This is the smallest category of computers, consisting of amicroprocessor and associated storage and input/output devices.
These are also called Personal Computers.
Personal Computers (PC) – Small computersPersonal computer is so named because it is designed for personaluse. IBM, the foremost computer manufacturing firm in the world,introduced the first PC named as IBM-PC
Desktop Computers. Notebook Computers. Laptop Computers. Packet Computers. Palmtop Computers.
Generations:
First Generation – (1942 -1955) Vacuum tubes: The computers produced between 1942-1955 are called the firstgeneration computers. They were extremely large with lowreliability. The first generation computers had the followingunfavorable features.
1. Too bulky in size.2. Unreliable for excessive heal generation.3. Air conditioning requirement was too much due to heat
generation.4. Non-portable
Second Generation (1955 - 1964) – TransistorsAdvantages:In comparison to first generation computers, the second
generation computer had the following favorable tea lures.1. Smaller in size as compared lo first generation computers2. More reliable3. Less heat generated4. Faster computational speed
Disadvantages:
Some unfavorable features also are seen in this generation1. Air conditioning required.2. Frequent maintenance required,3. Commercial production was difficult and costly.
5/11/2018 Fundamentals and C Language - slidepdf.com
http://slidepdf.com/reader/full/fundamentals-and-c-language 5/162
Third Generation (1964 – 1975) – Integrated CircuitsAdvantages :1. Smaller in size as compared lo previous generationcomputers2. Even more reliable than second generation3. Lower heat generated than second generation4. Reduce computational limes5. Low maintenance cost6. Comparatively portable7. Less power consumption8. Commercial production easier and cheaper
Fourth Generation (1975 – 1984) – VLSIAdvantages :1 Low cost machine
2, High speed3. Large memory A. Small size5 Less power consumption6. Floppy disk is used as storage device7. Hardware failure is negligible8. Cheapest among all generations
Fifth Generation (1984 – 1990) – Silicon ChipsScientists are now at work with the fifth generation of computers
the world is moving towards The development of what one can call‘Super Large Scale Integration’ - which in turn will compliment andimprove speed, miniaturization and cost reduction
Block diagram of Computer:
CPU – Central Processing UnitALU – Arithmetic Logical unitCU – Control Unit
Input
Memory
Storage
Output
CPU
ALU
CU
5/11/2018 Fundamentals and C Language - slidepdf.com
http://slidepdf.com/reader/full/fundamentals-and-c-language 6/162
Looking Inside The Machine:
Input devices – To accept data from userOutput devices – To display resultsProcessor – To process the user inputsMemory – To store the results temporarilyStorage devices – For permanent storageBuses – Means of communication in CPUMother board – Circuit board that connects CPU to all otherH/W devices
The Input devices:
Keyboard.Mouse.
Trackball. Track pad. Joystick.Light PenMike (or) Micro Phone.Bar Code Readers.Scanner.
Touch Screens.
The Output Devices:
The Monitor The Printer The Sound Systems
The CPU:
CPU – Central Processing UnitIt has a cabin like structure with many components placed
in it.
The Micro processorALU – Arithmetic Logical UnitCU – Control Unit
Memory UnitPrimary storageSecondary storage
The Microprocessor:
It is a chip which performs all the tasks.
ALU – It performs Arithmetic and Logical operationsCU – It controls the operations performed by the computerExample: Intel Pentium Processor
5/11/2018 Fundamentals and C Language - slidepdf.com
http://slidepdf.com/reader/full/fundamentals-and-c-language 7/162
The Memory Unit:
Memory – Storage area where data is storedROM – Read Only Memory
It holds the same data forever Data/Instructions are burnt on the chips at the time of
manufacturing it self
Contains start up instructions for computer
Primary memory – Temporary storage areaRAM – Random Access Memory
It is volatile It is fast It is available for the user
The Secondary Storage:
Secondary storage. Devices where data can be stored permanently. Storage and retrieval of data is slow when compared with Primary
storage
Magnetic Storage devices. Hard disks Floppies
Optical Storage devices CDs, DVDs
Operating System:
A set of programs that manages the system resources likememory, processes, peripherals and files
OS acts as an interface between system and userFunctions:
1. Device management.2. Memory management.3. Data management.4. Process management.5. Files and software management.6. CPU Time management.
Types of OS: Single user environment. Multi user environment.
Single user environment: Single user single tasking. Single user multi tasking.
5/11/2018 Fundamentals and C Language - slidepdf.com
http://slidepdf.com/reader/full/fundamentals-and-c-language 8/162
Multi user environment: Multi user multi tasking.
Booting:
What is Booting ? The Process of switching on the computer is
referred as the “Booting” of the computer.
Types of Booting: There are two types of Booting.
Cold Booting (Switch Booting) Hot Booting (Resetting)
Overview of Computer System:
Hardware – Touchable parts of ComputerSoftware – Set of programs
Application S/w – Programs for users Ex: Word processing – MS Word etc.
System s/w – Programs for computer Ex: Operating system – Windows, UNIX etc.
Computer
Hardware Software
Application System
OS,Compilers,
Interpreters
Packages UtilitiesLanguages
Low level High levelAssembly
5/11/2018 Fundamentals and C Language - slidepdf.com
http://slidepdf.com/reader/full/fundamentals-and-c-language 9/162
Back to Main menu…
INTRODUCTION TO C-LANGUAGE
C-Language:
C was developed at AT&T Bell Laboratories in1972 by
Dennis.M.Ritchie. In late 1970s it began to replace the existing languages like ALGOL
etc., C language is reliable, simple and easy to use
Historical development of C:
Yea
r
Langua
ge
Organization Remarks
1960
ALGOL60 International committee Too general, tooabstract
1963
CPL Cambridge university Hard to learn anddifficult to implement
1967
BCPL Martin Richards atCambridge university
Could deal with onlyspecific problems
1970
B Ken Thompson at AT&TBell Labs
Could deal with onlyspecific problems
1972
C Dennis Ritchie at AT&TBell Labs
Lost generality andrestored B
CPL – Combined Programming LanguageBCPL – Basic Combined Programming Language
Computer languages:
Problem oriented languages: These are also called high level languages. These are mainly usedfor faster program development.
5/11/2018 Fundamentals and C Language - slidepdf.com
http://slidepdf.com/reader/full/fundamentals-and-c-language 10/162
Examples: COBOL, Pascal, FORTRAN, etc;
Machine oriented languages: These are also called low level languages. These are mainly usedfor faster program execution.
Note:C is middle level language. It has features of both high level aswell as low level languages.
Getting started with C:
There are similarities in learning English and C language.
English is a language through which we can communicate withother people.
C is a language through which we can communicate with acomputer to fulfill our requirements.
Steps in learning English Language:
Steps in learning C Language:
Features of C Language:
C is a system programming language with which we can developother languages, packages, operating systems, editors, linkers,
loaders, assemblers and utilities.
C is a structured programming language. It follows a methodicalstructure to develop a program.
Alphabets
DigitsSpecialsymbols
ConstantsVariablesKeywords
Instructions Program
Alphabet Words Sentences Paragraphs
5/11/2018 Fundamentals and C Language - slidepdf.com
http://slidepdf.com/reader/full/fundamentals-and-c-language 11/162
It is strictly typed language. We should define data type for everyvariable we use in the program.
It supports high level programming as well as low levelprogramming with the concept of Bit wise operators andInterrupts.
C supports data structures. Dynamic allocation and de allocation of memory is possible with this concept. The power of C lies in
pointers. By making use of pointers we can create linked lists,stacks, queues, trees etc.,
C is a function oriented language.
It supports file handling facility with which we can store the datapermanently on magnetic media. This facilitates C to use in
commercial applications.
C is basically a scientific language which gives single precision anddouble precision results.
It supports graphics and music.
A C program can interact with external devices with the concept of interrupts i.e., software interacting with hardware.
It has readability , portability and correct ability .
The C Character set:
A character denotes any alphabet, digit or special symbol used torepresent information.
AlphabetsA, B, … Y, Za, b, … y, z
Digits0, 1, 2, 3, 4, 5, 6, 7, 8, 9
Special symbols
~ ` ! @ # % ^ & * ( ) _ - + = |\ { }[ ] : ; “ ‘ < > , . ? /
Constants, Variables and Keywords:
The alphabets, numbers and special symbols when properlycombined, form constants, variables and keywords.
Constant is an element whose value cannot be changed.
5/11/2018 Fundamentals and C Language - slidepdf.com
http://slidepdf.com/reader/full/fundamentals-and-c-language 12/162
Variable is an element whose value can be changed. Keyword is a set of characters which have some predefined
meaning.
Types of C Constants:
C constants can be divided into 2 categories:
Primary Constants Secondary Constants
Primary constants
These are predefined set of numbers, characters and special
characters.
Integer Constants:
An integer constant is formed using the digits i.e. 0 to 9 and anoptional sign + or –
The allowable range for integer constant is -32768 to +32767Ex: 1063
-100
Real Constants:Real constants are also called Floating Point constants. There are 2types of Real Constants:
Fractional Form: The real constant may be either +ve or –ve with a decimalpoint in it.Ex: +325.34
-0.10 Exponential Form:
This form is used if the value of real constant is too small ortoo large. In this form a real constant is represented in twoparts separated by ‘e’.
C Constants
Primary ConstantsSecondaryConstants
Integer ConstantReal ConstantCharacter
Constant
ArrayPointer
StructureUnionEnum etc.
5/11/2018 Fundamentals and C Language - slidepdf.com
http://slidepdf.com/reader/full/fundamentals-and-c-language 13/162
The part before ‘e’ is called mantissa and the part after ‘e’ iscalled exponent.
The range of real constants is -3.4e38 to +3.4e38Ex: +3.2e-5
1.2e8-1.6e-10-2.4e+5
Character Constants:
Any valid character in C character set enclosed in single quotes isconsidered as character constant. Character constants may besimple characters or character strings.
Ex: simple characters : ‘A’ ‘l’ ‘6’ ‘@’Character strings: “ant”, “100”, “computer”
Simple Characters are enclosed in single quotes. And strings areenclosed in double quotes.
Variables:
Variable is a name that is used to represent a data in thecomputers memory. In other words variables are names given tolocations in memory. The data of a variable can be modified at any
time during the program execution. Variable is also called asDataname or Identifier.
A variable must be declared before we store any value in to it. This is called variable declaration. A variable of particular type canhold values of only that type. For example, an integer variable canhold only integer constants and a real variable can hold only realconstants.
Rules for constructing variables:
A variable name is a combination of alphabet (upper and lowercase),
digits (0 to 9) or underscore (_). The first character in the variable name must be an alphabet or
underscore. The length of the variable may be any number of characters. No commas or blanks or any other special characters except
underscore is allowed in variable names.
Upper case and lower case letters are distinct. C is case sensitive. Reserved words should not be used as variable.
5/11/2018 Fundamentals and C Language - slidepdf.com
http://slidepdf.com/reader/full/fundamentals-and-c-language 14/162
C Keywords:
Keywords are the words which have some pre-defined meaning. The keywords cannot be used as variable names because if we doso we are trying to redefine the keyword, which is invalid. Thekeywords are also called ‘Reserved words’. There are 32 keywords
in C.
auto double Int structbreak else Long switchcase enum Register typedef char extern Return unionconst float Short unsignedcontinue for Signed voiddefault goto Sizeof volatiledo if Static while
Data types:
Data types specify the type of value that a variable holds. In C,before using a variable, its type must be declared. C allows 4primitive data types:
int – to store integer data float – to store real data
double – to store real data with greater precision char – to store character data
Any variable declared in the program is stored in memory which is asequence of bytes.
The size of each data type and the permissible range is given below.
Data type Size (in bytes) Rangeint 2 -32768 to +32767
float 4 -3.4e38 to +3.4e38
double 8 -1.7e308 to+1.7e308
char 1 -128 to +127(256 characters –ASCII)
Derived data types and format characters:
5/11/2018 Fundamentals and C Language - slidepdf.com
http://slidepdf.com/reader/full/fundamentals-and-c-language 15/162
Derived data types are derived from the primitive data types. These areused for effective memory usage and to increase the range of valuesallowed by data types.
Format characters are used to specify the data types in a format string. These are mainly used in I/O instructions. For every data type there iscorresponding format character.
Data Type Range Bytes Formatsigned char -128 to +127 1 %cunsigned char 0 to 255 1 %cshort signedint
-32768 to+32767
2 %d
shortunsigned int
0 to 65535 2 %u
signed int -32768 to+32767
2 %d
unsigned int -32768 to+32767
2 %u
long signedint
-2147483648to+2147483647
4 %ld
long unsignedint
0 to4294967295
4 %lu
Float -3.4e38 to+3.4e38
4 %f
double -1.7e308 to+1.7e308
8 %lf
long double -1.7e4932 to+1.7e4932
10 %Lf
Note: The sizes and ranges of int, short and long are compiler
dependent. Sizes in this figure are for 16 bit compiler.Program:
A program is a set of instructions which performs a specific task. AC program is a set of instructions arranged in logical order.
Features of C Program:
Each instruction in a C program is written as a separate statement. Therefore, a C program is a series of statements.
All the statements in a C program are executed sequentially. We can insert blank spaces between two words to increase
readability. But, we can’t insert blank spaces in a variable,keyword or constant.
5/11/2018 Fundamentals and C Language - slidepdf.com
http://slidepdf.com/reader/full/fundamentals-and-c-language 16/162
Every statement in C is terminated with ; (semicolon) and hence ;acts as a statement terminator.
Operators of C language :
The operators of C language can be classified as follows
Arithmetic Operators :
They are used to perform arithmetic calculations by evaluatingarithmetic expressions.
Assignment operators :
These are used to assign the values to variables.
operat
or
purpose
+ addition- subtraction* multiplication/ division% Modulo
(remainder)
Arithmeticoperators
Assignmentoperators
Comparison &logical
operators
Bit wiseoperators
Specialoperators
Relationaloperators
Equalityoperators
Logicaloperators
Unaryoperato
rs
Ternaryoperato
r
Commaoperato
r
Otheroperato
r
C operators
5/11/2018 Fundamentals and C Language - slidepdf.com
http://slidepdf.com/reader/full/fundamentals-and-c-language 17/162
Comparison & logical operators :
These can be grouped into three categories.
Relational operators :
They are used to compare the operands and returns 1 if
comparison is true other wise zero.
operator
purpose
< Less than> Greater than<= Less than or equal to>= Greater than or equal
to
Equality operators :
They check for equal or unequal of the operands
operator
purpose
= = Equal to!= Not equal to
Logical operators :
They are used for multiple condition checking.
operator purpose= Assigns value to variable+= Value is added and stored in same
variable-= Value is subtracted and stored in
same variable*= Value is multiplied and stored in
same variable/= divided and stored in same variable%= Remainder is stored in same variable>>= Righ shift and assigned to variable<<= Left shift and assigned to variable&= Bitwise AND operation and assigned
to variable|= Bitwise OR operation and assigned to
variable
~= Bitwise Compliment and assign tovariable
5/11/2018 Fundamentals and C Language - slidepdf.com
http://slidepdf.com/reader/full/fundamentals-and-c-language 18/162
operator
purpose
&& Logicaland
|| Logical or! Logical
not
Bitwise operators :
They are low level operators used to perform logical calculation onbits i.e binary digits
Operator
Meaning
& Bitwise AND^ Bitwise exclusive
OR| Bitwise OR>> Bitwise right shift<< Bitwise left shift~ Bitwise
complement
Special operators: They are used to perform some particular type of operations.
1. Unary operators:They require single expression.Operat
or
Meaning
* Pointer& Address of variable- Negative value! Negation~ Bitwise complement++ Incrementer-- Decrementer
Type Forced type of conversion
Sizeof Size of subsequent data type inbytes
2. Ternary operator:
5/11/2018 Fundamentals and C Language - slidepdf.com
http://slidepdf.com/reader/full/fundamentals-and-c-language 19/162
It is used for checking the conditions. It is short hand version of if-else statement.(condition) ? expression1 : expression2
3. Comma operator:It is used to separate the variable in variable declarations andexpressions in ‘for’ looping structure.Eg : int a,b,c;
Other operators:
Parentheses – for grouping expressionsMembership operators – used with arrays,structures,unions.Eg: . [] ->
OPERATORS AND THEIR PRECEDENCE
OPERATOR DESCRIPTIONASSOCIATIVITY
RANK
( )[ ]
Function callArray elementreference
Left to right 1
+-++
--!~*&sizeof (type)
Unary plusUnary minusIncrement
DecrementLogical negationOnes complementPointer referenceAddressSize of an object
Type cast (conversion)
Right to left 2
*/%
MultiplicationDivisionModulus
Left to right 3
+-
AdditionSubtraction
Left to right 4
<<>>
Left shiftRight shift
Left to right 5
<<=>>=
Less thanLess than or equal toGreater thanGreater than or equalto
Left to right 6
==!=
EqualityInequality
Left to right 7
& Bitwise AND Left to right 8^ Bitwise XOR Left to right 9| Bitwise OR Left to right 10
5/11/2018 Fundamentals and C Language - slidepdf.com
http://slidepdf.com/reader/full/fundamentals-and-c-language 20/162
&& Logical AND Left to right 11|| Logical OR Left to right 12?: Conditional expression Right to left 13=*= /= %=+=-=&= ^= |=<<= >>=
Assignment operators Right to left 14
, Comma operator Left to right 15
C program :
Combination of instructions becomes a Program. ‘C’ program canhave declarations, expressions, compound statements and controlstatements.
Declarations: All the variables used in the program are declared to theircorresponding data types.Example : int a,b,c;Example : float x,y;Example : char m;
Expressions: Any valid ‘C’ expression can be written followed by semicolon.
Example : a=b+c;Example : a++;
Compound statements : A group of ‘C’ expressions placed with in { and } is called
compound statement.Example:
{a=b+c;x=y*z;
}Control statement:
The control statements are used for the programming flow and tocheck the conditions of the given expression or variable orconstant.Example : if (a>b) big=a;Example : while(condition)
Structure of ‘C’ program:
# include filesmain(){
5/11/2018 Fundamentals and C Language - slidepdf.com
http://slidepdf.com/reader/full/fundamentals-and-c-language 21/162
type or variable declarationsstatements of operation
displaying the results}
main() :
This is built in function which indicates the beginning of ‘C’program. This function internally contains various statements. Thisin turn can call other functions.
printf() :
This is an output function. It is used to display output on monitor. Itdisplays the values of variables, string constants and expressions.
The formatting characters can be specified with printf(). Its
prototype is found in <stdio.h> header file.
Syntax:
printf(“format string “,argument list);or
printf(“string constant”);
Example: printf(“%d %d “,a,b);
Example: printf(“Welcome to infotech”);
scanf() :
This is input function. It is used to accept the values from keyboardinto the spacified variables. We specify format with scanf function.Its prototype is found in <stdio.h> header file.
Syntax :
scanf(“format string”, argument list);
Example : scanf(“%d”,&a);Example: scanf(“%f%f”,&x,&y);
Comments :
The comments are the optional statements. These are also calledremark statements. They are non-executable and are used toincrease the readability of program. The comments are given in
between /* and */
Example : /* Program to find factorial of a number */
Program 1:
5/11/2018 Fundamentals and C Language - slidepdf.com
http://slidepdf.com/reader/full/fundamentals-and-c-language 22/162
/* Example on printf() */
main(){printf("Welcome to Infotech. ");
}
Program 2:
/* Example on multiple printf() statements */
main(){
printf("Welcome to Infotech");printf("The choice of intellectuals");
}
Escape sequences:
These are also called Back slash characters. They are used withoutput finction i.e printf(). Some times they are also referred as
white space characters.
Back slash character Purpose\a Audible alert – beep sound\b Back space\f Form feed\n New line\t Horizontal tab\r Carriage return
\n New line\’ Single quotation\” Double quotation\\ Single slash\0 Null character
Program 3:
/* Example on '\n' - New line character */
main(){printf("Welcome to Infotech.\n");
Output:Welcome to Infotech.
Output:Welcome to Infotech.The choice ofintellectuals
Output:Welcome to Infotech.The choice ofIntellectualsBhagya Nagar
5/11/2018 Fundamentals and C Language - slidepdf.com
http://slidepdf.com/reader/full/fundamentals-and-c-language 23/162
printf("The choice of \n intellectuals\n");printf(“Bhagya Nagar \t Kurnool”);}
Program 4:
/* Multiple statements can be written in same line */
main(){int a,b,c;clrscr();a = 5; b = 10; c = a+b;printf("\n Sum is %d",c);getch();
}
clrscr() :
This is built in function which is used to clear the screen.
getch():
This makes the cursor wait till the user presses any key from keyboard. It is used to accept a character with out displaying it onmonitor.
Program 5:
/* Initialization of variables at the time of declaration */
main(){int a=5, b=10, c;clrscr();c = a+b;printf("\n Sum is %d",c);getch();
}
Program 6:
/* Expressions in printf statement */
main(){int a=5, b=10;
Output:Sum is 15
Output:Sum is 15
Output:Sum is 15Sum is 15
5/11/2018 Fundamentals and C Language - slidepdf.com
http://slidepdf.com/reader/full/fundamentals-and-c-language 24/162
clrscr();printf("\n Sum is %d",(a+b));printf("\n Sum is %d",(5+10));getch();
}
Program 7:
/* Common initialization */
main(){int a,b,c;clrscr();a = b = 5;c = a+b;
printf("\n Sum is %d",c);getch();
}
Note:
int a=b=5; This type of common initializations at the time of variabledeclaration is invalid .
Program 8:
/* Multiple %d in printf() */
main(){int a=5, b=10, c;clrscr();c = a+b;printf("\n Sum of %d and %d is %d",a,b,c);getch();
}
Program 9:/* Evaluate the following expressions
30 - 20 = ?50 * 10 = ?
Output:Sum is 10
Output:Sum of 5 and 10 is
5/11/2018 Fundamentals and C Language - slidepdf.com
http://slidepdf.com/reader/full/fundamentals-and-c-language 25/162
50 / 5 = ? */
main(){clrscr();printf("\n 30 - 20 = %d", (30-20));printf("\n 50 * 10 = %d", (50*10));printf("\n 50 / 5 = %d", (50/5));getch();
}
Program 10:/* Example on format characters or %characters */
main(){
int a = 10;float b = 3.14;double c = 1.231534;char d = 'a';clrscr();printf("\n Integer value is %d",a);printf("\n Float value is %f",b);printf("\n Double value is %lf",c);printf("\n Character value is %c",d);
getch();}
Program 11:/* Example on getting formatted output */
main(){int a=10, b=1234;float c=3.141324;clrscr();printf("\n%d%d",a,b);printf("\n%5d%5d",a,b);printf("\n%05d\n%05d",a,b);printf("\n%-5d%-5d",a,b);printf("\n%f",c);printf("\n%6.2f",c);printf("\n%06.2f",c);getch();
}Type casting :
Converting a set of declared types to some other required type iscalled type casting.
Output:30 – 20 = 1050 * 10 = 500
50 / 5 = 10
Output:Integer value is 10Float value is 3.140000Double value is 1.231534Character value is a
Output:10123410 1234
000100123410 12343.141324
3.14003.14
5/11/2018 Fundamentals and C Language - slidepdf.com
http://slidepdf.com/reader/full/fundamentals-and-c-language 26/162
A variable belonging to lower range can be converted implicitly tohigher range data type but the higher range variable can beexplicitly converted to lower range, which may result to data lost.
For example when a float variable is converted to integer, the
fractional part will be lost.
Program 12:
/* Example on type casting */
main(){
int a, b=100;float c=3.45, d;
clrscr();a = c;d = b;printf("\n a=%d",a);printf("\n d=%f",d);getch();
}
Program 13:
/* Example on type casting */
main(){int a=10, b=3;float res1, res2, res3;clrscr();res1 = a/b;res2 = a*1.0/b;res3 = (float)a/b;printf("\n Result1 : %f",res1);printf("\n Result2 : %f",res2);printf("\n Result3 : %f",res3);getch();
}
Mixed mode expression :
An expression with variable belonging to different datatypes iscalled mixed mode expression. The size of receiving variable’sdatatype should be greater than or equal to the size of expressionvariable’s datatype .
Output:Result1 :
3.000000
Result2 :
Output:a=3
d=100.00000
5/11/2018 Fundamentals and C Language - slidepdf.com
http://slidepdf.com/reader/full/fundamentals-and-c-language 27/162
Program 14:
/* Example on Mixedmode expression */
main(){int a=5;float b=10.52;double c=3.4567689,res;clrscr();res = (double)a + (double)b + c;printf("\nSum is %lf",res);getch();
}
Programs on accepting values from key board - using scanf()
function
Program 15:
/* Accept any two numbers from key board and display sum */
main(){int a,b,c;
clrscr();printf("\n Enter 1st number : ");scanf("%d",&a);printf("\n Enter 2nd number : ");scanf("%d",&b);c = a + b;printf("\n Sum of %d and %d = %d",a,b,c);getch();
}
Program 16:
/* Multiple inputs in single scanf() statement */main(){int a,b,c;clrscr();printf("\n Enter 2 numbers : ");scanf("%d%d",&a,&b);
c = a+b;printf("\n Sum is %d",c);getch();
}
Output:
Enter 1st number : 5Enter 2nd number :10
Output:Enter 2 numbers : 50
25
Output:Sum is 18.976769
5/11/2018 Fundamentals and C Language - slidepdf.com
http://slidepdf.com/reader/full/fundamentals-and-c-language 28/162
Program 17:
/* Accept 2 no.s from key board and find their sum, difference,product
quotient, remainder */
main(){int a,b;int s,d,p,r;float q;clrscr();printf("\n Enter 2 numbers : ");scanf("%d%d",&a,&b);
s = a+b;d = a-b;p = a*b;q = (float)a/b;r = a%b;
printf("\n Sum is %d",s);printf("\n Difference is %d",d);printf("\n Product is %d",p);printf("\n Quotient is %f",q);
printf("\n Remainder is %d",r);getch();}
Program 18:
/* Example on mod operator */
main(){int a,b,c;clrscr();a = 10; b = 3; c = a % b;printf("\n a%%b = %d",c);a = 10; b = -3; c = a % b;printf("\n a%%b = %d",c);a = -10; b = 3; c = a % b;printf("\n a%%b = %d",c);a = -10; b = -3; c = a % b;
printf("\n a%%b = %d",c);getch();
}
NOTE:
Output:Enter 2 numbers : 50
10Sum is 60Difference is 40Product is 500
uotient is 5.000000
Output:a%b = 1a%b = 1a%b = -1a%b = -1
5/11/2018 Fundamentals and C Language - slidepdf.com
http://slidepdf.com/reader/full/fundamentals-and-c-language 29/162
% operator always returns the remainder. The sign of result willbe same as that of left side value of % . It should not be usedwith real numbers.
Program 19:
/* Example on / and % operatorAccept number of days and display it in
Years , months and days */
main(){int days, years, months;clrscr();printf("\n Enter number of days : ");
scanf("%d",&days);years = days/365;days = days%365;months = days/30;days = days%30;printf("\n Years = %d\n Months = %d\n Days =
%d",years,months,days);getch();
}
Programs on Relational operators:
Relations are formed between variables, constants using relationaloperators .
An expression formed using relational operators is alwaysevaluated to either true (1) or false (0)
Program 20:
/*Example on relational operators */
main(){int a,b,res;clrscr();printf("\n Enter 2 numbers : ");scanf("%d%d",&a,&b);
res = a > b; printf("\n %d > %d is %d",a,b,res);res = a < b; printf("\n %d < %d is %d",a,b,res);res = a >= b; printf("\n %d >= %d is %d",a,b,res);res = a <= b; printf("\n %d <= %d is %d",a,b,res);
Output:Enter number of days :
400Years = 1Months = 1
Output:Enter 2 numbers : 858 > 5 is 18 < 5 is 08 >= 5 is 18 <= 5 is 08 == 5 is 0
5/11/2018 Fundamentals and C Language - slidepdf.com
http://slidepdf.com/reader/full/fundamentals-and-c-language 30/162
res = a == b; printf("\n %d == %d is %d",a,b,res);res = a != b; printf("\n %d != %d is %d",a,b,res);
getch();}
Logical operators :
They are used to relate the conditions logically. The differentlogical operators are
&& - And operator|| - Or operator! - Not operator
&& operator :
When conditions are checked with && operator, then if all theconditions are true, the result is evaluated to true. If any conditionis false, the result is treated false.
Condition1
Condition2
Result
False False False
False True False True False False True True True
|| operator :
When conditions are checked with || operator, then if anycondition is true, the result is evaluated to true. If all conditionsare false, the result is treated false.
Condition1
Condition2
Result
False False FalseFalse True True
True False True True True True
! operator :
It negates the condition. If condition is true, by using ! operator , itbecomes false and vice versa.
Conditio Resul
5/11/2018 Fundamentals and C Language - slidepdf.com
http://slidepdf.com/reader/full/fundamentals-and-c-language 31/162
n tFalse True
True False
Program 21:
/* Example on logical operators */
main(){int a,b,res;clrscr();printf("\n Enter 2 numbers : ");scanf("%d%d",&a,&b);
/* && Logical AND operator */res = (a>b) && (a<b);printf("\n (%d > %d) && (%d < %d) is %d",a,b,a,b,res);
/* || Logical OR operator */res = (a>b) || (a<b);printf("\n (%d > %d) || (%d < %d) is %d",a,b,a,b,res);
/* ! Logical NOT operator */res = !(a==b);printf("\n !(%d == %d) is %d",a,b,res);getch();
}
Shortand assignment operator :
When shorthand assignment operator is used in expression thenthe RHS is completely evaluated and that result is computed withLHS and finally the result is stored in LHS i.e.,
LHS op= RHS;where RHS is any expressionop is any operator like + - * / etc.,
Output:Enter 2 numbers : 8
5(8 > 5) && (8 < 5) is 0(8 > 5) || (8 < 5) is 1
5/11/2018 Fundamentals and C Language - slidepdf.com
http://slidepdf.com/reader/full/fundamentals-and-c-language 32/162
Program 22:
/* Example on shorthand assignment operators */
main(){int a=10;clrscr();a = a + 10;printf("\n a = %d",a);a += 10;printf("\n a = %d",a);getch();
}
Program 23:
/* Example on shorthand assignment operators */main(){int a,b;clrscr();printf("\n Enter 2 numbers : ");scanf("%d%d",&a,&b);
a += b; /* a = a + b */printf("\n a = %d b = %d",a,b);a -= b; /* a = a - b */printf("\n a = %d b = %d",a,b);a *= b; /* a = a * b */printf("\n a = %d b = %d",a,b);a /= b; /* a = a / b */printf("\n a = %d b = %d",a,b);a %= b; /* a = a % b */printf("\n a = %d b = %d",a,b);getch();
}
Program 24:
/* Example on increment (++) and decrement (--) operators */main(){int a = 10;
clrscr();printf("\n %d",a);/* Incrementing a */a = a + 1;printf("\n\n %d",a);
Output:
a = 20a = 30
Output:Enter 2 numbers : 10
5a = 15 b = 5a = 10 b = 5
a = 50 b = 5a = 10 b = 5
Output:10
1112
13
121110
5/11/2018 Fundamentals and C Language - slidepdf.com
http://slidepdf.com/reader/full/fundamentals-and-c-language 33/162
/* Pre incrementing a */++a;printf("\n %d",a);/* Post incrementing a */a++;printf("\n %d",a);/* Decrementing a */a = a - 1;printf("\n\n %d",a);/* Pre decrementing a */--a;printf("\n %d",a);/* Post decrementing a */a--;printf("\n %d",a);getch();
}NOTE:
There is no difference between pre or post incrementing or pre orpost decrementing when used independently i.e., when theyare not written in an expression.
Pre or post incrementing ‘a‘ in the sense a = a + 1Pre or post decrementing ‘a’ in the sense a = a – 1
Program 25:
/* Example on shorthand assignment operators */
main(){int a,b,c;a=b=c=0;clrscr();printf("\nInitial values of a,b,c %d %d %d",a,b,c);a = ++b + ++c;printf("\n a = ++b + ++c %d %d %d",a,b,c);a = ++b + c++;printf("\n a = ++b + c++ %d %d %d ",a,b,c);a = b-- + c--;printf("\n a = b-- + c-- %d %d %d",a,b,c);getch();}
Program 26:
/* To accept Name, sex and pay */
Output:Initial values of a,b,c 0
0 0a = ++b + ++c 2 1 1a = ++b + c++ 3 2 2
5/11/2018 Fundamentals and C Language - slidepdf.com
http://slidepdf.com/reader/full/fundamentals-and-c-language 34/162
# include <stdio.h>main(){
char name[20],sex;int pay;clrscr();printf("Enter Name ");scanf("%s",name);fflush(stdin);printf("Enter sex m/f ");scanf("%c",&sex);printf("Enter pay ");scanf("%d",&pay);printf("\n\n Your Name is %s",name);printf("\n Sex is %c",sex);
printf("\n Pay is %d",pay);getch();
}fflush(stdin) :
It is used to flush the keyboard buffer. It is used before acceptingthe characters. Its prototype is in header file <stdio.h>
Exercise:
1. Write a program to print your details.2. Accept length and breadth of a rectangle and find its area and
perimeter.3. (Area = length x breadth, Perimeter = 2(length+breadth)4. Accept radius of circle and find its area and perimeter5. (Area = 3.14*r*r, Perimeter = 2*3.14*r)6. Accept base, height of triangle and find its area7. (Area = 1/2*base*height)8. Accept distance between 2 cities in Kilometers and display the
distance in metres.9. (1 Kilometre = 1000 metres)10. Accept weight of a person in grams and display the weight in
Kilograms11. (1 gram = 1/1000 kg)12. Accept end points of a line and find its mid point.13. (If (x1,y1) and (x2,y2) are end points of a line then its mid
point is
14. (mx,my) = ((x1+x2)/2, (y1+y2)/2))15. Write a program to calculate simple interest by accepting
values for principle amount , rate of interest and time of interest.
16. Simple interest = (principle * time * rate ) / 100
Output:Enter Name PremEnter sex m/f mEnter pay10000
Your Name is PremSex is mPay is 10000
5/11/2018 Fundamentals and C Language - slidepdf.com
http://slidepdf.com/reader/full/fundamentals-and-c-language 35/162
17. Input temperature in Centigrade, Convert it into Fahrenheit.18. Explain the rules to declare variable19. Explain printf() and scanf() functions20. Write about ‘C’ datatypes.
CONTROL STATEMENTS
The control statements are used to control the flow of program. They are classified as follows.
unconditional control statements conditional control statements Looping structures
1. Unconditional control statements:
They are used to transfer the control without checking conditions.
Example:goto statement : This is used to transfer the control fromcurrent point of program execution to the ‘label’ specified.
Syntax : goto <label>;
Program 27:
/* Example on goto statement */
main(){
Output:Good Morning Students of
5/11/2018 Fundamentals and C Language - slidepdf.com
http://slidepdf.com/reader/full/fundamentals-and-c-language 36/162
clrscr();printf("Good Morning ");goto infotech;printf("Every body ");infotech:printf("Students of Infotech");getch();
}
2. Conditional control statements :
There are two types of statements, which are as follows if statement switch statement
a). if - statement :
It is used to check the condition and take necessary action. Thedifferent forms of ‘if’ statements are as follows.
Simple if statement If-else statement Nested if statement If-else-if statement
1. Simple if statement :
If the specified condition is true then the statements orexpressions following the condition will be evaluated. If multiplestatements are to be processed then they are made as block i.ecompound statement by enclosing them in flower brackets { }.
Syntax :
if (condition){
<statements/expressions>;}
Program 28:
/* Accept a number and find whether it is 0 or not */
main(){int a;clrscr();printf("\n Enter a number : ");
Output: Enter a number : 1The number is not 0
5/11/2018 Fundamentals and C Language - slidepdf.com
http://slidepdf.com/reader/full/fundamentals-and-c-language 37/162
scanf("%d",&a);if(a==0)printf("\n The number is 0");
if(a!=0)printf("\n The number is not 0");
getch();}
2. if-else statement :
If the specified condition is true then the statements orexpressions following the condition will be evaluated, otherwisethe statements or expressions following the ‘else ‘ will beprocessed.
Syntax :
if (condition){
<statements/expressions>}else
{
<statements/expressions>}
Program 29:
/* Accept a number and find whether it is even or odd */
main(){int a;clrscr();printf("\n Enter a number : ");scanf("%d",&a);
if(a%2==0)printf("\n %d is an even number.");
elseprintf("\n %d is an odd number.");
getch();}
Program 30:
Output: Enter a number : 88 is an even number
5/11/2018 Fundamentals and C Language - slidepdf.com
http://slidepdf.com/reader/full/fundamentals-and-c-language 38/162
/* Example on if-else with compound statements*//* Accept 2 numbers and find the big and small number */
main(){int a,b;clrscr();
printf("\n Enter 2 numbers : ");scanf("%d%d",&a,&b);
if(a>b){printf("\n Big = %d",a);printf("\n Small = %d",b);}
else{printf("\n Big = %d",b);printf("\n Small = %d",a);}
getch();}
3. Nested if-else statement :
An if-else statement can be written with in another if-elsestatement and so on.
Syntax :
if (condition){
<if – else statement >}else
{<if- else statements>
}
Program 31:
/* Finding greatest of 3 numbers */
Output: Enter 2 numbers : 4 8
Big = 8Small = 4
5/11/2018 Fundamentals and C Language - slidepdf.com
http://slidepdf.com/reader/full/fundamentals-and-c-language 39/162
main(){int a,b,c,big;clrscr();printf("\n Enter 3 numbers : ");scanf("%d%d%d",&a,&b,&c);
if(a>b)if(a>c)
big = a;else
big = c;else
if(b>c)big = b;
else
big = c;
printf("\n Biggest number : %d",big);getch();
}
4. if-else-if… :
When multiple conditions are to be checked, then if a condition is
false, control is transferred to ‘else’ part where another ‘if’condition is checked and so on. This is also called if-else ladder.
Syntax :
if (condition)<statements/expressions>
elseif (condition)
<statements/expressions>else …
Program 32:
/* Example on else-if ladder *//* Accept student number, marks in 3 sub.
Calculate average and display result.AVERAGE RESULT>75 - Distinction>60 - I Class>50 - II Class
Output:Enter 3 numbers : 4 8
3
5/11/2018 Fundamentals and C Language - slidepdf.com
http://slidepdf.com/reader/full/fundamentals-and-c-language 40/162
>35 - III Classotherwise - Fail */
main(){int sno,m1,m2,m3,tot;float avg;clrscr();printf("\n Enter student number : ");scanf("%d",&sno);printf("\n Enter marks in 3 subjects : ");scanf("%d%d%d",&m1,&m2,&m3);
tot = m1+m2+m3;avg = (float)tot/3;printf("\n Number : %d",sno);
printf("\n Marks : %d %d %d",m1,m2,m3);printf("\n Total : %d",tot);printf("\n Average : %f",avg);printf("\n Result : ");
if(avg>75)printf("Distinction");
else if(avg>60)printf("I Class");
else if(avg>50)printf("II Class");else if(avg>35)
printf("III Class");else
printf("Fail");getch();}
b) Switch – case statement:
The switch statement is a special multi way decision maker thattests whether an expression matches one of the number of constant values and branches accordingly.
Syntax:
switch(expression){
case constant 1 : <statements/expressions>;
case constant 2 : <statements/expressions>;case constant n : <statements/expressions>;default: <statements/expressions>;
}
Output:Enter student number : 101Enter marks in 3 subjects : 60
70 80
Number : 101Marks : 60 70 80Total : 210Average : 70.000000
5/11/2018 Fundamentals and C Language - slidepdf.com
http://slidepdf.com/reader/full/fundamentals-and-c-language 41/162
Program 33:
/* Accept grade 1/2/3 and display designations1 - Officer 2-Manager 3-Clerk */
main(){int grade;clrscr();printf("Enter grade 1/2/3 ");scanf("%d",&grade);
switch(grade){case 1 : printf("\nDesignation is Officer"); break;case 2 : printf("\nDesignation is Manager"); break;case 3 : printf("\nDesignation is Clerk"); break;
default : printf("\nInvalid Designation ");}getch();
}
Conditional operator : (Ternary operator (? :))
Ternary operator checks the condition. If the condition is true thestatements following the ? will be processed otherwise the
statements following the : will be processed.
Syntax :
(condition) ? <statement /expression> : <statement /expression>
Program 34:
/* Big out of two numbers – Example on ternary operator */
main(){int a,b,big;clrscr();
printf("\n Enter 2 numbers : ");scanf("%d%d",&a,&b);big = (a>b)?a:b;printf("\n Big number = %d",big);getch();
Output :Enter 2 numbers : 4
8
Output:Enter grade 1/2/32
5/11/2018 Fundamentals and C Language - slidepdf.com
http://slidepdf.com/reader/full/fundamentals-and-c-language 42/162
}
Looping structures :
The structures which are used to iterate the statementsconditionally are called looping structures. The different types of loops are as follows.
do – while looping structure while looping structure for looping structure
1). do – while looping structure : This is the loop with bottom programming approach. Here thecondition is checked at the bottom of the loop. The loop iteratesminimum once. The control directly enters into the loop, executesthe statements and then checks the condition. The conditionspecified can be simple condition or multiple conditions withlogical operators. The loop can be nested.
Syntax :do{<statements /expressions >
}while(<condition>);
Program 35:
/* Natural numbers from 1 to 5 */main(){int i=1;
clrscr();do {
printf(“%5d “,i);i++;}
while(i<=5);getch();
}2). while looping structure :
This is the loop with top programming approach. Here thecondition is checked at the top of the loop. The loop iterates if the
condition is true. The control will be transferred out of loop if condition is false. The condition specified can be simple conditionor multiple conditions with logical operators. The loop can benested.
Output:1 2 3 4
5/11/2018 Fundamentals and C Language - slidepdf.com
http://slidepdf.com/reader/full/fundamentals-and-c-language 43/162
Syntax :while(<condition>)
{<statements /expressions >
}
Program 36:
/* Example on while loopProgram to print 1 to 5 numbers */
main(){int i;clrscr();
printf("\n Numbers from 1 to 5 :\n\n");i=1;while(i<=5){printf("%5d",i);i++;}
getch();}
Program 37:
/* Program to print numbers between accepted 2 numbers */
main(){int n1,n2;clrscr();printf("\n Enter 2 numbers : ");scanf("%d%d",&n1,&n2);printf("\n The numbers between %d and %d :\n\n",n1,n2);while(n1<=n2){printf("%5d",n1);n1++;}
getch();}
Program 38:
/* Accept a number and find sum of digits in iteg: 346 = 3+4+6 =13 */
Output:
Numbers from 1 to 5 :1 2 3 4 5
Output:Enter 2 numbers : 5 10The numbers between 5 and10 :
Output:Enter a number : 346Sum of digits in 346 =13
5/11/2018 Fundamentals and C Language - slidepdf.com
http://slidepdf.com/reader/full/fundamentals-and-c-language 44/162
main(){int n,t,b,s;clrscr();printf("\n Enter a number : ");scanf("%d",&n);t=n;s=0;while(t>0){b = t%10;s = s+b;t = t/10;}
printf("\n Sum of digits in %d = %d",n,s);getch();
}
Program 39:
/* Accept 2 numbers and find their G.C.D */
main(){int a,b,t;
clrscr();printf("\n Enter 2 numbers : ");scanf("%d%d",&a,&b);t = a%b;while(t!=0){a = b;b = t;t = a%b;}
printf("\n The G.C.D is %d",b);getch();
}
3). for looping structure :
This is the most common loop of ‘C’ language. This loopconsists of three expressions. The first expressions is used to
Output:Enter 2 numbers : 16
40The G.C.D is 8
5/11/2018 Fundamentals and C Language - slidepdf.com
http://slidepdf.com/reader/full/fundamentals-and-c-language 45/162
initialize the variables. If multiple initializations are to be donethen they are separated by comma (,). This is optional part.
The second expression is condition. If the condition is true,the loop iterates and if false the loop terminates the execution.
The condition specified can be simple or multiple conditions withlogical operators. If condition is not specified the loop iteratesinfinitely.
The third expression is increment or decrement part wherethe processing statements can be written. If multiple statementsare to be written then comma is the delimiter. This is optional part.
The above three parts are separated by semi colon (;). If thefor loop is terminated with semicolon, then self looping takes placei.e loop iterates with in itself.
For loop can be nested. When multiple statements are toprocessed with for loop then those statements should be made asa compound statement.
Syntax :for(initialization; condition; increment/decrement )
{<statements / expressions >
}
Program 40:
/* Natural numbers from 1 to 5 */
main(){int i;clrscr();for(i=1;i<=5;i++)
printf("%5d",i);getch();}
Program 41:
/* sum of natural numbers from 1 to 5 */
main()
{int sum,i;
clrscr();for(i=1,sum=0 ; i<=5 ; sum+=i, i++) ;
printf(“Sum is %d”,sum);
Output1 2 3 45
OutputSum is 15
5/11/2018 Fundamentals and C Language - slidepdf.com
http://slidepdf.com/reader/full/fundamentals-and-c-language 46/162
getch();}
Program 42:
/* Nested for loop – matrix */
main(){int i,j;clrscr();for(i=1;i<=3;i++){
for(j=1;j<=3;j++)printf("%5d",j);
printf("\n\n");
}getch();
}
break : To transfer control out of the block forcibly.
Program 43:
/* Example on break */main(){int i;clrscr();i=1;while(i<=10){if(i==5)break;
printf("\n i = %d",i);i++;}
printf("\n The loop breaked at i = %d",i);getch();
}
Output:i = 1i = 2i = 3i = 4The loop breaked at i
Output
1 2 3
1 2 31 2 3
5/11/2018 Fundamentals and C Language - slidepdf.com
http://slidepdf.com/reader/full/fundamentals-and-c-language 47/162
continue:
The control transfers to condition part by skipping all thestatements after "continue"
Program 44:
/* Example on continue */
main(){
clrscr();for(i=1;i<10;i++)
{if(i%2==0)continue;
printf("%3d",i);}
getch();}
Program on nested looping structure:
Program 45:
/* Program to print prime numbers b/w 1 and 30 */
main(){int n,nf,i;clrscr();printf("\n Prime numbers between 1 and 30 :\n\n");
n=1;while(n<=30){
i=1;nf=0;
while(i<=n){
if(n%i==0)nf++;i++;
}if(nf==2)
Output:
1 3 5 7
Output
Prime numbers between 1 and30 :
2 3 5 7 11 13 17 19 23
5/11/2018 Fundamentals and C Language - slidepdf.com
http://slidepdf.com/reader/full/fundamentals-and-c-language 48/162
printf(" %d ",n);n++;
}getch();
}Control structures with conditions using logical operators:
Program 46:
/* Accept age, if it is in between 13 and 19 inclusive, displayteenage */
main(){
int age;clrscr();
printf(“Enter age “);scanf(“%d”,&age);if(age>=13 && age<=19)printf(“\nTeen age”);
elseprintf(“\nNot teen age”);
getch();}
Program 47:
/* Accept mark1, mark2. Calculate total.If marks are >=40 or if total is >80
display Pass otherwise Fail */
main(){
int m1,m2,total;clrscr();printf(“Enter marks in two subjects “);scanf(“%d %d”,&m1,&m2);total = m1 + m2;
if((m1>=40 && m2>=40)||(total>80))printf(“\nResult is PASS ”);
elseprintf(“\nResult is FAIL”);
getch();
}
Output
Enter age 16Teen age
Output
Enter marks in two subjects 6030
5/11/2018 Fundamentals and C Language - slidepdf.com
http://slidepdf.com/reader/full/fundamentals-and-c-language 49/162
Program 48:
/* Accept two numbers n1,n2. If n1 < n2 and if n1 is even numberthen
display natural numbers from n1 to n2 */
main(){int n1,n2,count;
clrscr();printf(“\n Enter any two numbers “);
scanf(“%d %d”&n1,&n2);count=n1;
while( (n1<n2) && (n1%2==0)&&(count<=n2)){
printf(“%5d”,count);count++;
}getch();}
Exercise :
1. Accept a number and reverse the number using for loop(Ex: Input is 193 --> Output should be 391)
1. Accept a number and replace every digit in it with its next digitin natural number
series using for loop.
(Ex: Input is 157 --> Output should be 268 i.e., (1+1 5+1 7+1)Input is 190 --> Output should be 201)
3. Using do-while looping structures, find sum of accepted nnumbers. 4. Accept a number and find whether it is Prime or not.
( Prime number : The number with two factors only and whichcan be divided by 1 and by itself. )
5. Accept a number and find whether it is STRONG or not.(STRONG NUMBER:Sum of factorials of all the digits in the accepted number =
accepted number
Output
Enter any two numbers 49
4 5 6 7 8 9
5/11/2018 Fundamentals and C Language - slidepdf.com
http://slidepdf.com/reader/full/fundamentals-and-c-language 50/162
Ex: 145 is STRONG since 1!+4!+5! = 1+24+120 = 145)
6. Write a program to find out n th Prime number.(HINT : n is input from key board
Ex: Input is 2 --> Output is 3 2nd prime no. is 3Input is 5 --> Output is 11 5th prime no. is 11)
7. Write a program to display the given format.
8. Write a program to display the given format.
9. Write a program to display the give format.
10. Accept day, month , year and display it is valid date or not.
11. Accept marks in three subjects.If marks>=70 in all three subjects display result as First
class.If marks>=70 in any two subjects display result as Second
class.If marks>=70 in any subject display result as Third class.
12.Accept any three numbers and display the middle number i.ethe number which isneither big nor small.
12 23 3 34 4 4 45 5 5 5 5
0 1 1 1 12 0 1 1 12 2 0 1 12 2 2 0 12 2 2 2 0
1 1 1 11
1 2 2 22
1 2 3 3
5/11/2018 Fundamentals and C Language - slidepdf.com
http://slidepdf.com/reader/full/fundamentals-and-c-language 51/162
Arrays
Array is a collection of similar elements (Homogenouselements) stored in adjacent memory locations sharing a commonname.
Array is represented by a variable called subscripted variable. The variable is always represented by its subscript which is theindex number of the element. Every element in an array isidentified by the index. The index starts from 0 . Hence the indexof first element is 0 and last element is size - 1.
The elements of array are always stored in contiguousmemory locations. Hence it is sequential data structure.
Before using an array its type and size must be declared. Anarray is declared in the following way.
Syntax :
<data_type> <variable>[<size_of_array];
Example:
int a[10];float b[5];char c[30];
An array can be initialized at the time of declaration. Here the
array size specification is optional.
Example:
int a[5] = {10, 20, 30, 40, 50};
5/11/2018 Fundamentals and C Language - slidepdf.com
http://slidepdf.com/reader/full/fundamentals-and-c-language 52/162
float b[] = {10.5, 1.3, 2.5};
The array elements are initialized to garbage values by default.
In C arrays there is no concept of boundary checking. Hence,usage of a subscript which exceeds the size of array is allowed.But this causes data loss.
The size of array should be always an integer greater than 0.
int a[-10], b[0], c[2.5] are all invalid declarations
Array declaration of variable size is invalid.
int a = 5;int b[a]
is invalid declaration.
Single dimensional array:
An array with only single subscripted value is called a singledimensional array.
int a[5];'a' is a single dimensional array.
Double dimensional array:
An array with two subscripted values is called a doubledimensional array.
A 2D array is a collection of many 1D arrays.
int a[5][3];'a' is a double dimensional array.
a
0 1 2 3 4
a0 1 2
5/11/2018 Fundamentals and C Language - slidepdf.com
http://slidepdf.com/reader/full/fundamentals-and-c-language 53/162
In the above example 'a' is an array of 5 single dimensionalarrays each of size 3.
Multidimensional arrays:
An array with multiple subscripted values is called a multidimensional array. int a[5][3][4];
In the above example a is a multidimensional array (3D array). 'a'is a collection of 5 2 Dimensional arrays each of size 3x4.
Programs on Single Dimension Arrays
Program 49:
/* Example on array initialization at the time of declaration */
main(){int a[3] = {10, 20, 30};int b[] = {100, 200, 300, 400, 500};int i;clrscr();/* Printing the array elements */printf("\n The elements of a :\n\n");for(i=0;i<3;i++)printf("%5d",a[i]);
printf("\n\n The elements of b :\n\n");for(i=0;i<5;i++)printf("%5d",b[i]);
getch();}
Program 50:
/* Example on array variable declaration and intialization */
Output The elements of a :
10 20 30The elements of b :100 200 300 400
500
5/11/2018 Fundamentals and C Language - slidepdf.com
http://slidepdf.com/reader/full/fundamentals-and-c-language 54/162
main(){int a[3], i;clrscr();a[0] = 10; a[1] = 20; a[2] = 30;printf("\n The elements of a :\n\n");for(i=0;i<3;i++)printf("%5d",a[i]);
getch();}
Program 51:
/* Example on accepting values into array using scanf */
main(){int a[10],n,i;clrscr();printf("\n Enter size of array below 10 : ");scanf("%d",&n);printf("\n Enter %d elements :\n\n ",n);for(i=0;i<n;i++)scanf("%d",&a[i]);
printf("\n\n The elements of a :\n\n");for(i=0;i<n;i++)printf("%5d",a[i]);
getch();}
Program 52:
/* Accept 5 elements into an array and display values
from last cell to first */
main(){int a[5], i;
Output The elements of a :
10 20 30
OutputEnter size of array below 10 :4Enter 4 elements :30 90 50 80The elements of a :
OutputEnter 5 elements :40 20 90 60 50
The elements from last tofirst :
50 60 90 20 40
5/11/2018 Fundamentals and C Language - slidepdf.com
http://slidepdf.com/reader/full/fundamentals-and-c-language 55/162
clrscr();printf("\n Enter 5 elements :\n\n ");for(i=0;i<5;i++)scanf("%d",&a[i]);
printf("\n The elements from last to first :\n\n");for(i=4;i>=0;i--)printf("%5d",a[i]);
getch();}
Program 53:
/* Accept values into an array.Display the contents of array along with sum of all elements */
main(){int a[15],n,i,sum;clrscr();printf("\n Enter size of array : ");scanf("%d",&n);for(i=0;i<n;i++){printf("\n Enter element %d : ",i+1);scanf("%d",&a[i]);}
for(sum=0,i=0;i<n;i++)sum = sum + a[i];
printf("\n\n The elements of the array :\n\n");for(i=0;i<n;i++)printf("%5d",a[i]);
printf("\n\n Sum of elements of array : %d",sum);getch();
}
Program 54:
/* Accept some numbers into an array and find sum of even andodd numbers */
OutputEnter size of array : 4Enter element 1 : 23Enter element 2 : 45Enter element 3 : 56Enter element 4 : 67
The elements of the array :23 45 56 67
Sum of elements of array :
5/11/2018 Fundamentals and C Language - slidepdf.com
http://slidepdf.com/reader/full/fundamentals-and-c-language 56/162
main(){int a[15], n, even, odd, i;clrscr();printf("\n Enter size of array : ");scanf("%d",&n);for(i=0;i<n;i++){printf("\n Enter element %d : ",i+1);scanf("%d",&a[i]);}
for(even=odd=i=0;i<n;i++)if(a[i]%2 == 0)even += a[i];else
odd += a[i];printf("\n Even sum : %d",even);printf("\n\n Odd sum : %d",odd);getch();
}
Program 55:
/* Accept any 4 elements into an array and store the sum in last
cell */
main(){int a[5],i;clrscr();
printf("\n Enter 4 elements :\n\n ");for(i=0;i<4;i++)scanf("%d",&a[i]);
for(i=0,a[4]=0;i<4;i++)a[4] += a[i];
printf("\n The elements of the array :\n\n");for(i=0;i<5;i++)printf("%5d",a[i]);
getch();}
Program 56:
/* Accept 5 numbers into an array andcopy all these elements into another array */
OutputEnter size of array : 4Enter element 1 : 34Enter element 2 : 55Enter element 3 : 17Enter element 4 : 26
Even sum : 60
Odd sum : 72
Output Enter 4 elements :20 40 10 30The elements of the
array :
5/11/2018 Fundamentals and C Language - slidepdf.com
http://slidepdf.com/reader/full/fundamentals-and-c-language 57/162
main(){int a[5],b[5],i;clrscr();
printf("\n Enter 5 elements :\n\n ");for(i=0;i<5;i++)scanf("%d",&a[i]);
for(i=0;i<5;i++)b[i] = a[i];
printf("\n The elements of a :\n\n");for(i=0;i<5;i++)printf("%5d",a[i]);
printf("\n\n The elements of b :\n\n");for(i=0;i<5;i++)printf("%5d",b[i]);
getch();}
Program 57:
/* Accept 5 numbers into an array andcopy all these elements into another array in reverse order */
main(){int a[5],b[5],i;clrscr();printf("\n Enter 5 elements :\n\n ");for(i=0;i<5;i++)scanf("%d",&a[i]);
for(i=0;i<5;i++)b[4-i] = a[i];
printf("\n The elements of a :\n\n");for(i=0;i<5;i++)printf("%5d",a[i]);
printf("\n\n The elements of b :\n\n");for(i=0;i<5;i++)printf("%5d",b[i]);
getch();}
Program 58:
OutputEnter 5 elements :20 40 30 80 10The elements of a :20 40 30 80 10
The elements of b :20 40 30 80 10
OutputEnter 5 elements :
30 10 20 60 50The elements of a :30 10 20 60 50
The elements of b :50 60 20 10 30
5/11/2018 Fundamentals and C Language - slidepdf.com
http://slidepdf.com/reader/full/fundamentals-and-c-language 58/162
/* Accept n elements into an array and reverse its contentswith out using any temporary array */
main(){int a[15],n,i,t;clrscr();printf("\n Enter no. of elements : ");scanf("%d",&n);printf("\n Enter %d elements :\n\n ",n);for(i=0;i<n;i++)scanf("%d",&a[i]);
printf("\n The elements before reversing a :\n\n");for(i=0;i<n;i++)printf("%5d",a[i]);
for(i=0;i<n/2;i++){
t = a[i];a[i] = a[n-i-1];a[n-i-1] = t;}
printf("\n\n The elements after reversing a :\n\n");for(i=0;i<n;i++)printf("%5d",a[i]);
getch();}
Program 59:
/* Fibonacci series using arrays 0 1 1 2 3 5 8 13 ….*//* Program to generate 10 fibonacci numbers starting from 0 */
main(){int a[10],i;clrscr();a[0] = 0; a[1] = 1;
for(i=2;i<10;i++)a[i] = a[i-1] + a[i-2];
printf("\n The Fibonacci series :\n\n");for(i=0;i<10;i++)
printf("%5d",a[i]);
getch();
}
Program 60:
/* Adding 2 arrays */
OutputEnter no. of elements : 4Enter 4 elements :40 20 80 60The elements before reversing
a :40 20 80 60The elements after reversin
OutputThe Fibonacci series :0 1 1 2 3 5 8 13
21 34
5/11/2018 Fundamentals and C Language - slidepdf.com
http://slidepdf.com/reader/full/fundamentals-and-c-language 59/162
main(){int a[5],b[5],c[5],i;clrscr();
printf("\n Enter 5 elements of array a :\n\n ");for(i=0;i<5;i++)scanf("%d",&a[i]);
printf("\n Enter 5 elements of array b :\n\n ");for(i=0;i<5;i++)scanf("%d",&b[i]);
for(i=0;i<5;i++)c[i] = a[i] + b[i];
printf("\n The elements of array c :\n\n");for(i=0;i<5;i++)printf("%5d",c[i]);
getch();}
Program 61:
/* Linear Sorting -Arrange the values of array in ascending order */main(){int a[5],i,j,t;clrscr();printf("\n Enter 5 values : ");for(i=0;i<5;i++)scanf("%d",&a[i]);
/* linear sorting logic*/for(i=0;i<5;i++)for(j=i+1;j<5;j++)if(a[i]>a[j]){
t=a[i];a[i]=a[j];
a[j]=t;}
printf("\n\nSorted values \n");for(i=0;i<5;i++)printf("%5d",a[i]);
OutputEnter elements of array a
:10 40 70 60 30Enter elements of array
b :15 75 25 35 55The elements of array c :
OutputEnter 5 values : 40 20 10 90
60Sorted values
5/11/2018 Fundamentals and C Language - slidepdf.com
http://slidepdf.com/reader/full/fundamentals-and-c-language 60/162
getch();}
Program 62:
/* Bubble Sorting -Arrange the values of array in ascending order */main(){int a[5],i,j,t;clrscr();printf("\n Enter 5 values ");for(i=0;i<5;i++)
scanf("%d",&a[i]);/* bubble sorting */for(i=0;i<5;i++)for(j=0;j<4-i;j++)
if(a[j]>a[j+1]){
t=a[j];a[j]=a[j+1];a[j+1]=t;
}printf("\n\nSorted values \n");for(i=0;i<5;i++)
printf("%5d",a[i]);
getch();}Programs on Double Dimension Arrays
Program 63:
/* Example on 2D Array declaration */main(){int a[2][3] = { {10,20,30}, {40,50,60} };int b[3][2] = { 10,20,30,40,50,60 };int c[2][2];c[0][0] = 10; c[0][1] = 20;c[1][0] = 30; c[1][1] = 40;clrscr();printf("\n\n Elements of a :\n");printf("\n%3d%3d%3d",a[0][0],a[0][1],a[0][2]);printf("\n%3d%3d%3d",a[1][0],a[1][1],a[1][2]);printf("\n\n Elements of b :\n");
printf("\n%3d%3d",b[0][0],b[0][1]);printf("\n%3d%3d",b[1][0],b[1][1]);printf("\n%3d%3d",b[2][0],b[2][1]);printf("\n\n Elements of c :\n");printf("\n%3d%3d",c[0][0],c[0][1]);
OutputEnter 5 values 40 10 20 9060Sorted values
OutputElements of a :
10 20 3040 50 60Elements of b :10 2030 4050 60Elements of c :10 2030 40
5/11/2018 Fundamentals and C Language - slidepdf.com
http://slidepdf.com/reader/full/fundamentals-and-c-language 61/162
printf("\n%3d%3d",c[1][0],c[1][1]);getch();
}
Program 64:
/* Accept elements into 3x3 2D array and display the same */main(){int a[3][3],i,j;clrscr();printf("\n Enter elements of A :\n");for(i=0;i<3;i++)for(j=0;j<3;j++){printf("\n Enter element (%d,%d) : ",i+1,j+1);
scanf("%d",&a[i][j]);}
printf("\n\n Elements of A :\n\n");for(i=0;i<3;i++){for(j=0;j<3;j++)printf("%5d",a[i][j]);
printf("\n\n");}
getch();}
Program 65:
/* Accept a 3x3 matrix and display the matrix along with row sum*/
main(){int a[3][3],i,j,sum;clrscr();
printf("\n Enter elements of A :\n");for(i=0;i<3;i++)for(j=0;j<3;j++){printf("\n Enter element (%d,%d) : ",i+1,j+1);scanf("%d",&a[i][j]);
}
printf("\n\n The elements of A along with row sum :\n\n");
for(i=0;i<3;i++)
OutputEnter elements of A :Enter element (1,1) :
12Enter element (1,2) :
23Enter element (1,3) :
34Enter element (2,1) :
45Enter element (2,2) :
56Enter element (2,3) :
67Enter element (3,1) :
OutputEnter elements of A :Enter element (1,1) : 12Enter element (1,2) : 23Enter element (1,3) : 34Enter element (2,1) : 45Enter element (2,2) : 56Enter element (2,3) : 67Enter element (3,1) : 78Enter element (3,2) : 89Enter element (3,3) : 90
The elements of A alongwith row sum :12 23 34 69
45 56 67 168
78 89 90 257
5/11/2018 Fundamentals and C Language - slidepdf.com
http://slidepdf.com/reader/full/fundamentals-and-c-language 62/162
{for(sum=j=0;j<3;j++){sum += a[i][j];printf("%5d",a[i][j]);
}printf("%5d",sum);printf("\n\n");}
getch();}
Program 66:
/* Declare a 4x4 matrix.Accept a 3x3 matrix.Store the row sum into last column i.e., 4th column of each rowStore the column sum into last row i.e., 4th row of each columnStore the diagonal sum into cell where 4th row 4th column
intersect */
main(){int a[4][4],i,j;clrscr();
printf("\n Enter elements of A :\n");for(i=0;i<3;i++)for(j=0;j<3;j++){printf("\n Enter element (%d,%d) : ",i+1,j+1);
OutputEnter elements of A :Enter element (1,1) : 12Enter element (1,2) : 23Enter element (1,3) : 34Enter element (2,1) : 45Enter element (2,2) : 56Enter element (2,3) : 67Enter element (3,1) : 78Enter element (3,2) : 89Enter element (3,3) : 90The elements of A along
with row,column, diagonal
sum :12 23 34 69
45 56 67 168
78 89 90 257
5/11/2018 Fundamentals and C Language - slidepdf.com
http://slidepdf.com/reader/full/fundamentals-and-c-language 63/162
scanf("%d",&a[i][j]);}
for(i=0;i<3;i++){a[3][i] = 0;a[i][3] = 0;}
a[3][3] = 0;for(i=0;i<3;i++)for(j=0;j<3;j++){a[i][3] += a[i][j];a[3][i] += a[j][i];if(i==j)a[3][3] += a[i][j];
}
printf("\n\n The elements of A along with row,column,diagonal sum :\n\n");
for(i=0;i<4;i++){for(j=0;j<4;j++)printf("%5d",a[i][j]);
printf("\n\n");}
getch();
}
Program 67:
/* Accept a 3x3 matrix and copy elements into another matrix */
main(){int a[3][3],b[3][3],i,j;clrscr();printf("\n Enter elements of A :\n");for(i=0;i<3;i++)
for(j=0;j<3;j++){printf("\n Enter element (%d,%d) : ",i+1,j+1);scanf("%d",&a[i][j]);
}
Output
Enter elements of A :Enter element (1,1) :12Enter element (1,2) :23Enter element (1,3) :34Enter element (2,1) :45Enter element (2,2) :56
Enter element (2,3) :67Enter element (3,1) :78Enter element (3,2) :89Enter element 3 3 :
5/11/2018 Fundamentals and C Language - slidepdf.com
http://slidepdf.com/reader/full/fundamentals-and-c-language 64/162
for(i=0;i<3;i++)for(j=0;j<3;j++)b[i][j] = a[i][j];
printf("\n\n The elements of A :\n\n");for(i=0;i<3;i++){for(j=0;j<3;j++)printf("%5d",a[i][j]);
printf("\n\n");}
printf("\n\n The elements of B :\n\n");for(i=0;i<3;i++){for(j=0;j<3;j++)printf("%5d",b[i][j]);
printf("\n\n");}
getch();}
Exercise:
Accept values into single dimension array of 10 cells and display
sum of odd position values. Accept values into single dimension array of 10 cells and display
sum of single digit numbers, two digit numbers and multi digitnumbers
Accept values into double dimension array of 3 x 3. Sort the entirearray.
Accept values into double dimension array and transpose them i.echange rows as columns and columns as rows.
Accept values into double dimension array and perform column
sorting. Do a program for matrix multiplication.
Character Handling
Combination of characters is called string. In ‘C’ the strings areconstructed using character arrays.
The procedure of declaring character array is almost like otherdata types such as integer and floats.Syntax :
Char array_name[size];
5/11/2018 Fundamentals and C Language - slidepdf.com
http://slidepdf.com/reader/full/fundamentals-and-c-language 65/162
Example :char name[20];char line[80];
The basic structure of character arrays is as followschar name[7] = “PREM”;
nameP R E M \00 1 2 3 4
Character string always ends with NULL character i.e \0.
Program 68:
/* Example on string declaration */main()
{char a[10] = "Infotech";char b[] = { 'C','o','m','p','u','t','e','r','s','\0'};clrscr();printf("\n The string a is : %s",a);printf("\n The string b is : %s",b);getch();
}
Program 69:
/* Accepting a character and string as input from keyboard */main(){char ch;char a[10];clrscr();printf("\n Enter a single character : ");scanf("%c",&ch);printf("\n The character is : %c",ch);printf("\n\n Enter a name : ");scanf("%s",a);printf("\n The name is : %s",a);getch();
}Program 70:
/* Accept student number, name, marks in 3 subjects.
Find total marks and display the student details */
main(){int sno, m1, m2, m3, tot;
Output:
The string a is : InfotechThe string b is : Computers
Output:Enter a single
character : IThe character is : I
Enter a name : prem
5/11/2018 Fundamentals and C Language - slidepdf.com
http://slidepdf.com/reader/full/fundamentals-and-c-language 66/162
char sna[20];clrscr();printf("\n Enter student number : ");scanf("%d",&sno);printf("\n Enter student name : ");scanf("%s",sna);printf("\n Enter marks in 3 sub : ");scanf("%d%d%d",&m1,&m2,&m3);tot = m1+m2+m3;printf("\n Number : %d",sno);printf("\n Name : %s",sna);printf("\n Total : %d",tot);getch();
}
gets() : Accepts strings as input from keyboard. Its prototype is
defined in <stdio.h> header file.
Syntax:char *gets(char *string);
puts() : Prints strings on the monitor. Its prototype is defined in<stdio.h> header file.
Syntax:
int puts(const char *s)
Program 71:
/* Example on puts() and gets()Accept a sentence and display it */
#include <stdio.h>main(){char a[20];clrscr();puts("Enter a sentence : ");gets(a);puts("The sentence is ");puts(a);getch();
}getchar() - Takes a character as input from keyboard. Prototype
is in <stdio.h>
Syntax:int getchar(void);
Output:Enter student number : 1Enter student name : premEnter marks in 3 sub : 67 78
89
Number : 1Name : prem
Output:Enter a sentence :Infotech ComputerCentre
The sentence isInfotech Computer
5/11/2018 Fundamentals and C Language - slidepdf.com
http://slidepdf.com/reader/full/fundamentals-and-c-language 67/162
putchar() - Prints a character on monitor . Prototype is in<stdio.h>
Syntax:int putchar(int ch);
Program 72:
/* Example on getchar() and putchar() */#include <stdio.h>main(){char ch;clrscr();printf("\n Enter a character : ");ch = getchar();
printf("\n The character is : ");putchar(ch);getch();
}
getch() - Accepts a key stroke and does not print it on monitor.Prototype in <conio.h>
Syntax :
int getch(void); getche() - Accepts a key stroke and prints it on monitor .Prototype in <conio.h> Syntax:
int getche(void);
Program 73:
/* Example on getch() and getche() */main(){char ch;clrscr();printf("\n Press any key : ");ch = getch();printf("\n U have pressed %c",ch);printf("\n\n Press another key : ");
ch = getche();printf("\n U have pressed %c",ch);getch();
}Program 74:
Output:Enter a character : IThe character is : I
Output:Press any key :U have pressed I
Press another key :AU have pressed A
5/11/2018 Fundamentals and C Language - slidepdf.com
http://slidepdf.com/reader/full/fundamentals-and-c-language 68/162
/* Finding length of string *//* Every string is terminated by NULL character i.e., '\0' */
main(){char a[20];int l;clrscr();puts("Enter a string : ");gets(a);for(l=0; a[l] != '\0'; l++);printf("\nThe length of string is : %d",l);getch();
}
strlen() - Returns length of a string . Prototype in string.h
Syntax:int strlen(const char *s);
Program 75:
/* Example on strlen()Find length of accepted string*/#include <string.h>main(){char a[20];int l;clrscr();
puts("Enter a string :");gets(a);
l = strlen(a);
printf("\nLength of a is : %d",l);getch();
}
Program 76:
Output:Enter a string :INFOTECHThe length of string is :8
Output:Enter a string :INFOTECHLength of a is : 8
5/11/2018 Fundamentals and C Language - slidepdf.com
http://slidepdf.com/reader/full/fundamentals-and-c-language 69/162
/* Copying contents of one string to other */
main(){char a[20],b[20];int i;clrscr();puts("Enter a string : ");gets(a);
for(i=0; a[i] != '\0'; i++)b[i] = a[i];
b[i] = '\0';
puts("The new string is : ");puts(b);getch();
}
strcpy() - Copies one string into another . Prototype in <string.h>
Syntax:char *strcpy(char *dest, const char *src);
Program 77:
/* Example on strcpy() */
#include <string.h>main(){char a[20], b[20];clrscr();puts("Enter a string :");gets(a);strcpy(b,a);printf("\n\nThe string a is : %s",a);printf("\n\nThe string b is : %s",b);getch();
}
Program 78:
Output:Enter a string :
INFOTECH
The new string is :INFOTECH
Output:Enter a string :
INFOTECHThe string a is : INFOTECHThe string b is : INFOTECH
5/11/2018 Fundamentals and C Language - slidepdf.com
http://slidepdf.com/reader/full/fundamentals-and-c-language 70/162
/* Example on reversing a string without using other temporarystring */main(){int i,l;char a[20], ch;clrscr();puts("Enter a string :");gets(a);/* Finding length of string a */for(l=0; a[l] != '\0'; l++);/* Reversing the string */for(i=0; i<l/2; i++){ch = a[i];
a[i] = a[l-i-1];a[l-i-1] = ch;}
/* Printing the reverse string */puts("The reverse of a is :");puts(a);getch();
}
strrev() - Reverses the contents of a specified string. Prototype in<string.h >
Syntax:char *strrev(char *s);
Program 79:
/* Example on strrev() */#include <string.h>
main(){char a[20];clrscr();
puts("Enter a string :");gets(a);
strrev(a);
puts("Reverse of a is :");puts(a);
Output:Enter a string :
INFOTECHThe reverse of a is:HCETOFNI
Output:Enter a string :
INFOTECHReverse of a is :HCETOFNI
5/11/2018 Fundamentals and C Language - slidepdf.com
http://slidepdf.com/reader/full/fundamentals-and-c-language 71/162
getch();}strcat() - Joins the specified 2 strings. Prototype in <string.h>
Syntax:
char *strcat(char *dest, const char *src);
Program 80:
/* Example on strcat() – To concatenate two strings */#include <string.h>main(){char a[20],b[20];clrscr();puts("Enter string a :");
gets(a);puts("Enter string b :");gets(b);strcat(a,b);printf("\n String a is : %s",a);printf("\n String b is : %s",b);getch();
}
strcmp() - Compares specified 2 strings . Prototype in <string.h>Syntax :int strcmp(const char *s1, const char *s2);Returns a value that is < 0 if s1 is less than s2. == 0 if s1 isthe same as s2. > 0 if s1 is greater than s2.
Program 81:
/* Example on strcmp() - To compare two accepted strings */#include <string.h>main(){char a[20],b[20];int res;clrscr();puts("Enter string a :");gets(a);puts("Enter string b :");gets(b);
res = strcmp(a,b);if(res == 0)
printf("\nThe 2 strings are equal.");else
printf("\nThe 2 strings are unequal.");
Output:Enter string a :
INFOEnter string b :TECH
String a is : INFOTECHString b is : TECH
Output:Enter string a :
INFOEnter string b :TECH
The 2 strings areune ual
5/11/2018 Fundamentals and C Language - slidepdf.com
http://slidepdf.com/reader/full/fundamentals-and-c-language 72/162
getch();}
Program 82:
/* Accept a string from key board. Find whether it is palindrome ornot */
#include <string.h>main(){char a[20],b[20];int res;clrscr();puts("Enter a string :");gets(a);
strcpy(b,a);strrev(b);res = strcmp(a,b);if(res == 0)printf("\nThe string is palindrome.");
elseprintf("\nThe string is not palindrome.");
getch();}
ASCII : It stands for American Standard Code for InformationInterchange There are 0 to 255 ASCII characters. It is developed byANSI (American National Standard Institution). Every character ishaving its corresponding ASCII number.
Example :A to Z - 65 to 90a to z - 97 to 1220 to 9 - 48 to 57Blank - 32
Program 83:
/* Printing ASCII chart - 0 to 255 */
main(){int i;
clrscr();
for(i=0;i<=255;i++)printf("%d %c ",i,i);
Output:Enter a string :MALAYALAM
The string ispalindrome.
Output0 1 2 3 4☺ ☻ ♥ ♦ 5 6 7 8 9♣ ♠ 10
14 15 16 17♫ ☼ ► ◄
18 19 ‼ 20 ¶ 21 § 22↕ 23 24 25 26▬ ↨ ↑ ↓ ← ∟ ↔
5/11/2018 Fundamentals and C Language - slidepdf.com
http://slidepdf.com/reader/full/fundamentals-and-c-language 73/162
getch();}
Program 84:
/* Accept a string and find number of blank spaces and words in it*/
main(){int i,nb;char a[20];
clrscr();puts("Enter a string :");gets(a);
for(i=0,nb=0;a[i]!='\0';i++)if(a[i]==32)nb++;
printf("\nNumber of blank spaces : %d",nb);
printf("\nNumber of words : %d",nb+1);getch();}
Program 85:
/* Accept a string and display it in lower case *//* Difference between lowercase and uppercase letter is 32 *//* lowercase = uppercase + 32 */main(){int i;char a[25];
clrscr();puts("Enter a string :");gets(a);
for(i=0;a[i]!='\0';i++)
if(a[i]>='A' && a[i]<='Z')a[i] = a[i] + 32;
puts("\nLower case string is :");puts(a);
OutputEnter a string :
INFOTECH COMPUTER CENTRENumber of blank spaces : 2Number of words : 3
OutputEnter a string :INFOTECH COMPUTER CENTRE
Lower case string is :infotech computer center
5/11/2018 Fundamentals and C Language - slidepdf.com
http://slidepdf.com/reader/full/fundamentals-and-c-language 74/162
getch();}
Program 86:
/* Accept a string and convert it into title case *//* Title case : 1st alphabet of each word in uppercase */
main(){int i;
char a[25];clrscr();puts("Enter a string :");gets(a);
if(a[0] == '\0'){printf("\nString not entered.\nTry again . . .");getch();
exit(1);}
if(a[0]>='a' && a[0]<='z')a[0] = a[0] - 32;
for(i=1;a[i]!='\0';i++){if(a[i-1]==32){if(a[i]>='a' && a[i]<='z')a[i] = a[i] - 32;
continue;}
if(a[i]>='A' && a[i]<='Z')a[i] = a[i] + 32;
}
puts("\nTitle case string :");
puts(a);
getch();}
OutputEnter a string :infotech computercentre
Title case string :
5/11/2018 Fundamentals and C Language - slidepdf.com
http://slidepdf.com/reader/full/fundamentals-and-c-language 75/162
Program 87:
/* Accept a string and find number of blankspaces, vowels,consonants,
digits, special characters in it */
main()
{int nb=0,nv=0,nc=0,nd=0,ns=0,i;char a[30];
clrscr();puts("Enter a string : ");gets(a);for(i=0;a[i]!='\0';i++){
if(a[i] == ' ')nb++;else if(a[i]>='0' && a[i]<='9')nd++;
else if((a[i]>='A' && a[i]<='Z') || (a[i]>='a' && a[i]<='z')){switch(a[i]){case 'a' :case 'e' :case 'i' :case 'o' :case 'u' :case 'A' :case 'E' :case 'I' :case 'O' :case 'U' :nv++;
break;default :nc++;
}}
OutputEnter a string :Infotech Computer Centre
2007!
Number of blanks : 3Number of digits : 4Number of vowels : 8Number of consonants : 14
5/11/2018 Fundamentals and C Language - slidepdf.com
http://slidepdf.com/reader/full/fundamentals-and-c-language 76/162
elsens++;
}printf("\nNumber of blanks : %d",nb);printf("\nNumber of digits : %d",nd);printf("\nNumber of vowels : %d",nv);printf("\nNumber of consonants : %d",nc);printf("\nNumber of special characters : %d",ns);
getch();}
Program 88:
/* Encrypt a string using ROT5 technique.ROT5 : Replace a character with 5th character from current
position */
main(){char a[20];int i;clrscr();
puts("Enter a string : ");gets(a);
for(i=0;a[i]!='\0';i++){if(a[i] >= 'A' && a[i] <= 'Z')a[i] = (a[i]-65+5)%26+65;
else if(a[i] >= 'a' && a[i] <= 'z')a[i] = (a[i]-97+5)%26+97;
else if(a[i] >= 48 && a[i] <= 57)a[i] = (a[i]-48+5)%10+48;
elsea[i] = a[i]+5;
}puts("The encoded string : ");puts(a);getch();
}
Program 89:
/* Example on array of strings -
Explanation : In the below program ‘a’ is an array of strings.‘a’ can hold a maximum of 5 strings each of maximum length
10 */
main()
OutputEnter a string :
INFOTECH COMPUTERSThe encoded string :NSKTYJHM%HTRUZYJWX
OutputEnter name 1 : infoEnter name 2 :techEnter name 3 :premEnter name 4 :kumarEnter name 5 :srinuThe names are :info
5/11/2018 Fundamentals and C Language - slidepdf.com
http://slidepdf.com/reader/full/fundamentals-and-c-language 77/162
{int i;char a[5][10];clrscr();for(i=0;i<5;i++){printf("\n Enter name %d : ",i+1);scanf("%s",a[i]);}
printf("\n The names are :\n");for(i=0;i<5;i++)printf("\n %s",a[i]);
getch();}
Exercise:
Accept any string and construct a new string with consonantspresent in it.Example : Accepted string : INFOTECH new string : NFTCH
Accept any string and display its abbreviation.Example :Accepted string : Andhra Pradesh State Road TransportCorporation.Abbriviation : APRTC
Accept any sentence and display all palindrome words present init.Example : madam uses liril - madam liril
Accept any four digit number display it in words.Example : 2845 – Two thousand eight hundred and forty five
Accept multiple lines of text and display number of sentences
present in it.
Input your class students names and sort them in alphabeticalorder.
5/11/2018 Fundamentals and C Language - slidepdf.com
http://slidepdf.com/reader/full/fundamentals-and-c-language 78/162
Header Files and built in functions
Header files : ‘C’ is called function oriented language. It contains
rich set of built in functions placed in predefined files called headerfiles. There are 29 header files with approximately 400 functions.Header files contains predefined functions, global variables. Theyare with file extension “.h”
Header files are not compiled separately. The header files can beincluded in C program using the macro definition “# include “command. The header files are included at the top of the program.
The header files can be declared in one of the following way
# include <header file name>or# incude “header file name >
C supports two type of header filesbuilt in header filesuser defined header files
Built in header files are as follows
alloc.h assert.h bios.h conio.h ctype.hdir.h dos.h errno.h fcntl.h float.h
5/11/2018 Fundamentals and C Language - slidepdf.com
http://slidepdf.com/reader/full/fundamentals-and-c-language 79/162
graphics.h io.h limits.h mem.h process.h
math.h setjmp.h share.h signal.h stdarg.h
stddef.h stdio.h stdlib.h string.h sys\stat.hsys\types.h
sys\timeb.h
time.h values.h
alloc.h : Memory allocation built in functions are available inheader file alloc.hFunctions are as follows.
calloc malloc free
assert.h : To test conditions and take action i.e programdiagnosticsFunctions are as follows.
assert
bios.h : Functions related to basic input output operations relatedto biosFunctions are as follows. bioscom biosmemory biosdisk biosprintbiosequip biostime bioskey
conio.h : Functions related to console input output operationsFunctions are as follows
clreol gotoxy clrscr cprintf cputs kbhit
getch getche putch puttext gettext Textbackground
wherex textcolor
wherey textmode
window
ctype.h: Functions related to character type identification.Functions are as follows
isacii isspac
e
isalnu
m
isupper isalpha
isxdigit iscntrl toascii isdigit isgraphtolower
islower isprint toupper ispunct
5/11/2018 Fundamentals and C Language - slidepdf.com
http://slidepdf.com/reader/full/fundamentals-and-c-language 80/162
dir.h : Functions related to directories, subdirectories and diskoperationsFunctions are as follows
dos.h : Functions related to disk operating system and interruptprogramming.Functions are as follows.
graphics.h : Functions related to graphical programs.
Functions are as follows
bar floodfill bar3d getarccoords
getaspectratio
circle cleardevice learviewport
getbkcolor getcolor
closegraph getdefaultpalette
detectgraph
getdrivername
drawpoly
getfillpatter
n
ellipse getfillsettin
gs
fillellipse Getgraphm
odefillpoly getimage getlinesettings
Getviewsettings
getmaxcolor
getx getmaxmode
gety getmaxx Graphdefaults
getmaxy grapherrormsg
getmodename
getmoderange
Installuserf ont
rectangle getpalette graphresult getpalettesize
Imagesize
getpixel initgraph gettextsettings installuserdriver Line
registerbgidriver
linerel registerbgif ont
lineto Restorecrtmode
moverel sector moveto outtext Setallpalette
outtextxy setaspectratio
pieslice setbkcolor Putimage
setcolor putpixel setfillpattern
setfillstyle settextstyle
setgraphbufsize
Setusercharsize
setgraphmode
setviewport setlinestyle
setvisualpage
setpalette setwritemode
setrgbcolor textheight
chdir getdisk findfirst mkdir
findnext
mktemp fnmerge rmdir
fnsplit searchpath getcurdir setdiskgetcwd
5/11/2018 Fundamentals and C Language - slidepdf.com
http://slidepdf.com/reader/full/fundamentals-and-c-language 81/162
setrgbpalette
textwidth settextjustify
io.h : The functions related with general input output operations.Functions are as follows
limits.h : Functions or constants related with checking the limitsof data types.
They are as follows
math.h : Functions related to mathematical calculations They are as follows
abs floor acos fmod asin frexpatan hypot atan2 labs atof ldexpcabs log ceil log10 cos fabsmatherr cosh modf exp poly Powpow10 sqrt sin tan sinh tanh
mem.h : Functions related to memory manipulations
process.h : Functions related with process control.
setjmp.h : Functions perform local and non local jump activities.
share.h : Functions and constants related with file sharing, inmulti user environment
signal.h : Functions related with signal sending or receiving.
stdarg.h : Functions related with standard argument list
stddef.h : Functions or constants related with Standarddefinitions.
stdio.h : The functions related with standard input outputoperations.
The functions are as follows.
clearerr flushall fclose fopen fcloseall fprintf fdopen fputc feof fputchar ferror fputsfflush fread fgetc freopen fgetchar fscanf fgetpos fseek fgets fsetpos fileno ftell
5/11/2018 Fundamentals and C Language - slidepdf.com
http://slidepdf.com/reader/full/fundamentals-and-c-language 82/162
putw fwrite remove getc rename Getchar
rewind gets scanf getw setbuf perrorsetvbuf printf sprintf putc sscanf putcha
rputs strerror tmpfile vfscanf tmpnam vprintf
ungetc vscanf unlink vsprintf vfprintf vsscanf
stdlib.h : Functions frequently used are available in standardlibrary.
string.h : Functions related with string manipulations. They are as follows
memccpy
strchr memchr strcmp memcmp strcmpi
memcpy strcpy memicmp
strcspn memmove
strdup
memset movedata
strerror movmem stricmp setmem
strlen stpcpy strlwr strcat strncat strncmp
strrev strncmpi strset strncpy strspn strnicmp
strstr strnset strtok strupr strrchr
sys \ stat.h : Functions related with file status bits and statstructure
time.h : Time manipulating functions are available in this headerfile.
sys\timeb.h: Functions to store the current system time. values.h: Defines UNIX compatible constants for limitsto float and double values. Functions or constants are as follows.
Progarms on <math.h> header file
Program 90:
/* abs() - Returns absolute value */
Outputabs(-5) = 5
5/11/2018 Fundamentals and C Language - slidepdf.com
http://slidepdf.com/reader/full/fundamentals-and-c-language 83/162
# include <math.h>main(){clrscr();printf("abs(-5) = %d",abs(-5));getch();
}
Program 91:
/* acos() - Returns arc cos valueasin() - Returns arc sin valueatan() - Returns arc tan value*/
# include <math.h>main()
{clrscr();printf("acos(1) = %f\n",acos(1));printf("asin(1) = %f\n",asin(1));printf("atan(1) = %f\n",atan(1));getch();
}
Program 92:
/* ceil() – Higher integer of the real valuefloor() – Lower integer of the real value */
# include <math.h>main(){clrscr();printf("ceil(7.2) = %f\n",ceil(7.2));printf("floor(7.2) = %f\n",floor(7.2));getch();
}
Program 93:
/* exp() - returns exponential valuepow() - returns power of numbersqrt() - returns square root of number */
# include <math.h>
main(){clrscr();
Output
ceil(7.2) = 8.000000floor(7.2) = 7.000000
Outputacos(1) = 0.000000asin(1) = 1.570796atan(1) = 0.785398
Outputexp(5) = 148.413159pow(5.0,3.0) =125.000000
5/11/2018 Fundamentals and C Language - slidepdf.com
http://slidepdf.com/reader/full/fundamentals-and-c-language 84/162
printf("exp(5) = %f \n",exp(5));printf("printf("pow(5.0,3.0) = %f\n",pow(5.0,3.0));printf("sqrt(625.0) = %f\n",sqrt(625.0));getch();
}
Programs on <ctype.h> header files
Program 94:
/* isalnum() - Returns 1 if alphabet or number */# include <ctype.h># include <stdio.h>main(){
char ch;clrscr();printf("Enter character ");ch=getchar();if(isalnum(ch)>0)printf("It is alphanumeric character ");
elseprintf("It is special character");
getch();
}Program 95:
/* isalpha() - Returns 1 if alphabetisdigit() - Returns 1 if digitiscntrl() - Returns 1 if control characterislower() - Returns 1 if lower case characterisupper() - Returns 1 if upper case character */
# include <ctype.h># include <stdio.h>main(){char ch;clrscr();printf("Enter character ");ch=getchar();if(isalpha(ch)>0)printf("It is alphabetic character \n");
else
if(isdigit(ch)>0)printf("It is Numeric character \n");
elseprintf("It is special character \n");
if(islower(ch))
OutputEnter character IIt is alphanumeric
character
OutputEnter character IIt is alphabeticcharacterIt is upper case
5/11/2018 Fundamentals and C Language - slidepdf.com
http://slidepdf.com/reader/full/fundamentals-and-c-language 85/162
printf("It is lower case character \n");elseif(isupper(ch))
printf("It is upper case character");getch();}
Program 96:/* ispunct() - Returns 1 if puctuation
isspace() - Returns 1 if space */# include <ctype.h># include <stdio.h>main(){char ch;clrscr();
printf("Enter character ");ch=getchar();if(ispunct(ch)>0)printf("It is punctuation character \n");
elseif(isspace(ch)>0)
printf("It is space character \n");else
printf("It is alphanumeric character \n");
getch();}User defined header files : User can define header files withrequired file name but with file extension “.h”.
Develop a file with any file name and with extension .h. Writeglobal variables and functions in it. Save it. Example : MyFun.h
Now open another file where we write the main() function. Includethe header file at the top of the program with # include macro.
Example:
Program 97:
MyFun.h
int x=5;void show()
{printf("Welcome to INFOTECH \n");
}
Test.c
OutputEnter character ;It is punctuationcharacter
Outputx = 5Welcome to INFOTECH
5/11/2018 Fundamentals and C Language - slidepdf.com
http://slidepdf.com/reader/full/fundamentals-and-c-language 86/162
/* Example on user defined header file */# include "MyFun.h"main(){clrscr();printf("x = %d \n",x);show();getch();
}
FUNCTIONS
A function is a sub program, which is used to perform a specifictask.
When a program is lengthy, it is advised to divide the program intosmaller units (routines) called functions.
When a set of statements are to be executed frequently, thenthose statements are written as separate programming unit calledfunction.
The benefits of functions are
It reduces the program length because a function can be called for
any number of times by passing different parameters. It facilitates the top-down programming approach, that is the main
logic is accessed first and then control transfers for the lower leverlogic
5/11/2018 Fundamentals and C Language - slidepdf.com
http://slidepdf.com/reader/full/fundamentals-and-c-language 87/162
Debugging becomes easy It increases clarity of program Function developed in library, can be used by any ‘C’ program.
Function are of two types
Library functions : These are built in functions available inheader files.Example : strcmp, strcat, sqrt
User defined functions: Functions defined by programmer
Every function has a "function identifier" (name of function) and its"return type".
A function can return value only to its calling program. A functionwhich does not return any value is called void function.
Before using a function, its prototype must be specified. This iscalled function declaration. Function prototype is also calledsignature of the function.
Function prototype includes return type of function, function name,number and type of arguments.
<return type> <function name> (<arg1>, <arg2>, ...);
A function can call another function. In this case, we have to writethe prototype of called function in calling function.
A function can be specified before or after the main program.
We can write functions in a header file. These functions can beinvoked in the program by including the header file.
We can send parameters to functions.
Arguments written in the program while calling the function arecalled "actual parameters" and the arguments used in the functionare called "formal parameters".
The values of actual parameters are received by the formal
parameters (receiving parameters)
5/11/2018 Fundamentals and C Language - slidepdf.com
http://slidepdf.com/reader/full/fundamentals-and-c-language 88/162
The number of actual parameters should be equal to the numberof formal parameters and their corresponding data types shouldmatch.
We can invoke a function in one of the following two ways:
Call by Value or Value parameters Call by Reference or Variable parameters
In Call by Value, the value of actual parameter is passed to formalparameter. If the value of formal parameter is changed, it will notaffect the corresponding values of actual parameter. This impliesthat the formal and actual parameters maintain separate memorylocations to hold data.
In Call by Reference, the address of actual parameter is passed to
formal. This implies that the formal and actual parameters refersto the same memory location. If the value of formal parameter ischanged, it affects the corresponding actual parameter. Thishappens when we pass arrays, pointers as parameters.
A function can call another function or any number of functions.
A function calling by itself is called "Recursive function".
SYNTAX:
<return_type> <function_name> (<parameter_list>){
........;
........;function_body;........;........;
}
Note: The function prototype need not be written for functions returning"int". When return type is not mentioned for a function , itassumes ‘int’.
Program 98:
/* Example on void functions */
5/11/2018 Fundamentals and C Language - slidepdf.com
http://slidepdf.com/reader/full/fundamentals-and-c-language 89/162
main(){void show(); /* prototype */clrscr();show();getch();
}
/* The function show */
void show(){printf("\n Welcome to Infotech.");
}
Program 99:
/* Example on void function with parameters */
main(){int a,b;void sum(int , int );clrscr();
printf("\n Enter 2 numbers : ");scanf("%d%d",&a,&b);sum(a,b);getch();
}
/* The function sum */
void sum(int x, int y){int z;z = x + y;printf(" Sum of 2 numbers : %d",z);
}
Program 100:
/* Example on function returning a value*/
OutputWelcome to
OutputEnter 2 numbers : 52
5/11/2018 Fundamentals and C Language - slidepdf.com
http://slidepdf.com/reader/full/fundamentals-and-c-language 90/162
main(){int a,b,c;int sum(int , int );clrscr();printf("\n Enter 2 numbers : ");scanf("%d%d",&a,&b);/* a,b are actual parameters */c = sum(a,b);printf("\n Sum of 2 numbers : %d",c);getch();
}
/* The function sum */
/* x,y are formal parameters */
int sum(x, y) /* ansi c type of function parameters */int x,y;{/* z is a local variable of sum() */int z;z = x + y;return z;
}
Program 101:
/* Example on global variables */int a,b,c;main(){void sum();clrscr();printf("\n Enter 2 numbers : ");scanf("%d%d",&a,&b);sum();printf("\n Sum is %d",c);getch();
}
/* The function sum */void sum()
{c = a + b;
}Program 102:
Output Enter 2 numbers : 52
Output
Enter 2 numbers : 52
5/11/2018 Fundamentals and C Language - slidepdf.com
http://slidepdf.com/reader/full/fundamentals-and-c-language 91/162
/* Example on multiple functions */main(){int a,b,r1,r2,r3;float r4;int sum(int,int), diff(int,int), mul(int,int);float div(int,int);clrscr();printf("\n Enter 2 numbers : ");scanf("%d%d",&a,&b);r1 = sum(a,b);r2 = diff(a,b);r3 = mul(a,b);r4 = div(a,b);printf("\n Sum = %d",r1);printf("\n Difference = %d",r2);
printf("\n Product = %d",r3);printf("\n Division = %f",r4);getch();
}
/* The function sum */int sum(int x,int y){return (x+y);
}
/* The function diff */int diff(int x,int y){return (x-y);
}
/* The function mul */int mul(int x,int y){return (x*y);
}
/* The function div */float div(int x,int y){return (float)x/y;
}
Program 103:
OutputEnter 2 numbers : 105Sum = 15Difference = 5Product = 50
5/11/2018 Fundamentals and C Language - slidepdf.com
http://slidepdf.com/reader/full/fundamentals-and-c-language 92/162
/* Example on function calling another function */main(){int a,b,c;int sum(int,int);clrscr();printf("\n Enter 2 numbers : ");scanf("%d%d",&a,&b);c = sum(a,b);printf("\n Sum is : %d",c);getch();
}
/* The function sum */int sum(int x,int y)
{int z;void mul(int,int);z = x + y;mul(x,y);return z;
}
/* The function mul */
void mul(int x,int y){int z;z = x * y;printf("\n Product is : %d",z);
}
Program 104:
/* Finding factorial using function */main(){int a,res;int fact(int );clrscr();printf("\n Enter a number : ");scanf("%d",&a);res = fact(a);printf("\n Factorial of %d = %d",a,res);
getch();}
OutputEnter 2 numbers : 10 5
Product is : 50Sum is : 15
OutputEnter a number : 5Factorial of 5 =
5/11/2018 Fundamentals and C Language - slidepdf.com
http://slidepdf.com/reader/full/fundamentals-and-c-language 93/162
/* The function fact */int fact(int x){
int f;for(f=1;x>0;x--)f = f * x;
return f;}
Program 105:
/* Calling function many times -Finding Binomial co-efficient */
main()
{int n,r,res;int fact(int );clrscr();printf("\n Enter values for n,r : ");scanf("%d%d",&n,&r);res = fact(n)/(fact(n-r)*fact(r));printf("\n The binomial co-efficient = %d",res);getch();
}
/* The function fact */int fact(int x){int f;for(f=1; x>0; x--)f = f * x;
return f;}
Program 106:
/* Example on function call by value */main(){int a,b;void change(int , int );clrscr();
printf("\n Enter 2 numbers : ");scanf("%d%d",&a,&b);change(a,b);printf("\n\n The values after function call :\n");printf("\n a = %d b = %d",a,b);
Output
Enter values for n,r : 5 2The binomial co-efficient =10
OutputEnter 2 numbers : 5 10
The values in function :x = 105 y = 110
The values after function call:a = 5 b = 10
5/11/2018 Fundamentals and C Language - slidepdf.com
http://slidepdf.com/reader/full/fundamentals-and-c-language 94/162
getch();}
/* The function change */void change(int x, int y){x = x + 100;y = y + 100;printf("\n\n The values in function :\n");printf("\n x = %d y = %d",x,y);
}
Program 107:
/* Example on function call by reference */main(){
int a,b;void change(int *, int *);clrscr();printf("\n Enter 2 numbers : ");scanf("%d%d",&a,&b);change(&a,&b); /* & refers to address */printf("\n\n The values after function call :\n");printf("\n a = %d b = %d",a,b);getch();
}/* The function change */void change(int x, int y) /* here x and y are pointers */{*x = *x + 100;*y = *y + 100;printf("\n\n The values in function :\n");printf("\n x = %d y = %d",*x,*y);
}
Program 108:/* Find single digit sum of a multidigited number */
/* 879 = 8+7+9 = 24 = 2+4 = 6 */main(){int a,s;int sum(int );clrscr();printf("\n Enter a number : ");
scanf("%d",&a);s = a;while(s>9){s = sum(s);
OutputEnter 2 numbers : 5 10
The values in function :x = 105 y = 110The values after function
call :
OutputEnter a number : 487Single digit sum of 487 =1
5/11/2018 Fundamentals and C Language - slidepdf.com
http://slidepdf.com/reader/full/fundamentals-and-c-language 95/162
}printf("\n Single digit sum of %d = %d",a,s);getch();
}/* The function sum */
int sum(int x){int b,c=0;while(x>0){b = x%10;c = c+b;x = x/10;}
return c;}
Program 109:
/* Example on passing arrays as parameters */
main(){
int a[5],i;void change(int []);clrscr();printf("\n Enter 5 elements :\n\n ");for(i=0;i<5;i++)scanf("%d",&a[i]);
change(a);printf("\n\n The array elements after function call :\n\n");for(i=0;i<5;i++)printf("%5d",a[i]);
getch();}
/* The function change */
void change(int x[]){int i;for(i=0;i<5;i++)
x[i] = x[i] + 10;printf("\n\n The array elements in function :\n\n");for(i=0;i<5;i++)printf("%5d",x[i]);
}
OutputEnter 5 elements :5 6 7 8 9
The array elements in function :15 16 17 18 19
The array elements after functioncall :
5/11/2018 Fundamentals and C Language - slidepdf.com
http://slidepdf.com/reader/full/fundamentals-and-c-language 96/162
Note: Using passing by address, implicitly we can return morevalues .
Program 110:
/* Example on passing 2D array as parameter - Call by reference*//* Sorting strings */
#include <string.h>main(){
int n;char a[10][10];void input(char [10][10], int );void sort(char [10][10], int );void output(char [10][10], int );clrscr();printf("\n Enter number of strings : ");scanf("%d",&n);printf("\n Enter %d names :\n",n);
input(a,n);sort(a,n);printf("\n The sorted names :\n");output(a,n);getch();
}
/* The function input */
void input(char x[10][10], int no){int i;for(i=0;i<no;i++){printf("\n Enter name %d : ",i+1);scanf("%s",x[i]);}
}
/* The function sort */
void sort(char x[10][10], int no){int i,j;
OutputEnter number of strings :
5Enter 5 names :Enter name 1 : premEnter name 2 : srinuEnter name 3 : kumarEnter name 4 : vasuEnter name 5 : info
The sorted names :infokumar
premsrinu
5/11/2018 Fundamentals and C Language - slidepdf.com
http://slidepdf.com/reader/full/fundamentals-and-c-language 97/162
char t[10];for(i=0;i<no-1;i++)for(j=0;j<no-i-1;j++)if(strcmp(x[j],x[j+1])>0){strcpy(t,x[j]);strcpy(x[j],x[j+1]);strcpy(x[j+1],t);
}}
/* The function output */void output(char x[10][10], int no){int i;for(i=0;i<no;i++)
printf("\n %s",x[i]);}
Program 111:
/* Example on Recursion - Function calling by itself */
main(){
int a,res;int fact(int );clrscr();printf("\n Enter a number : ");scanf("%d",&a);res = fact(a);printf("\n Factorial of %d = %d",a,res);getch();
}
/* The function fact */
int fact(int x){if(x==0)return 1;
elsereturn (x * fact(x-1));
}
Program 112:
/* Example on recursion *//* Finding sum of first n natural numbers */
OutputEnter a number : 4Factorial of 4 =
24
5/11/2018 Fundamentals and C Language - slidepdf.com
http://slidepdf.com/reader/full/fundamentals-and-c-language 98/162
main(){int n,s;int sum(int );clrscr();printf("\n Enter a number : ");scanf("%d",&n);s = sum(n);printf("\n Sum = %d",s);getch();
}/* The function sum */
int sum(int no){if(no==0)
return 0;elsereturn (no + sum(no-1));
}
Exercise:
Explain function Explain call by value and call by reference
What are formal and actual parameters Explain recursion Write a function name ‘Palin’ to find whether the accepted number
is palindrome or not. (Palindrome : The reversed number is sameas original number. Example : 121 , 565, 777, 10201. )
Write a function to find sum of given series for 10 terms. ( 1! – 3!+ 5! - 7! + 9!…)
Write functions to accept values into two double dimension arraysof 3x3 and perform matrix multiplication. Store the result in third
matrix. Using a function display multiplication table of accepted number. Write functions to accept principle amount, rate of interest , time
of interest and calculate simple interest and compound interest. Write a function to calculate ‘m’ to the power of ‘n’.
OutputEnter a number : 5Sum = 15
5/11/2018 Fundamentals and C Language - slidepdf.com
http://slidepdf.com/reader/full/fundamentals-and-c-language 99/162
STORAGE CLASSES
The scope of variable refers to how widely it is known among aset of functions in a program. Every identifier optionally has astorage class that provides information about its visibility, lifetimeand location. The following storage classes are supported in ‘C’
Automatic variables Register variables static variables External variables
Automatic variables:
An auto variable is a variable, which is created automatically
when control enters into a block, and is destroyed when thecontrol leaves the block.The local variables of a function are oftenreferred as automatic variables. The default storage class is ‘auto’.Memory is automatically allocated when ever a variable isdeclared to particular storage class. Automatic variables can bedeclared not only at the beginning of function but also at thebeginning of a compound statement.
Syntax :
auto <data type> <variables>
The declarationint a,b;
is exactly same asauto int a,b;
Program 113:
/* Example on auto variable */
void main(){
Output
We are in inner block.a = 10 b = 20
We are in external block.a = 2528
Note: The value 2528 is
5/11/2018 Fundamentals and C Language - slidepdf.com
http://slidepdf.com/reader/full/fundamentals-and-c-language 100/162
auto int a;{auto int a,b;clrscr();a=10; b=20;printf("\n We are in inner block.");printf("\n a = %d b = %d",a,b);
}printf("\n\n We are in external block.");printf("\n a = %d");/* printf(" b = %d",b); */getch();
}
Program 114:
/* Example on multiple declarations of same variable*/
main(){void infotech(int);int i=100;clrscr();infotech(200);printf("i=%d in function main\n",i);
getch();}/* function */void infotech(i)int i;{i=i*10;
{int i;i=300;printf("i=%d in inner most block \n",i);
}printf("i=%d (parameter of function) \n",i);
}
Register variables :
Auto variables are stored in memory, where as Register variablesare stored in CPU’s registers. Register variables are faster in
execution as they are part and parcel of processor. The variablesfrequently used for processing can be declared as registervariables.
Syntax:
Outputi=300 in inner most blocki=2000 (parameter offunction)i=100 in function main
5/11/2018 Fundamentals and C Language - slidepdf.com
http://slidepdf.com/reader/full/fundamentals-and-c-language 101/162
register <data type> <variables>
Program 115:
/* Example on register variables */
void main(){register int a;clrscr();for(a=0;a<5;a++)
printf(" %d ",a);getch();
}
Static variables:
The static variables defined within a function have the samescope of rules of automatic variables but in this case the contentsof the variables will be retained throughout the program. Thestatic variables are initialized to zero by default. They areinitialized only once.
Syntax :
static <data type> < variables list>
Program 116:
/* Example on static variables */
main(){int i;clrscr();
for(i=1;i<=3;i++)test();
getch();}
/* The function test */
test(){static int a;int x = 50;printf("a = %5d x = %5d\n",a,x);
Output0 1 2 3 4
Outputa = 0 x = 50a = 1 x = 50
a = 2 x = 50
5/11/2018 Fundamentals and C Language - slidepdf.com
http://slidepdf.com/reader/full/fundamentals-and-c-language 102/162
a = a+1;}
Program 117:
static void fun(){printf("\n We are in static fun");
}
main(){clrscr();printf("\n We are in main");fun();
getch();}
External variables:
External variables are those variables, that are declared elsewherein the program, but can be used in the current block. Externalvariables are declared out of main function. They resemble theglobal variables, but the external variables can be used prior to its
declaration. They are initialized to zero by default.
Syntax:
extern <data type> <variables>
Program 118:
/* Example on global and external variable */
int a;main(){extern int b;clrscr();printf("\n a = %d b = %d",a,b);infotech();getch();
}
int b;
/* function */infotech(){
Outputa= 0 b=0Inside function
a= 0 b=0
OutputWe are in main
We are in static fun
5/11/2018 Fundamentals and C Language - slidepdf.com
http://slidepdf.com/reader/full/fundamentals-and-c-language 103/162
printf("\nInside function ");printf("\n a= %d b=%d",a,b);}
Exercise:
Differentiate global variable from extern variable. Explain the memory architecture of static storage class when used
in program Explain the benefit of register storage class Write about scope of variable with an example. Develop a program using variables of all storage classes.
Structures:
Structures : Structure is heterogeneous, complex data structure.It is called heterogeneous because it can combine elements of
different data types into single unit. It is complex data typebecause a structure variable can hold multiple values.
Structure contains multiple fields, each of which is called asmember of structure. Some times the member of structure can bea structure variable. That is structures can be nested.Arrays can be used inside the structure as members and arrayscan be created using structures that is array of structures.
Structures help to organize the complex data in a more meaningfulway. They increase the speed of program execution as thememory allocated for the members of structure is in sequentialmemory locations. Structures are convenient to handle thelogically related data items. This provides the packing of data as aunit.
Syntax:struct [<structure name>]{
<members of structure>};
Note : Naming the structure is optional.
5/11/2018 Fundamentals and C Language - slidepdf.com
http://slidepdf.com/reader/full/fundamentals-and-c-language 104/162
Program 119:
/* Example on Structure global declaration The structure student */struct student{int sno,tot;char sna[20];
};/* The main program */main(){struct student s;clrscr();printf("\n Enter student number : ");
scanf("%d",&s.sno);printf("\n Enter student name : ");scanf("%s",s.sna);printf("\n Enter total marks : ");scanf("%d",&s.tot);printf("\n Student details :\n");printf("\n Number : %d",s.sno);printf("\n Name : %s",s.sna);printf("\n Total : %d",s.tot);
getch();}Note: In the above program ‘s’ is a variable of ‘struct student’type. To refer any member of ‘s’ use a dot (.) member shipoperator.
Program 120:
/* Example on structure with local declarationStructure Employee*/
main(){struct employee{int eno;float sal;char ena[20];}e;
float hra,da,tax,nsal;clrscr();printf("\n Enter employee number : ");scanf("%d",&e.eno);printf("\n Enter name : ");
OutputEnter student number : 1Enter student name : premEnter total marks : 800
Student details :Number : 1Name : premTotal : 800
OutputEnter employee
number :Enter name : PREM
Enter salary : 10000 Employee details :Number : 1Name : PREMSalary : 10000.000000HRA : 1200.000000DA : 1000.000000TAX : 500.000000
5/11/2018 Fundamentals and C Language - slidepdf.com
http://slidepdf.com/reader/full/fundamentals-and-c-language 105/162
scanf("%s",e.ena);printf("\n Enter salary : ");scanf("%f",&e.sal);
hra = e.sal*12/100.0;da = e.sal*10/100.0;tax = e.sal*5/100.0;nsal = e.sal+hra+da-tax;
printf("\n Employee details :\n");printf("\n Number : %d",e.eno);printf("\n Name : %s",e.ena);printf("\n Salary : %f",e.sal);printf("\n HRA : %f",hra);printf("\n DA : %f",da);printf("\n TAX : %f",tax);
printf("\n Net sal : %f",nsal);getch();
}
Program 121:
/* Example on array of structures */
struct student{int sno,tot;char sna[20];
};/* The main program */
main(){
int n,i;
struct student s[10];
clrscr();
printf("\n Enter number of students below 10 : ");
OutputEnter number of students below10 : 2Enter details of student 1 :
Enter number : 1Enter name : premEnter total : 800
Enter details of student 2 :Enter number : 2Enter name : srinuEnter total : 900
Student details :Number : 1
Name : premTotal : 800
Number : 2Name : srinuTotal : 900
5/11/2018 Fundamentals and C Language - slidepdf.com
http://slidepdf.com/reader/full/fundamentals-and-c-language 106/162
scanf("%d",&n);
for(i=0;i<n;i++){printf("\n Enter details of student %d :\n",i+1);printf("\n Enter number : ");scanf("%d",&s[i].sno);printf("\n Enter name : ");scanf("%s",s[i].sna);printf("\n Enter total : ");scanf("%d",&s[i].tot);}
printf("\n Student details :");for(i=0;i<n;i++){
printf("\n\n Number : %d",s[i].sno);printf("\n Name : %s",s[i].sna);printf("\n Total : %d",s[i].tot);getch();}
}
Program 122:
/* Structures with in another structure */
/* The structure address */struct address{int hno;char strna[10];
};
/* The structure student */struct student
{int sno,tot;char sna[15];struct address A;
};
OutputEnter student number, name,total :1 PREM 900
Enter house number, streetname :57 BhagyaNagar
Student details :Number : 1Name : PREMTotal : 900
5/11/2018 Fundamentals and C Language - slidepdf.com
http://slidepdf.com/reader/full/fundamentals-and-c-language 107/162
/* The main program */main(){struct student S;clrscr();
printf("\n Enter student number, name, total :\n ");scanf("%d%s%d",&S.sno,S.sna,&S.tot);printf("\n Enter house number, street name :\n ");scanf("%d%s",&S.A.hno,S.A.strna);
printf("\n Student details :\n");printf("\n Number : %d",S.sno);printf("\n Name : %s",S.sna);printf("\n Total : %d",S.tot);
printf("\n House no : %d",S.A.hno);printf("\n Street : %s",S.A.strna);
getch();}
Program 123:
/* Example on structure with in another structure */
struct student{int sno,tot;char sna[15];
struct address{
int hno;char strna[15];}A;
}S;
OutputEnter student number, name,total :1 Srinivas 900
Enter house number, street :20 MaddurNagar
Number : 1Name : SrinivasTotal : 900HNo : 20
5/11/2018 Fundamentals and C Language - slidepdf.com
http://slidepdf.com/reader/full/fundamentals-and-c-language 108/162
main(){clrscr();
printf("\n Enter student number, name, total :\n ");scanf("%d%s%d",&S.sno,S.sna,&S.tot);printf("\n Enter house number, street :\n ");scanf("%d%s",&S.A.hno,S.A.strna);
printf("\n Number : %d",S.sno);printf("\n Name : %s",S.sna);printf("\n Total : %d",S.tot);printf("\n HNo : %d",S.A.hno);printf("\n Street : %s",S.A.strna);getch();
}
Assigning structure variables :
Assigning structure variables of similar structure is possible butthe structure variables belonging to different structures is notpossible. In this case the structure member of one structure can beassigned to another structure.
Program 124:
/* Assigning structure variables *//* The structure student */struct student{int sno,tot;char sna[10];
};
/* The main program */main(){struct student S1, S2;
Output
Enter Student number, name,total :1 PREM 900
The student details :Number : 1Name : PREMTotal : 900
5/11/2018 Fundamentals and C Language - slidepdf.com
http://slidepdf.com/reader/full/fundamentals-and-c-language 109/162
clrscr();
printf("\n Enter Student number, name, total :\n ");scanf("%d%s%d",&S1.sno,S1.sna,&S1.tot);
S2 = S1;
printf("\n The student details :\n");printf("\n Number : %d",S2.sno);printf("\n Name : %s",S2.sna);printf("\n Total : %d",S2.tot);
getch();}
Program 125:
#include <string.h>/* Assigning structure variables *//* The structure student1 */struct student1{int sno,tot;char sna[10];
};
/* The structure student2 */struct student2{int sno,tot;char sna[10];
};
/* The main program */main(){struct student1 S1;struct student2 S2;clrscr();
printf("\n Enter Student number, name, total :\n ");scanf("%d%s%d",&S1.sno,S1.sna,&S1.tot);
/* S2 = S1; */
Output:
Enter Student number, name,total : 1 PREM 900
The student details :Number : 1Name : PREMTotal : 900
5/11/2018 Fundamentals and C Language - slidepdf.com
http://slidepdf.com/reader/full/fundamentals-and-c-language 110/162
S2.sno = S1.sno;strcpy(S2.sna, S1.sna);S2.tot = S1.tot;
printf("\n The student details :\n");printf("\n Number : %d",S2.sno);printf("\n Name : %s",S2.sna);printf("\n Total : %d",S2.tot);getch();
}
Program 126:
/* Passing structure as parameter to function *//* Call by value *//* The structure test */
struct test{int a,b;
};
/* The main program */
main()
{struct test T;void change(struct test );clrscr();T.a = 10;T.b = 20;change(T);printf("\n\n Structure values after function change :\n");printf("\n a = %d b = %d",T.a,T.b);getch();
}
/* The function change */void change(struct test X){X.a = X.a + 10;X.b = X.b + 10;
printf("\n\n Structure values in function :\n");printf("\n a = %d b = %d",X.a,X.b);
}
Program 127:
Output
Structure values in function :a = 20 b = 30
Structure values after functionchange :
5/11/2018 Fundamentals and C Language - slidepdf.com
http://slidepdf.com/reader/full/fundamentals-and-c-language 111/162
/* Passing structure as parameter to function *//* Call by reference *//* The structure test */
struct test{int a,b;
};
/* The main program */
main(){struct test T;void change(struct test *);
clrscr();
T.a = 10;T.b = 20;
change(&T);
printf("\n\n Structure values after function change :\n");printf("\n a = %d b = %d",T.a,T.b);
getch();}
/* The function change */
void change(struct test *X){X->a = X->a + 10;X->b = X->b + 10;
printf("\n\n Structure values in function :\n");printf("\n a = %d b = %d",X->a,X->b);
}
Unions
Unions resembles structures in all regards but it differs in storage
allocation. In structures each member has its own memorylocation, where as in unions all the union members share commonmemory location. Unions allocate memory for the member withlargest data type in which the values of other members can bestored. Ultimately, the value of only one member can be stored in
OutputStructure values in function :a = 20 b = 30
Structure values after functionchange :a = 20 b = 30
5/11/2018 Fundamentals and C Language - slidepdf.com
http://slidepdf.com/reader/full/fundamentals-and-c-language 112/162
union identified. Unions can be nested. Apart from primitive datatypes, unions can have even structures as its members.
Syntax:union [<tag>]
{<members>
}
Example :union data{
int a;float b;char c;
} X;
Program 128:
/* Example on union */union Test{
int a;float b;char c;
double d;};
/* The main program */main(){union Test T;clrscr();T.a = 10;T.b = 3.14;T.c = 'Z';T.d = 1.2345;printf("\n a = %d",T.a);printf("\n b = %f",T.b);printf("\n c = %c",T.c);printf("\n d = %lf",T.d);printf("\n\n size of T = %d",sizeof(T));getch();
}
Note: See the above output. This is because only the last assigneditem is available from union variable ‘T’.structure within union
Program 129:
Output
a = -26739b = 0.000000c = ìd = 1.234500
size of T = 8
Memory allocation diagram
X1000 1001 1002 1003
4 bytes of memoryint a – 2 bytes can be stored in 4bytesfloat b- 4 bytes can be stored in 4
5/11/2018 Fundamentals and C Language - slidepdf.com
http://slidepdf.com/reader/full/fundamentals-and-c-language 113/162
/* Example on structure within union*/
main(){
struct date{int day,month,year;
};union value{int i;float f;struct date bdate;
} X;clrscr();
X.i = 10;X.f = -1456.45;X.bdate.day=20;X.bdate.month=3;X.bdate.year=2007;printf("X.i = %d\n",X.i);printf("X.f = %f\n",X.f);printf("Structure : \n");printf("%d - %d - %d
\n",X.bdate.day,X.bdate.month,X.bdate.year);printf("Size of union %d",sizeof(X));getch();
}
Enumerations
The enumeration data types are a used to increase readability of program. It is programmers convenience. Enumerations are usedto declare user defined data types. Enumeration is a set of valuesrepresented by user defined constants called enumerationconstants.
Output
X.i = 22X.f = 0.000000Structure :20 - 3 – 2007Size of union 6
5/11/2018 Fundamentals and C Language - slidepdf.com
http://slidepdf.com/reader/full/fundamentals-and-c-language 114/162
Syntax
enum <user_defined name>{
member 1,member 2,
… member n};
Example
enum staff {
gopi, prem, srinu, sunil, rajasekhar};
Compiler automatically assigns integer constants 0 to gopi, 1 toprem, 2 to srinu and so on.
Example:
enum courses{
C=5,
Pascal,cobol};
‘C’ is assigned integer constant 5, pascal gets 6 and cobol gets 7.
Program 130:
/* Example on enumaration */enum courses{
java,oracle,dotnet,msoffice
};
main(){
enum courses i;clrscr();for(i=java;i<=msoffice;i++)
Output
0 1 2 3
5/11/2018 Fundamentals and C Language - slidepdf.com
http://slidepdf.com/reader/full/fundamentals-and-c-language 115/162
printf("%d ",i);getch();
}
Program 131:
/* example on enumaration */
enumStaffCode{prem=101,srinu=201,sunil=301,rajasekhar=401};main(){enum StaffCode code;clrscr();printf("Enter staff code 101/201/301/401 ");scanf("%d",&code);
if (code==prem)printf("Prem got experience of 15 years ");
elseif (code==srinu)printf("Srinu got experience of 16 years ");
elseif(code==sunil)
printf("Sunil got experience of 12 years");else
if(code==rajasekhar)printf("Rajasekhar got experience of 10 years");getch();}
Macros – Pre Processors:
Macros are used to simplify the existing statements as perprogrammer’s convenience.# defineWe can define our own constants in program. These constantsmay appear repeatedly in our program. The macro definitions arealso called pre processors because before processing, theconstants are replaced by respective values by pre processors.
These programs increase readability, understandability andmodifiability of program. Even we can design new programminglanguage with # define statements.
Syntax
# define <symbolic-name> <value of constant>
Example# define Max 100# define PI 3.14159
OutputEnter staff code
101/201/301/401 201Srinu got experience of 16 years
5/11/2018 Fundamentals and C Language - slidepdf.com
http://slidepdf.com/reader/full/fundamentals-and-c-language 116/162
Program 132:
/* Example on # define */# define min 101# define max 105# define inc i++# define display printf("%5d",i)
main(){
int i;clrscr();for(i=min; i<=max; inc)display;
getch();}
Type def : This allows user to define an identifier that wouldrepresent an existing data type. The user defined data typeidentifier can be used latter to declare variables.
Syntax:typedef <type identifier>;
Example:
typedef int amount;typedef float pay;
Program 133:
/* Example on typedef */
typedef int marks;typedef char string;
main(){
string name[20];marks m1,m2,m3,total;clrscr();printf("Enter student name ");scanf("%s",name);printf("\nEnter marks in 3 subjects ");scanf("%d %d %d",&m1,&m2,&m3);
total = m1+m2+m3;printf("\n\nStudent name %s",name);printf("\nMarks are %d %d %d ",m1,m2,m3);printf("\nTotal is %d",total);getch();
Output
101 102 103 104105
Output
Enter student name PREMEnter marks in 3 subjects 70 80
90
Student name PREMMarks are 70 80 90Total is 240
5/11/2018 Fundamentals and C Language - slidepdf.com
http://slidepdf.com/reader/full/fundamentals-and-c-language 117/162
}
Command Line Arguments
In these programs, arguments are supplied to the program asparameters from the command prompt at the time of programexecution.
When ‘C’ program is compiled, an executable file will be createdwith file extension .exe. This file can be executed from commandprompt with out loading ‘C’ software or compiler.
The arguments passed from the command prompt will be taken bythe main() function into two parameters ‘argc’ and ‘argv’.
‘argc’ stands from argument count and ‘argv’ stands from
argument values. The argc contains the total number of parameters passed to the program. It is of integer data type.
The ‘argv’ contains all the values of parameters. It is of charactertype pointer array. The 0th cell of argv array always contains theprogram name as its value.
Example
main(int argc, char *argv[])
{<statements>}
Program 134:
/* Example on command line arguments1.Save the program with name CMDEX .C2. compile the program and make Exe */
main(int argc,char *argv[]){int i;clrscr();printf("Total number of arguments %d",argc);printf("\nThe arguments are \n");
for(i=0;i<argc;i++)printf("\n%s",argv[i]);
getch();}
Exercise
D:\>CMDEX prem srinu infotech
Output
Total number of arguments 5The arguments are
D:\CMDEX.EXEpremsrinuinfotech
5/11/2018 Fundamentals and C Language - slidepdf.com
http://slidepdf.com/reader/full/fundamentals-and-c-language 118/162
Accept a string and reverse it using command line arguments Copy the content of one file to another file using command line
arguments Accept three strings from command prompt. Concatenate them
display Write about typedef with your own example.
Explain macros with suitable examples. What is enum. Explain with examlpels.
Pointers
Pointer : Pointer is a variable which holds the address of memorylocation where the data is stored. The pointer is a powerfultechnique to access the data by indirect reference because it holdsthe address of that variable where it has been stored in thememory.
The power of ‘C’ lies in pointers. This is because of two resigns.
powerful memory manage techniques are with pointers. Thedynamic memory allocation and deallocation can be done withpointer programs. The memory can be released if not necessary.
Speed of program execution increases because the pointerprograms maintains addresses of memory locations.
Pointers are called Dynamic variables. A dynamic variable can becreated or disposed at any time during the program execution.
The binding of a dynamic variable is done at runtime. Bindingmeans allocating memory to a variable. All normal variables gettheir memory allocation at compile time. This is known as earlybinding or static binding. But pointers get their memory allocationat runtime as per the request. This is known as Late binding ordynamic binding.
The pointer variable consists of two parts such as the pointeroperator and the address operator
Pointer operator : A pointer operator can be represented bythe combination of *(asterisk) with a variable.
Example : int *ptr;
The above example denotes that the ‘ptr’ is a variable of type“pointer to integer”.
That is the ptr is a pointer variable which holds the address of aninteger data type.
The following declarations are all valid declarations
5/11/2018 Fundamentals and C Language - slidepdf.com
http://slidepdf.com/reader/full/fundamentals-and-c-language 119/162
float *fptr;double *dptr;char *cptr;
Address operator: An address operator can be represented bythe combination of &(ampersand) with a pointer variable.
Example: m = &ptr;
Note that the pointer operator & will return the address of thevariable following it. So in the above example ‘m’ receives theaddress of ‘ptr’ but not its value.
Pointer Expressions The general rule to assign a value to pointer is same as any othervariable data type.Example:
int x=100;int *ptr;ptr = &x;
In the above example the address of ‘x’ is assigned to pointervariable ‘ptr’. Now if we print *ptr, the value 100 will be displayed.
Program 135:
/* Example on & and *& - address fetch operator* - value at address operator */
main(){int a = 5;clrscr();
/* Accessing value in a - Normal way */printf("\n\n Value of a : %d",a);
/* Getting address of a */printf("\n\n Address of a : %u",&a);
/* Accessing a using its address - Special way */
printf("\n\n Value of a : %d",*(&a));
getch();}
OutputValue of a : 5
Address of a : 65504
Value of a : 5
5/11/2018 Fundamentals and C Language - slidepdf.com
http://slidepdf.com/reader/full/fundamentals-and-c-language 120/162
In the above example ‘&a’ will return the address of normalvariable ‘a’.*(&a) :- &a will represent the address of memory location ‘a’ and* preceding it indicated the content of memory location. That isdata 5.
Programs on normal variables and pointer variables
Program 136:
/* Pointer variable getting address of normal variable */void main(){int a, *b;clrscr();a = 50;
/* b is pointing to a */b = &a;printf("%5d %5d",a,*b);getch();
}
In the above example the address of normal variable ‘a’ isassigned to pointer variable ‘b’ by the statement ‘b = &a’
Program 137:
/* Assigning address of one pointer variableto another pointer variable*/
void main(){int a, *b, *c;clrscr();
a = 50;
/* b and c are pointing to a */b = &a;c = b;
printf("%5d%5d%5d",a,*b,*c);getch();
}
In the above example by the statement b=&a, the address of normal variable ‘a’ is given to pointer variable ‘b’ and the addressreferred by ‘b’ is given to pointer variable ‘c’.
Output50 50
Output 50 50 50
5/11/2018 Fundamentals and C Language - slidepdf.com
http://slidepdf.com/reader/full/fundamentals-and-c-language 121/162
Program 138:
/*Content of pointer variable is assigned to normal variable */
void main(){int a, *b, *c, d;clrscr();a = 50;/* b and c are pointing to a */b = &a;c = b;
/* The contents at memory location pointed by b are copied into d*/
d = *b;
printf("%5d%5d%5d%5d",a,*b,*c,d);getch();
}
In the above example by the statement d=*b, the content of pointer variable ‘b’ is given to normal variable ‘d’.
Program 139:
/* Example pointer program */
void main(){int a,b,c,*d,*e;clrscr();
c = 75;e = &c;b = *e;c = 50;a = 100;d = &a;a = 150;
printf("%5d%5d%5d%5d%5d",a,b,c,*d,*e);getch();
}
malloc() : Allocates memory of specified size dynamically by therequest made at runtime from heap memory. Prototype in alloc.h,stdlib.h
Output 50 50 50 50
Output 150 75 50 150
5/11/2018 Fundamentals and C Language - slidepdf.com
http://slidepdf.com/reader/full/fundamentals-and-c-language 122/162
Syntax :
void *malloc(size in bytes);
Programs on malloc function
Program 140:
/* Example on malloc */
void main(){int *a, b;clrscr();
a = (int *) malloc (sizeof(int));*a = 50;b = *a;
printf("%5d %5d",*a, b);getch();
}
In the above example the malloc statement will allocate two bytes
of memory. That is the size of integer. (int *) is type casting whichdenotes the integer pointer.Program 141:
/* Example on malloc - scanf */
void main(){int *a,b;clrscr();a = (int *) malloc (sizeof(int));printf("\n Enter a number : ");scanf("%d",a);
/* in the above input & is ignored before variable ‘a’ because it isalready an address*/
b = *a;
printf("%5d%5d",*a,b);getch();
}
In the above example by the statement b=*a, the content of pointer variable ‘a’ is given to normal variable ‘b’.
Output50 50
OutputEnter a number : 50
50 50
5/11/2018 Fundamentals and C Language - slidepdf.com
http://slidepdf.com/reader/full/fundamentals-and-c-language 123/162
Program 142:
/* Sum of 2 numbers using pointers */
void main(){int *a, *b, *c;clrscr();a = (int *) malloc (sizeof(int));b = (int *) malloc (sizeof(int));c = (int *) malloc (sizeof(int));
printf("\n Enter 2 numbers : ");scanf("%d%d",a,b);
*c = *a + *b;
printf("\n Sum is %d",*c);getch();
}
In the above example by the statement *c = *a + *b; the contentof pointer variables ‘a’ and ‘b’ is stored as content of pointervariable ‘c’
Programs on Array pointers
Program 143:
/* Arrays - Pointers */
void main(){int a[5] = {10,20,30,40,50};int i;clrscr();printf("%5d%5d%5d%5d%5d",*a,*(1+a),*(a+2),*(a+3),*(a+4));
printf("\n\n");for(i=0;i<5;i++)printf("%5d",i[a]);
printf("\n\n");
Output
Enter 2 numbers : 5025
Sum is 75
Output 10 20 30 40 50
10 20 30 40 50
10 20 30 40 50
10 20 11
5/11/2018 Fundamentals and C Language - slidepdf.com
http://slidepdf.com/reader/full/fundamentals-and-c-language 124/162
for(i=0;i<5;i++)printf("%5d",a[i]);
printf("\n\n");printf("%5d%5d%5d",*a,*(a+1),*a+1);
getch();}
In the above example *a represents the 0th element of array.*(a+1) represents 1st element of array and so on. The arrayelement can be represent as a[ i] or i[a].
Pointer arithmetic :
In general the variable are incremented and decremented. Themathematical expressions are constructed with of variables. Apart
from that ‘C’ supports pointer arithmetic. As per this, the addresscan be incremented or decremented. No other operations likemultiplications and divisions can be performed with addresses.
These are best used with Arrays.
Programs on Pointer Arithmetic
Program 144:
/* Example on pointer arithmetic’s */main(){int a[3] = {10,20,30};int *b;int i;clrscr();b = a;
printf("\n The array elements :\n\n");for(i=0;i<3;i++){printf("%d ",*b);b++;
OutputThe arrayelements :
5/11/2018 Fundamentals and C Language - slidepdf.com
http://slidepdf.com/reader/full/fundamentals-and-c-language 125/162
}getch();
}
In the above example by the statement b=a; the address of 0 th cellof array ‘a’ is assigned to ‘b’. In ‘for’ looping structure thestatement b++; denotes the address incrementation. By this thepointer variable ‘b’ will be pointing to different elements of array indifferent iterations of for loop.
Program 145:
/* Creating array using malloc() */main(){int *a, n, i;
clrscr();printf("\n Enter size of the array : ");scanf("%d",&n);a = (int *) malloc (sizeof(int) * n);printf("\n Enter %d elements :\n ",n);for(i=0;i<n;i++)scanf("%d",(a+i));
printf("\n The array elements :\n");for(i=0;i<n;i++)
printf("%5d",*(a+i));printf("\n The array elements :\n");for(i=0;i<n;i++){printf("%5d",*a);a++;}
getch();}
In the above example by the statement a = (int *) malloc(sizeof(int) * n); ‘n’ represents the no of elements and sizeof(int)*nwill allocate memory for required number of elements, each of sizetwo bytes.
Program 146:
/* The base address of array can't be changed */
main()
{int a[5] = {10,20,30,40,50};int *p;int i;clrscr();
OutputEnter size of the array : 4
Enter 4 elements :10 20 30 40
The array elements :10 20 30 40
The array elements :
10 20 30 40
Output The array elements :
10 20 30 40 50
5/11/2018 Fundamentals and C Language - slidepdf.com
http://slidepdf.com/reader/full/fundamentals-and-c-language 126/162
p = a;
printf("\n The array elements :\n");for(i=0;i<5;i++){/* The base address of array can't be changed.
Hence a++ is invalid statementprintf("%5d",*a);a++; */
printf("%5d",*p);p++;}
getch();}
Programs on Pointer to Pointer
Program 147:
/* Pointer to a pointer */
main(){
int a,*b,**c;clrscr();a = 50;b = &a;c = &b;printf("%5d%5d%5d",a,*b,**c);getch();
}In the above example by the statement b=&a, the address of ‘a’ isgiven to pointer variable ‘b’ and by the statement c=&b, theaddress of ‘b’ is given to pointer variable ‘c’.So **c represents the content of address of ‘c’.
Program 148:
/* Pointer to pointer using malloc() */
main(){int **a;
clrscr();a = (int **) malloc (sizeof(int *));
*a = (int *) malloc (sizeof(int));
Output 50 50 50
Output
Enter a number : 50
The number is : 50
5/11/2018 Fundamentals and C Language - slidepdf.com
http://slidepdf.com/reader/full/fundamentals-and-c-language 127/162
printf("\n Enter a number : ");scanf("%d",*a);
printf("\n The number is : %d",**a);getch();
}
In the above example the statement a = (int **) malloc (sizeof(int*)); says that ‘a’ will hold the address of memory location in whichaddress of another memory location can be stored.
Program 149:
/* Pointer to a pointer representing a 2D array */
main()
{int **a, r, c, i, j;clrscr();printf("\n Enter number of rows and columns : ");scanf("%d%d",&r,&c);a = (int **) malloc (sizeof(int *) * r);
for(i=0; i<r; i++)a[i] = (int *) malloc (sizeof(int) * c);
printf("\n Enter %d elements :\n ",(r*c));for(i=0; i<r; i++)for(j=0; j<c; j++)scanf("%d",(*(a+i)+j));
printf("\n The elements of array :\n\n");for(i=0;i<r;i++){for(j=0;j<c;j++)printf("%5d", *(*(a+i)+j));
printf("\n\n");}
getch();}
Programs on Pointer to Structures
Program 150:
/* Example on structure pointer */
struct test{int a;
}*T;
OutputEnter number of rows and columns :3 3
Enter 9 elements :10 20 30 40 50 60 70 80 90
The elements of array :10 20 30
40 50 60
70 80 90
Outputa = 10
5/11/2018 Fundamentals and C Language - slidepdf.com
http://slidepdf.com/reader/full/fundamentals-and-c-language 128/162
main(){clrscr();
T = (struct test *) malloc (sizeof(struct test ));T->a = 10;printf("\n a = %d",T->a);
getch();}
In the above example *T is a pointer to structure where values of structure members can be stored.
Program 151:
/* Example on structure with a pointer variable */
struct test{int *a;
}T;
main()
{clrscr();
T.a = (int *) malloc (sizeof(int));*T.a = 10;printf("\n a = %d",*T.a);
getch();}
In the above example T is a normal structure variable whichinternally contains a pointer member *a. The memory is allocatedto the pointer member with the statement T.a = (int *)malloc (sizeof(int));. The statement *T.a = 10; is used to assignvalue to pointer member of structure.
Program 152:
/* Example on structure pointer and structure with pointer
variable */struct test{int *a;
}*T;
Outputa = 10
Outputa = 10
5/11/2018 Fundamentals and C Language - slidepdf.com
http://slidepdf.com/reader/full/fundamentals-and-c-language 129/162
/* The main program */main(){clrscr();T = (struct test *) malloc (sizeof(struct test));T->a = (int *) malloc (sizeof(int));*T->a = 10;printf("\n a = %d",*T->a);getch();
}
This is example on structure pointer and pointer member. The statement T = (struct test *) malloc (sizeof(struct test)); isused to allocate memory for structure pointer.
The statement T->a = (int *) malloc (sizeof(int)); is used to
allocate memory for pointer member of structure.
free() : De allocates the memory allocated. Prototype in stdlib.h,alloc.h
Syntax : void free(void *block);
Program on de allocation of memory
Program 153:
/* Example on free() */main(){int *a;clrscr();a = (int *) malloc (sizeof(int));printf("\n Enter a number : ");scanf("%d",a);printf("\n The number is : %d",*a);free(a);printf("\n\n Memory deallocated.");printf("\n\n Number = %d",*a);getch();
}
In the above example free(a) is used to de allocate memory of pointer variable ‘a’.
After de allocation, the pointer variable contains garbage value.Programs on Pointer to function
Program 154:
OutputEnter a number :50
The number is : 50
Memory
5/11/2018 Fundamentals and C Language - slidepdf.com
http://slidepdf.com/reader/full/fundamentals-and-c-language 130/162
/* Example on pointer to a function */
main(){int s;int (*ptr)(int );int sum(int);clrscr();
ptr = sum;
s = (*ptr)(3);printf("\n sum = %d",s);
s = ptr(3);printf("\n sum = %d",s);
/* s = *ptr(3); */getch();
}
int sum(int x){int s = 0,i;for(i=1; i<=x; i++)
s+=i;return s;}
In the above example the statement
int (*ptr)(int ); represents that ‘ptr’ is pointer to function which cantake integer as parameter.
The statement ptr = sum; makes the function pointer ‘ptr’ to pointto the function sum.
The statement s = (*ptr)(3); call the function sum by passing theparameter 3 which is received by the formal parameter ‘x’.
Program 155:
OutputSum = 6Sum = 6
5/11/2018 Fundamentals and C Language - slidepdf.com
http://slidepdf.com/reader/full/fundamentals-and-c-language 131/162
/* Example on pointer to function with parameters */
main(){int a,b,res;
int sum(int , int);int (*fptr)(int, int);
clrscr();
printf("\n Enter 2 numbers : ");scanf("%d%d",&a,&b);
fptr = sum;
res = sum(a,b);printf("\n Result is : %d", res);
res = (*(&sum))(a,b);printf("\n Result is : %d", res);
res = (*(fptr))(a,b);printf("\n Result is : %d", res);
getch();}
/* The function sum */int sum(int x, int y){return x+y;
}
Output
Enter 2 numbers : 1020
Result is : 30Result is : 30Result is : 30
5/11/2018 Fundamentals and C Language - slidepdf.com
http://slidepdf.com/reader/full/fundamentals-and-c-language 132/162
Files
File programs are used to store the data permanently onsecondary storage devices and access it when required. The datastored on secondary storage is permanent. File programs aregenerally used to do data transactions in large volume.
Buffers are used to access data files. A Buffer is memory area thatis reserved for any input/output device. There are some standardbuffers for keyboard, monitor ,printer etc., For disk files we need tocreate our own buffers. That is done in C language by a struct typecalled FILE.
FILE *pointer; The *pointer is called a buffer or stream.
C language data files are also called as stream data files. A streamis a continuous flow of data where we can write into or read fromany number of characters.
File is the place on the secondary media where a group of relateddata is stored. The programs related with files are 1. Data creationprogram 2. Appending program 3. Processing program
Data creation program: The program which is used to storethe data into disk is called data creation program.
Appending program: The program which is used to add newdata for the existing data.
Processing program: The program which is used to read the datafrom disk and process it is called processing program or accessingprogram.
The functions used for file operations are defined in “stdio.h”header file.
fprintf(): Writes set of data values to file according to the formatspecified.
Syntaxint fprintf(FILE *fp, const char *format [,arguments]);
fscanf(): Reads set of data values from file as per the formatspecified.
Syntaxint fscanf(FILE *fp, const char *format, arguments);
5/11/2018 Fundamentals and C Language - slidepdf.com
http://slidepdf.com/reader/full/fundamentals-and-c-language 133/162
fopen() : Creates a new file or opens existing file. Syntax
FILE *fp;Fp = fopen(“file name”, ”mode”);
Mode can be following characters r Open for reading w Create for writing a Append, open for writing at end-of-file + Add symbol to allow read/write access b Open in binary mode t Open in text mode
fclose() : Closes the opened file
Syntaxint fclose(FILE *fp)
feof(): This function checks for end of file while reading datafrom a disk file. It returns a –1 when the file comes toan end otherwise it returns a 0(zero).
int feof(FILE *fp)The below two programs demonstrates the data creation program
and processing program of student data.
Program 156:/* Data creation program
To store student name, number and marks in three subjectsin infotech.dat file*/
#include "stdio.h"main(){
char sna[20];int sno,m1,m2,m3;char ch;FILE *p;
p=fopen("infotech.dat","w");if(p==NULL){printf("not pos");exit(0);}do{printf("enter student name");scanf("%s",&sna);
5/11/2018 Fundamentals and C Language - slidepdf.com
http://slidepdf.com/reader/full/fundamentals-and-c-language 134/162
printf("enter student number");scanf("%d",&sno);printf("enter marks in 3 subjects ");scanf("%d%d%d",&m1,&m2,&m3);fprintf(p,"%20s%5d%3d%3d%3d",sna,sno,m1,m2,m3);printf("any more y/n");ch=getch();}while(ch=='y');fclose(p);
}Program 157:
/* Accessing program To read student data from infotech.dat file */
#include "stdio.h"main(){char sna[20];int sno,m1,m2,m3;char ch;FILE *p;float tot,avg;
p=fopen("infotech.dat","r");
if(p==NULL){printf("Accessing not possible");exit(0);}clrscr();while(!feof(p)){fscanf(p,"%20s%5d%3d%3d%3d",&sna,&sno,&m1,&m2,&m3);printf("student name :%s\n",sna);printf("student number :%d\n",sno);printf("marks in 3 sub :%d %d %d\n",m1,m2,m3);tot=m1+m2+m3;avg=tot/3;printf("student total marks :%f\n",tot);printf("student avg marks :%5.2f\n",avg);}fclose(p);
}
fwrite(): Writes to a stream
size_t fwrite(const void *ptr, size_t size, size_t n, FILE *fp);
5/11/2018 Fundamentals and C Language - slidepdf.com
http://slidepdf.com/reader/full/fundamentals-and-c-language 135/162
Writes n items of size bytes each. Returns the number of items(not bytes) actually written.
fread(): Reads data from a stream
size_t fread(void *ptr, size_t size, size_t n, FILE *fp);
Reads n items of size bytes each. Returns the number of items(not bytes) actually read.
The following two programs are used to store the data of studentand read the data
Program 158:
/* Data creation programWrite a program to store student details into disk using fwrite() */
#include "stdio.h"main(){struct student{
char sna[20];int sno,m1,m2,m3;};struct student s;char ch;FILE *p;
p=fopen("infotech1.dat","wb");if(p==NULL){printf("not pos");exit(0);}do{printf("enter st name");scanf("%s",&s.sna);printf("enter st number");scanf("%d",&s.sno);printf("enter marks in 3 sub");
scanf("%d%d%d",&s.m1,&s.m2,&s.m3);fwrite(&s,sizeof(s),1,p);printf("any more y/n");ch=getch();}
5/11/2018 Fundamentals and C Language - slidepdf.com
http://slidepdf.com/reader/full/fundamentals-and-c-language 136/162
while(ch=='y');fclose(p);}
Program 159:
/* Processing program To read student data from infotech1.dat file with fread() */#include "stdio.h"main(){struct student
{char sna[20];int sno,m1,m2,m3;};struct student s;char ch;FILE *p;
p=fopen("infotech1.dat","rb");if(p==NULL){printf("not pos");exit(0);}clrscr();while(fread(&s,sizeof(s),1,p)){printf("st name :-%s\n",s.sna);printf("st number :-%d\n",s.sno);printf("marks in 3 sub :-%d %d
%d\n",s.m1,s.m2,s.m3);}
fclose(p);}
5/11/2018 Fundamentals and C Language - slidepdf.com
http://slidepdf.com/reader/full/fundamentals-and-c-language 137/162
Data of any text file can be read by ‘C’ file program
fgetc() : Gets character from a stream
Syntaxint fgetc(FILE *fp);
fputc() : Outputs a character to a stream
int fputc(int c, FILE *fp);
Program 160:
/* Reading data from text file*/
#include "stdio.h"
main(){char name[12],ch;FILE *p;
printf("enter file name to list");scanf("%s",&name);p=fopen(name,"r");if(p==NULL){printf("File Not Found :- %s",name);
exit(0);}while(!feof(p)){ch=fgetc(p);printf("%c",ch);}fclose(p);
}
5/11/2018 Fundamentals and C Language - slidepdf.com
http://slidepdf.com/reader/full/fundamentals-and-c-language 138/162
Program 161:
/* Write a program to accept a file name and list out
number of characters, words and lines present in it */
#include "stdio.h"main(){char name[12],ch;FILE *p;int nc=0,nw=0,nl=0;
printf("enter file name to list");scanf("%s",&name);p=fopen(name,"r");if(p==NULL){printf("File Not Found :- %s",name);exit(0);
}while(!feof(p)){ch=fgetc(p);
nc++;if(ch==' ')nw++;
if(ch=='\n'){
5/11/2018 Fundamentals and C Language - slidepdf.com
http://slidepdf.com/reader/full/fundamentals-and-c-language 139/162
nw++;nl++;
}}fclose(p);clrscr();printf("no of lines %d\n",nl);printf("no of words %d\n",nw);printf("no of char %d\n",nc);getch();
}
Program 162:
/*Write a program to read data from one file and write it intoanother file */
#include "stdio.h"main(){char sname[12],tname[12],ch;FILE *p,*q;
printf("enter file name to read");scanf("%s",&sname);p=fopen(sname,"r");if(p==NULL){printf("File Not Found :- %s",sname);exit(0);
}printf("enter file name to write");scanf("%s",&tname);
q=fopen(tname,"w");while(!feof(p)){ch=fgetc(p);fputc(ch,q);
5/11/2018 Fundamentals and C Language - slidepdf.com
http://slidepdf.com/reader/full/fundamentals-and-c-language 140/162
}fcloseall();
}
Program 163:
/* Accept characters from keyboard and store it in notes.txt file*//* type 0 to exit */
#include<stdio.h>main(){int ch;FILE *p;clrscr();
p=fopen("notes.txt","w");while(1){ch=getche();if(ch=='0')break;
fputc(ch,p);}fclose(p);
}
Program 164:
/* Accessing the data of above program*/
#include<stdio.h>main(){int ch;FILE *p;p=fopen("notes.txt","r");clrscr();while(!feof(p)){ch=fgetc(p);putchar(ch);
}fclose(p);
getch();}
Data appending and accessing program
5/11/2018 Fundamentals and C Language - slidepdf.com
http://slidepdf.com/reader/full/fundamentals-and-c-language 141/162
Rewind(): repositions a file pointer to the beginning of a stream.
Syntax
void rewind(FILE *fp);
Program 165:
/* Program to append employee data and read it*/#include<stdio.h>main()
{int eno,bsal;char ena[20],ch;float hra, da, ta, pf, tax, ins, gross, net;FILE *p;p=fopen("emp1.dat","a+");do{printf("Enter Name,Number ,Basic salary");scanf("%s%d%d",&ena,&eno,&bsal);
fprintf(p,"%10s%5d%5d\n",ena,eno,bsal);printf("Any More Records to add Y/N");ch=getch();}while(ch=='y' || ch=='Y');
5/11/2018 Fundamentals and C Language - slidepdf.com
http://slidepdf.com/reader/full/fundamentals-and-c-language 142/162
rewind(p);
while(!feof(p)){fscanf(p,"%10s%5d%5d\n",&ena,&eno,&bsal);hra=bsal*0.1;da=bsal*0.05;ta=bsal*0.03;pf=bsal*0.01;tax=bsal*0.02;ins=500;gross=bsal+hra+da+ta;net=gross-(ins+pf+tax);printf("EMPLOYEE NUMBER IS %d\n",eno);printf("EMPLOYEE NAME IS %s\n",ena);
printf("EMPLOYEE BSAL IS %d\n",bsal);printf("EMPLOYEE GROSS IS %f\n",gross);printf("EMPLOYEE NET IS %f\n",net);printf("\n\n");getch();}fclose(p);}
File Merging : The data available in two different files with samefile structure can be merged and made as single file.
Program 166:
#include<stdio.h>/*MERGING FILERead the data from stud1.data file , stud2.dat file and store it instudent.dat fle*/main(){int sno,marks;char sna[20],ch;FILE *p,*q,*r;p=fopen("stud1.dat","r");q=fopen("stud2.dat","r");
r=fopen("student.dat","w");while(!feof(p)){fscanf(p,"%20s%5d%5d\n",&sna,&sno,&marks);fprintf(r,"%20s%5d%5d\n",sna,sno,marks);
5/11/2018 Fundamentals and C Language - slidepdf.com
http://slidepdf.com/reader/full/fundamentals-and-c-language 143/162
}while(!feof(q)){fscanf(q,"%20s%5d%5d\n",&sna,&sno,&marks);fprintf(r,"%20s%5d%5d\n",sna,sno,marks);
}fcloseall();}
Splitting the data of one file to multiple files
Program 167:
/* spliting the data into pass.dat and fail.dat from student.dat*/#include<stdio.h>
main()
{int sno,marks;char sna[20];FILE *p,*q,*r;p=fopen("student.dat","r");q=fopen("pass.dat","w");r=fopen("fail.dat","w");while(!feof(p)){
fscanf(p,"%10s%5d%5d\n",&sna,&sno,&marks);if(marks>50)fprintf(q,"%10s%5d%5d\n",sna,sno,marks);
elsefprintf(r,"%10s%5d%5d\n",sna,sno,marks);
}fcloseall();}/* Reading data from pass.dat*/
q=fopen("pass.dat","r");
while(!feof(q)){fscanf(q,"%10s%5d%5d\n",&sna,&sno,&marks);printf("\nPASS RECORDS\n");printf("STUDENT NUMBER IS %d\n",sno);printf("STUDENT NAME IS %s\n",sna);printf("STUDENT MARKS IS %d\n",marks);
getch();}fclose(q);
/*Reading data from fail.dat*/
5/11/2018 Fundamentals and C Language - slidepdf.com
http://slidepdf.com/reader/full/fundamentals-and-c-language 144/162
r=fopen("fail.dat","r");while(!feof(r)){fscanf(r,"%10s%5d%5d\n",&sna,&sno,&marks);printf("\nFAIL RECORDS\n");printf("STUDENT NUMBER IS %d\n",sno);printf("STUDENT NAME IS %s\n",sna);printf("STUDENT MARKS IS %d\n",marks);
getch();}fclose(r);
}
Random access files : In random access files, there is facility toread data from required position.
The functions used are fseek(), ftell()
fseek() : Positions the file pointer of a stream
int fseek(FILE *fp, long offset, int whence);
offset is the new position relative to the position specified bywhence.Whence Sets seek starting points as follows
SEEK_SET / 0 - seeks from beginning of fileSEEK_CUR /1 - seeks from current positionSEEK_END /2 - seeks from end of file
Returns 0 if successful or nonzero on failure.
ftell() : Returns the current file pointerSyntax
long ftell(FILE *fp);Returns the current file-pointer position on success or -1L on
error.Program 168:
/* Accept input from key board and store it in file. Read fromrequired character */
# include <stdio.h>main()
{FILE *fp;int no;char ch;/* To store data into file. Press ^z or F6 to stop */
5/11/2018 Fundamentals and C Language - slidepdf.com
http://slidepdf.com/reader/full/fundamentals-and-c-language 145/162
fp=fopen("infotech.txt","w");while((ch=getchar())!=EOF)fputc(ch,fp);printf("Number of characters stored %d\n",ftell(fp));fclose(fp);/* To read data from required position */fp=fopen("infotech.txt","r");printf("\nEnter position number to read from ");scanf("%d",&no);fseek(fp,no,0);while(!feof(fp)){ch=fgetc(fp);putchar(ch);
}fclose(fp);
getch();}
Exercise
Write a file program to store and read the details of employees Write a file program to append the details of students Write a file program using fwrite and fread functions
Write a file program to accept a file name and read the data fromrequired position
Explain fprintf, fscanf, fgetc, fputc.
Data Structures
Organizing and accessing the data in a methodical way withefficient memory management and processing speed is the centralconcept of data structures.
The data structuring can be done in two ways:
5/11/2018 Fundamentals and C Language - slidepdf.com
http://slidepdf.com/reader/full/fundamentals-and-c-language 146/162
Non Pointer programming Pointer programming
In Non pointer programming, the set of data is organized andaccessed in methodical order using arrays, structures andcombination.
In pointer oriented programming the set of data is organized andaccessed with the help of pointers and address references. Thisstyle is preferred for its speed and storage management. Someexample programs on pointer data structures are Linked lists,stacks, queues, trees etc.
The header files stdlib.h and alloc.h are included for pointer basedprograms. Some of the functions of these header files are as
follows
alloc() : This function allocates specified number of bytes inheap of memory and fill it with zeros.
SyntaxChar *alloc(size)
Example:
struct student *ptr;prt = (struct student*)alloc(sizeof(struct student));
malloc() : This function allocates specified number of bytes inheap of memory but it is not filled with zeros.
Syntax:char *malloc(size)
Example:struct student *ptr;prt = (struct student*)malloc(sizeof(struct student));
calloc(): This function allocates contiguous memory.
Syntax
Char *calloc(elements,element_size);
Examplesturct student *ptr;
5/11/2018 Fundamentals and C Language - slidepdf.com
http://slidepdf.com/reader/full/fundamentals-and-c-language 147/162
prt = (sturct student*)calloc(5,sizeof(struct student));
realloc(): This function is used to increase or decrease the size of memory.
Syntaxchar *realloc(old block,size)
Exampleptr =realloc(prt,5);
free(): This is used to free the allocated memory space.
Syntaxint free(pointer)
Examplefree(ptr);
Linked list :
The dynamic allocation of memory for data and de allocationcan be done with linked lists.
The problem with arrays is, it is with static memoryallocation. The specified number of elements are allocated andthey cannot be increased or decreased. Dynamic insertion anddeletion of elements is not possible with array based programs.
We can over come the above problems with pointer basedlinked list programs.
Linked list contains self referencing structures. Each structureis called node. Every node is with two parts. The first part iscalled information part and the second part is called pointer part.
The information part contains the data to be stored and thepointer part contains the address of the next node to point. Thelast node of linked list’s pointer part contains NULL.
The single linked list is also called a linear linked list or one waylinked list.
Example
Linked list
5/11/2018 Fundamentals and C Language - slidepdf.com
http://slidepdf.com/reader/full/fundamentals-and-c-language 148/162
222
Adding node with data 80
222 333
Inserting node with data 60 in between 40 and 80
111 222 444333
Deleting node with data 40
111 444 333
Programs on Linked lists :Single Linked list :
Program 169:
/* Single linked list program *//* Program to implement Single Linked List */
#include <stdio.h>#include <conio.h>#include <stdlib.h>#include <alloc.h>/* The structure slist */struct slist{int no;struct slist *next;
};typedef struct slist node;node *start = NULL, *n = NULL, *ptr = NULL;void insert();void delete();
OutputEnter ur choice asshown:1. Insert2. Delete3. Display4. Exit
Enter ur choice here : 3
10 40222
null
10 40222
444 60333l 80 null
10444
60 333 80 null
10 40222
333 80 null
5/11/2018 Fundamentals and C Language - slidepdf.com
http://slidepdf.com/reader/full/fundamentals-and-c-language 149/162
void display();
/* The main program */main(){int ch;clrscr();while(1){printf("\n Enter ur choice as shown :\n");printf("\n 1. Insert\n 2. Delete\n 3. Display\n 4. Exit\n");
printf("\n Enter ur choice here : ");scanf("%d",&ch);switch(ch){case 1:insert();display();break;
case 2:
delete();display();break;
case 3:display();break;
default:exit(0);
}}
}
/* The function insert */
void insert(){int m,ch,num;
n = (node *)malloc(sizeof(node));
printf("\n Enter an element : ");scanf("%d",&num);
n->no = num;
5/11/2018 Fundamentals and C Language - slidepdf.com
http://slidepdf.com/reader/full/fundamentals-and-c-language 150/162
n->next = NULL;
if(start == NULL)start = n;
else{printf("\n Enter ur choice as shown :\n");printf("\n 1. Insert at start");printf("\n 2. Insert at end");printf("\n 3. Insert at given node\n");printf("\n Enter ur choice here : ");scanf("%d",&ch);switch(ch){case 1:n->next = start;
start = n;break;
case 2:ptr = start;while(ptr->next != NULL)ptr = ptr->next;
ptr->next = n;break;
case 3:printf("\n Enter node after which element should be inserted?");
scanf("%d",&m);
ptr = start;
while(ptr != NULL){if(ptr->no == m)break;
ptr = ptr->next;}
if(ptr == NULL){printf("\n Match not found.");return;
}
n->next = ptr->next;ptr->next = n;break;
}
5/11/2018 Fundamentals and C Language - slidepdf.com
http://slidepdf.com/reader/full/fundamentals-and-c-language 151/162
}}
/* The function delete */
void delete(){int m;printf("\n Enter node to be deleted : ");scanf("%d",&m);n = start;if(start->no ==m){n = start;start = start->next;free(n);
}else{while(n!=NULL){if(n->next->no == m)break;
n = n->next;}
if(n==NULL){printf("\n Match not found.");return;
}ptr = n->next;n->next = n->next->next;free(ptr);}
}
/* The function display */
void display(){ptr = start;printf("\n ");while(ptr!=NULL){
printf("%d -> ",ptr->no);ptr = ptr->next;}
printf("NULL");}
5/11/2018 Fundamentals and C Language - slidepdf.com
http://slidepdf.com/reader/full/fundamentals-and-c-language 152/162
Double Linked list : It is similar to single linked list but with anadded facility of bi -directional traversing. That is one can traversefrom first node to last node as well as from last node to first node.Hence it is also called two way linked list.
Each node of double linked list contains three parts. The first partis called before pointer which contains the address of previousnode. The second part is called information part which containsthe data. The third part is called next pointer which contains theaddress of next node. The address in the before pointer of veryfirst node and the address in the next pointer of last node is NULL.
Example:
Double linked list
11 222
Adding node to double linked list
111 222 333
Deleting node with data 40 from double linked list
111 333
Program 170:
/* Double Linked List */
#include <stdio.h>#include <conio.h>#include <alloc.h>
#include <stdlib.h>
/* The struct dlist */struct dlist{
OutputEnter ur choice as shownbelow:1. Insert2. Delete3. Display4. Exit
Enter ur choice here : 1
null 10 222111
40 null
null 10 222111
40 333222
90 null
null 10 333111
90 null
5/11/2018 Fundamentals and C Language - slidepdf.com
http://slidepdf.com/reader/full/fundamentals-and-c-language 153/162
int no;struct dlist *prev;struct dlist *next;
};
typedef struct dlist node;
node *start = NULL, *tail = NULL, *n = NULL, *p = NULL;
void insert();void delete();void display();
/* The main program */
main(){int ch;clrscr();while(1){
printf("\n\n Enter ur choice as shown below :\n");printf("\n 1. Insert\n 2. Delete\n 3. Display\n 4. Exit\n");printf("\n Enter ur choice here : ");scanf("%d",&ch);
switch(ch){case 1:insert();display();break;
case 2:delete();display();break;
case 3:display();break;
default:
exit(0);}
}}
5/11/2018 Fundamentals and C Language - slidepdf.com
http://slidepdf.com/reader/full/fundamentals-and-c-language 154/162
/* The function insert */
void insert(){int m,ch,num;n = (node *)malloc(sizeof(node));printf("\n Enter an element : ");scanf("%d",&num);n->no = num;n->prev = n->next = NULL;if(start == NULL){start = tail = n;return;}
printf("\n Enter ur choice as shown below :\n");printf("\n 1. Insert at start.");printf("\n 2. Insert at end.");printf("\n 3. Insert at given node.\n");printf("\n Enter ur choice here : ");scanf("%d",&ch);
switch(ch){
case 1:n->next = start;start->prev = n;start = n;break;
case 2:tail->next = n;n->prev = tail;tail = n;break;
case 3:printf("\n Enter node after which the element is to be inserted?
");scanf("%d",&m);
p = start;
while(p!=NULL){
if(p->no == m)break;
p = p->next;}
5/11/2018 Fundamentals and C Language - slidepdf.com
http://slidepdf.com/reader/full/fundamentals-and-c-language 155/162
if(p==NULL){printf("\n Match not found.");return;
}
n->next = p->next;p->next->prev = n;p->next = n;n->prev = p;
if(n->next == NULL)tail = n;
break;}
}
/* The function delete */
void delete()
{int m;printf("\n Enter element to be deleted : ");scanf("%d",&m);
if(start->no == m){n = start;if(start == tail)start = tail = NULL;
elsestart = start->next;
free(n);return;}
if(tail->no == m){n = tail;
tail = tail->prev;tail->next = NULL;return;}
5/11/2018 Fundamentals and C Language - slidepdf.com
http://slidepdf.com/reader/full/fundamentals-and-c-language 156/162
n = start;while(n!=NULL){if(n->no == m)break;
n = n->next;}
if(n == NULL){printf("\n Match not found.");return;}
n->prev->next = n->next;n->next->prev = n->prev;
free(n);}
/* The function display */
void display(){n = start;printf("\n NULL <-> ");while(n!=NULL){printf("%d <-> ",n->no);n = n->next;}
printf("NULL");}
Circular Linked List:
Circular linked is similar to linked list but the pointer part of lastnode will be referring to the first node.
Example
111 222 333444
10 40222
333 60 444 80 111
5/11/2018 Fundamentals and C Language - slidepdf.com
http://slidepdf.com/reader/full/fundamentals-and-c-language 157/162
Program 171:
/* circular linked list */#include "stdio.h"main(){struct stu{int sno;struct stu *next;};
struct stu *f,*l,*n;char ch;
f=l=n=NULL;clrscr();
do{
n=(struct stu *)malloc(sizeof(struct stu));printf("enter a no");scanf("%d",&n->sno);
if(f==NULL)f=n;elsel->next=n;
l=n;l->next=f;
printf("any more nodes to add y/n");ch=getch();
}while(ch=='y');
clrscr();n=f;do{printf("%5d",n->sno);n=n->next;
}while(n!=f);
getch();}
5/11/2018 Fundamentals and C Language - slidepdf.com
http://slidepdf.com/reader/full/fundamentals-and-c-language 158/162
Queues : Queue is an ordered group of elements in whichelements are added at last called rear end and elements aredeleted from front. This is first in – first out (FIFO) concept.
Operations on queue are
1. adding elements2. deleting elements3. Displaying elements
ExampleQueue
222
Adding node with data 80 to queue
111 222 333 Deleting node from queue
222 333Program 172:
/* Example on queue */
#include "stdio.h"main(){
struct node{int no;struct node *next;};
struct node *n, *f, *l;int c;
f=l=n=NULL;do{clrscr();gotoxy(30,5);
10 40222
null
40 333 80 null
10 40222
333 80 null
5/11/2018 Fundamentals and C Language - slidepdf.com
http://slidepdf.com/reader/full/fundamentals-and-c-language 159/162
printf(" QUEUE ");gotoxy(27,7);printf("1 Add");gotoxy(27,8);printf("2 Delete");gotoxy(27,9);printf("3 List");gotoxy(27,10);printf("4 Quit");gotoxy(10,12);printf("enter choice :-\t");scanf("%d",&c);
switch(c){
case 1:n=(struct node *)malloc(sizeof(struct node));
printf("enter st number\t");scanf("%d",&n->no);if(f==NULL)f=n;
elsel->next=n;l=n;l->next=NULL;
break;
case 2:if(f==NULL)printf("q is empty");
else{n=f;f=f->next;free(n);}getch();break;
case 3:if(f==NULL)printf("q is empty");
else{n=f;
while(n){printf("%5d",n->no);
n=n->next;}
}getch();break;
5/11/2018 Fundamentals and C Language - slidepdf.com
http://slidepdf.com/reader/full/fundamentals-and-c-language 160/162
}}while(c<4);
}
Stack : Stack is an ordered set of elements in which elements areadded and deleted at same end of stack called stack top. Addingelements is called pushing and deleting elements is called poping.
This follows last in first out (LIFO) concept. So the element whichis added last will be removed first and the element which is addedfirst will be removed last.
Different operations on stack are 1.pushing elements 2.popingelements 3. displaying elements.
Example
Stack
Stack top
111 222
Pushing node with data 10 to stack stack top
333 111 222
Poping from stack Stack top
111 222
10 40111
222 80 null
40 222 80 null
40 222 80 null
5/11/2018 Fundamentals and C Language - slidepdf.com
http://slidepdf.com/reader/full/fundamentals-and-c-language 161/162
Program 173:
/* Example on stack */
#include "stdio.h"main(){
struct node{int no;struct node *next;};
struct node *n,*f;int c;f=n=NULL;
do
{clrscr();gotoxy(30,5);printf(" STACK ");gotoxy(27,7);printf("1 Push");gotoxy(27,8);printf("2 Pop");gotoxy(27,9);
printf("3 Peep");gotoxy(27,10);printf("4 Quit");gotoxy(10,12);printf("enter choice :-");scanf("%d",&c);switch(c){case 1:
n=(struct node *)malloc(sizeof(struct node));printf("enter st number");scanf("%d",&n->no);n->next=f;f=n;break;
case 2:if(f==NULL)printf("stack is empty");
else
{n=f;
f=f->next;free(n);}
5/11/2018 Fundamentals and C Language - slidepdf.com
http://slidepdf.com/reader/full/fundamentals-and-c-language 162/162
getch();break;
case 3:if(f==NULL)printf("stack is empty");
else{
n=f;while(n){printf("%5d",n->no);n=n->next;
}}getch();break;
}}while(c<4);
}