You are on page 1of 162

COMPUTER FUNDAMENTALS What is a computer?

Characteristics of Computer History of Computers Abacus Pascals Mechanical Calculator Charles Babbages Differential Engine Mark I Electronic Numeric Integrator and Calculator (ENIAC) Universal Automatic Computer (UNIVAC) Computer Families Generations Block diagram of Computer Looking Inside The Machine The Input devices The Output Devices The CPU Memory Unit The Microprocessor The Memory Unit The Secondary Storage Operating System Booting 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.

Instruction Program

Command that a computer can understand. Set of Instructions.

Characteristics of Computer: Speed No. of instructions executed per second Speed

is Measured in MHz, MIPS, FLOPS etc., Storage Computer can store data temporarily and permanently The storage is measured in Bits, Bytes, Kilo bytes, Mega bytes, Giga bytes Accuracy Computer never goes wrong Reliability Computer doesnt cheat Versatility Can be used in multiple ways History of Computers: The evolution of computer has passed through different stages before it reached the present state of development. The evolution probably started from the 3500 BC when human being first started to learn to calculate with a calculating machine named Abacus. Abacus: Abacus seems to be the earliest calculating machine, which was developed by the Chinese. Abacus consists of beads, which can move, in wires. Pascals 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 consisted of gears, wheels and dials.Charles Babbages Differential Engine: Charles Babbage, a professor of mathematics at Cambridge University, invented a machine called Differential Engine which could evaluate accurately algebraic expressions and mathematical tables correct up to 20 decimal place. Mark I: In 1934 Harvard professor H. Eiken developed an automatic calculating machine, which was called Mark-I digital computer. Its internal operation was automatically controlled. Electronic Numeric Integrator and Calculator (ENIAC): While Mark-I was the first electromechanical computer, the first electronic general purpose computer was built in 1946. It was a bulky machine consisting of 18,000 vacuum tubes, 70,000

resistors, 10,000 capacitors, 60,000 switches and a large size occupying 1500 Sq. feet of space. Universal Automatic Computer (UNIVAC): In the year 1946, Eckert and Mauchly founded their own company and began to work on the Universal Automatic Computer, or UNIVAC. 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 the result. 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 Hybrid Computers. Robots are best example for hybrid Computers. Digital Computers can be classified based on Size, Cost, and Speed: Super Computers Most powerful: There are the largest and fastest computers available but are typically not used in specialized areas such as in Defence, Aircraft design, computer generated movies, weather search. Super computers can process 64 bits or more at a time. Their processing speed ranges from 10,000 million instructions per sec (MIPS) to 1.2 billion instructions per sec. They can support 10,000 terminals at a time. 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 a Mainframe. Mainframes have large on-line secondary storage capacity. Mini Computers: This type of computer performs data processing activities in the same way as the Mainframe but on a smaller scale. The cost of minis is lower.

Micro computers: This is the smallest category of computers, consisting of a microprocessor and associated storage and input/output devices. These are also called Personal Computers. Personal Computers (PC) Small computers Personal computer is so named because it is designed for personal use. 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 first generation computers. They were extremely large with low reliability. The first generation computers had the following unfavorable features. 1. 2. 3. Too bulky in size. Unreliable for excessive heal generation. Air conditioning requirement was too much due to heat generation. 4. Non-portable Second Generation (1955 - 1964) Transistors Advantages: 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 computers 2. More reliable 3. Less heat generated 4. Faster computational speed

Disadvantages: Some unfavorable features also are seen in this generation 1. Air conditioning required. 2. Frequent maintenance required, 3. Commercial production was difficult and costly.

Third Generation (1964 1975) Integrated Circuits Advantages : 1. Smaller in size as compared lo previous computers 2. Even more reliable than second generation 3. Lower heat generated than second generation 4. Reduce computational limes 5. Low maintenance cost 6. Comparatively portable 7. Less power consumption 8. Commercial production easier and cheaper Fourth Generation (1975 1984) VLSI Advantages : 1 Low cost machine 2, High speed 3. Large memory A. Small size 5 Less power consumption 6. Floppy disk is used as storage device 7. Hardware failure is negligible 8. Cheapest among all generations

generation

Fifth Generation (1984 1990) Silicon Chips Scientists 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 and improve speed, miniaturization and cost reduction Block diagram of Computer:
CPU ALU Input CU Output

Memory

Storage

CPU Central Processing Unit ALU Arithmetic Logical unit CU Control Unit

Looking Inside The Machine: Input devices To accept data from user Output devices To display results Processor To process the user inputs Memory To store the results temporarily Storage devices For permanent storage Buses Means of communication in CPU Mother board Circuit board that connects CPU to all other H/W devices The Input devices: Keyboard. Mouse. Trackball. Track pad. Joystick. Light Pen Mike (or) Micro Phone. Bar Code Readers. Scanner. Touch Screens. The Output Devices: The Monitor The Printer The Sound Systems The CPU: CPU in it. ALU CU The Micro processor Arithmetic Logical Unit Control Unit Central Processing Unit It has a cabin like structure with many components placed

Memory Unit Primary storage Secondary storage The Microprocessor: It is a chip which performs all the tasks. ALU It performs Arithmetic and Logical operations CU It controls the operations performed by the computer Example: Intel Pentium Processor

The Memory Unit: Memory Storage area where data is stored ROM 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 area RAM 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 like memory, processes, peripherals and files OS acts as an interface between system and user Functions: 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.

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: Computer Hardware Application Packages Languages Utilities Software System

OS, Compilers, Interpreters

Low level

Assembly

High level

Hardware Touchable parts of Computer Software 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.

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 Langua Organization r ge 196 ALGOL60 International committee 0 196 3 196 7 197 0 197 2 CPL BCPL B C Cambridge university Martin Richards at Cambridge university Ken Thompson at AT&T Bell Labs Dennis Ritchie at AT&T Bell Labs Remarks Too general, too abstract Hard to learn and difficult to implement Could deal with only specific problems Could deal with only specific problems Lost generality and restored B

CPL Combined Programming Language BCPL Basic Combined Programming Language Computer languages: Problem oriented languages: These are also called high level languages. These are mainly used for faster program development.

Examples: COBOL, Pascal, FORTRAN, etc; Machine oriented languages: These are also called low level languages. These are mainly used for faster program execution. Note: C is middle level language. It has features of both high level as well 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 with other people. C is a language through which we can communicate with a computer to fulfill our requirements. Steps in learning English Language: Alphabet Words Sentences Paragraphs

Steps in learning C Language: Alphabets Digits Special symbols

Constants Variables Keywords

Instructions

Program

Features of C Language:
C is a system programming language with which we can develop

other languages, packages, operating systems, editors, linkers, loaders, assemblers and utilities.
C is a structured programming language. It follows a methodical

structure to develop a program.

It is strictly typed language. We should define data type for every

variable we use in the program.


It

supports high level programming as well as low level programming with the concept of Bit wise operators and Interrupts. 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 supports data structures. Dynamic allocation and de allocation of

C is a function oriented language. It supports file handling facility with which we can store the data

permanently on magnetic media. This facilitates C to use in commercial applications.


C is basically a scientific language which gives single precision and

double 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 to represent information. Alphabets Digits Special symbols A, B, Y, Z a, b, y, z 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 ~`!@#%^&*()_-+=| \{} []:;<>,.?/

Constants, Variables and Keywords: The alphabets, numbers and special symbols when properly combined, form constants, variables and keywords. Constant is an element whose value cannot be changed.

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: C Constants Primary Constants Secondary Constants Primary Constants Integer Constant Real Constant Character Constant Secondary Constants Array Pointer Structure Union Enum etc.

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 an optional sign + or The allowable range for integer constant is -32768 to +32767 Ex: 1063 -100 Real Constants: Real constants are also called Floating Point constants. There are 2 types of Real Constants: Fractional Form: The real constant may be either +ve or ve with a decimal point in it. Ex: +325.34 -0.10 Exponential Form: This form is used if the value of real constant is too small or too large. In this form a real constant is represented in two parts separated by e.

The part before e is called mantissa and the part after e is called exponent. The range of real constants is -3.4e38 to +3.4e38 Ex: +3.2e-5 1.2e8 -1.6e-10 -2.4e+5 Character Constants: Any valid character in C character set enclosed in single quotes is considered as character constant. Character constants may be simple characters or character strings. Ex: simple characters : A l 6 @ Character strings: ant, 100, computer Simple Characters are enclosed in single quotes. And strings are enclosed in double quotes. Variables: Variable is a name that is used to represent a data in the computers memory. In other words variables are names given to locations in memory. The data of a variable can be modified at any time during the program execution. Variable is also called as Dataname 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 can hold values of only that type. For example, an integer variable can hold only integer constants and a real variable can hold only real constants. Rules for constructing variables: A variable name is a combination of alphabet (upper and lower case), 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.

C Keywords: Keywords are the words which have some pre-defined meaning. The keywords cannot be used as variable names because if we do so we are trying to redefine the keyword, which is invalid. The keywords are also called Reserved words. There are 32 keywords in C. auto break case char const continue default do 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 4 primitive data types:

double else enum extern float for goto if

Int Long Register Return Short Signed Sizeof Static

struct switch typedef union unsigned void volatile while

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 a sequence of bytes. The size of each data type and the permissible range is given below. Data type int float double char Size (in bytes) 2 4 8 1 Range -32768 to +32767 -3.4e38 to +3.4e38 -1.7e308 to +1.7e308 -128 to +127 (256 characters ASCII)

Derived data types and format characters:

Derived data types are derived from the primitive data types. These are used for effective memory usage and to increase the range of values allowed 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 is corresponding format character. Data Type signed char unsigned char short signed int short unsigned int signed int Range -128 to +127 0 to 255 -32768 to +32767 0 to 65535 Bytes 1 1 2 2 2 2 4 4 4 8 10 Format %c %c %d %u %d %u %ld %lu %f %lf %Lf

-32768 to +32767 unsigned int -32768 to +32767 long signed -2147483648 int to +2147483647 long unsigned 0 to int 4294967295 Float -3.4e38 to +3.4e38 double -1.7e308 to +1.7e308 long double -1.7e4932 to +1.7e4932

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. A C 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 cant insert blank spaces in a variable, keyword or constant.

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

C operators

Arithmetic operators

Assignment operators

Comparison & logical operators

Bit wise operators

Special operators

Relational operators

Equality operators

Logical operators

Unary operato rs

Ternary operato r

Comma operato r

Other operato r

Arithmetic Operators : They are used to perform arithmetic calculations by evaluating arithmetic expressions. operat or + * / % purpose addition subtraction multiplication division Modulo (remainder)

Assignment operators : These are used to assign the values to variables.

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 to variable 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. operat or < > <= >= 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 operat or == != purpose Equal to Not equal to

Logical operators : They are used for multiple condition checking.

operat or && || !

purpose Logical and Logical or Logical not

Bitwise operators : They are low level operators used to perform logical calculation on bits i.e binary digits Operat or & ^ | >> << ~ 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 Meaning or * Pointer & Address of variable Negative value ! Negation ~ Bitwise complement ++ Incrementer -Decrementer Type Forced type of conversion Sizeof Size of subsequent data type in bytes
2. Ternary operator:

It is used for checking the conditions. It is short hand version of ifelse statement. (condition) ? expression1 : expression2
3. Comma operator:

It is used to separate the variable in variable declarations and expressions in for looping structure. Eg : int a,b,c; Other operators: Parentheses for grouping expressions Membership operators used with arrays,structures,unions. Eg: . [] -> OPERATORS AND THEIR PRECEDENCE OPERATOR () [] + ++ -! ~ * & sizeof (type) * / % + << >> < <= > >= == != & ^ | DESCRIPTION Function call Array element reference Unary plus Unary minus Increment Decrement Logical negation Ones complement Pointer reference Address Size of an object Type cast (conversion) Multiplication Division Modulus Addition Subtraction Left shift Right shift Less than Less than or equal to Greater than Greater than or equal to Equality Inequality Bitwise AND Bitwise XOR Bitwise OR ASSOCIATIVI TY Left to right Right to left RAN K 1 2

Left to right Left to right Left to right Left to right

3 4 5 6

Left to right Left to right Left to right Left to right

7 8 9 10

&& || ?: = *= /= %=+= -= &= ^= |= <<= >>= , C program :

Logical AND Logical OR Conditional expression Assignment operators

Left to right Left to right Right to left Right to left

11 12 13 14

Comma operator

Left to right

15

Combination of instructions becomes a Program. C program can have declarations, expressions, compound statements and control statements. Declarations: All the variables used in the program are declared to their corresponding 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 to check the conditions of the given expression or variable or constant. Example : if (a>b) big=a; Example : while(condition) Structure of C program: # include files main() {

type or variable declarations statements of operation displaying the results } main() : This is built in function which indicates the beginning of C program. This function internally contains various statements. This in turn can call other functions. printf() : This is an output function. It is used to display output on monitor. It displays 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 keyboard into 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 called remark statements. They are non-executable and are used to increase the readability of program. The comments are given in between /* and */ Example : /* Program to find factorial of a number */ Program 1:

/* Example on printf() */ main() { printf("Welcome to Infotech. "); } Program 2:

Output: Welcome to Infotech.

/* Example on multiple printf() statements */ main() { Output: printf("Welcome to Infotech"); Welcome to Infotech.The choice of printf("The choice of intellectuals"); intellectuals } Escape sequences: These are also called Back slash characters. They are used with output finction i.e printf(). Some times they are also referred as white space characters. Back slash character \a \b \f \n \t \r \n \ \ \\ \0 Program 3: /* Example on '\n' - New line character */ main() { printf("Welcome to Infotech.\n");
Output: Welcome to Infotech. The choice of Intellectuals Bhagya Nagar Kurnool

Purpose Audible alert beep sound Back space Form feed New line Horizontal tab Carriage return New line Single quotation Double quotation Single slash Null character

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 key board. It is used to accept a character with out displaying it on monitor. 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 15 Sum is 15

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 variable declaration is invalid . Program 8: /* Multiple %d in printf() */ main() Sum of 5 and 10 is { 15 int a=5, b=10, c; clrscr(); c = a+b; printf("\n Sum of %d and %d is %d",a,b,c); getch(); }
Output:

Output: Sum is 10

Program 9: /* Evaluate the following expressions 30 - 20 = ? 50 * 10 = ?

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(); }

Output: 30 20 = 10 50 * 10 = 500 50 / 5 = 10

Program 10: /* Example on format characters or %characters */ main() { Output: int a = 10; Integer value is 10 float b = 3.14; Float value is 3.140000 double c = 1.231534; Double value is 1.231534 Character value is a 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 :
Output: 101234 10 1234 00010 01234 10 1234 3.141324 3.14 003.14

Converting a set of declared types to some other required type is called type casting.

A variable belonging to lower range can be converted implicitly to higher range data type but the higher range variable can be explicitly 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 is called mixed mode expression. The size of receiving variables datatype should be greater than or equal to the size of expression variables datatype .

Output: a=3 d=100.00000 0

Output: Result1 : 3.000000 Result2 : 3.333333

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(); }
Output: Sum is 18.976769

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; Output: clrscr(); Enter 1st number : 5 Enter 2nd number : printf("\n Enter 1st number : "); 10 scanf("%d",&a); Sum of 5 and 10 = 15 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() Output: { Enter 2 numbers : 50 int a,b,c; 25 clrscr(); Sum is 75 printf("\n Enter 2 numbers : "); scanf("%d%d",&a,&b); c = a+b; printf("\n Sum is %d",c); getch(); }

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 10 Sum is 60 Difference is 40 Product is 500 Quotient is 5.000000

Output: a%b = 1 a%b = 1 a%b = -1 a%b = -1

% operator always returns the remainder. The sign of result will be same as that of left side value of % . It should not be used with real numbers. Program 19: /* Example on / and % operator Accept number of days and display itOutput: in Enter number of days : 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 relational operators . An expression formed using relational operators is always evaluated 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 res res res = = = = a a a a
Output: Enter 2 numbers : 8 5 8 > 5 is 1 8 < 5 is 0 8 >= 5 is 1 8 <= 5 is 0 8 == 5 is 0 8 != 5 is 1 400 Years = 1 Months = 1 Days = 5

> b; printf("\n %d > %d is %d",a,b,res); < b; printf("\n %d < %d is %d",a,b,res); >= b; printf("\n %d >= %d is %d",a,b,res); <= 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); getch(); }

Logical operators : They are used to relate the conditions logically. The different logical operators are && - And operator || - Or operator ! - Not operator && operator : When conditions are checked with && operator, then if all the conditions are true, the result is evaluated to true. If any condition is false, the result is treated false. Condition 1 False False True True || operator : When conditions are checked with || operator, then if any condition is true, the result is evaluated to true. If all conditions are false, the result is treated false. Condition 1 False False True True ! operator : It negates the condition. If condition is true, by using ! operator , it becomes false and vice versa. Conditio Resul Condition 2 False True False True Resul t False True True True Condition 2 False True False True Resul t False False False True

n False True

t True False

Program 21: /* Example on logical operators */ main() { int a,b,res; clrscr(); printf("\n Enter 2 numbers : "); scanf("%d%d",&a,&b);

Output: Enter 2 numbers : 8 5 (8 > 5) && (8 < 5) is 0 (8 > 5) || (8 < 5) is 1 !(8 == 5) is 1

/* && 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 then the RHS is completely evaluated and that result is computed with LHS and finally the result is stored in LHS i.e., LHS op= RHS; where RHS is any expression op is any operator like + - * / etc.,

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() { Output: int a,b; Enter 2 numbers : 10 clrscr(); 5 printf("\n Enter 2 numbers : "); a = 15 b = 5 scanf("%d%d",&a,&b); a = 10 b = 5 a += b; /* a = a + b */ a = 50 b = 5 a = 10 b = 5 printf("\n a = %d b = %d",a,b); a=0 b=5 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: 10 11 12 13 12 11 10

Output: a = 20 a = 30

/* 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 or post decrementing when used independently i.e., when they are not written in an expression. Pre or post incrementing a in the sense a = a + 1 Pre 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; Output: printf("\n a = ++b + ++c %d %d %d",a,b,c); of a,b,c 0 Initial values a = ++b + c++; 00 a ++b + ++c printf("\n a = ++b + c++ %d %d %d=",a,b,c); 2 1 1 a = ++b + c++ 3 2 2 a = b-- + c--; a = b-- + printf("\n a = b-- + c-- %d %d %d",a,b,c); c-- 4 1 1 getch(); } Program 26: /* To accept Name, sex and pay */

# include <stdio.h> main() { char name[20],sex; int pay; Output: clrscr(); Enter Name Prem printf("Enter Name "); Enter sex m/f m Enter pay scanf("%s",name); 10000 fflush(stdin); printf("Enter sex m/f "); Your Name is Prem scanf("%c",&sex); Sex is m printf("Enter pay "); Pay is 10000 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 accepting the 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 perimeter 5. (Area = 3.14*r*r, Perimeter = 2*3.14*r) 6. Accept base, height of triangle and find its area 7. (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 Kilograms 11. (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

17. 18. 19. 20.

Input temperature in Centigrade, Convert it into Fahrenheit. Explain the rules to declare variable Explain printf() and scanf() functions 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 from current point of program execution to the label specified. Syntax : goto <label>; Program 27: /* Example on goto statement */ main() {
Output: Good Morning Students of Infotech

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. The different 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 or expressions following the condition will be evaluated. If multiple statements are to be processed then they are made as block i.e compound 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 : 1 The number is not 0

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 or expressions following the condition will be evaluated, otherwise the statements or expressions following the else will be processed. 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);

Output: Enter a number : 8 8 is an even number

if(a%2==0) printf("\n %d is an even number."); else printf("\n %d is an odd number."); getch(); } Program 30:

/* 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 printf("\n } else { printf("\n printf("\n } getch(); }

Output: Enter 2 numbers : 4 8 Big = 8 Small = 4

Big = %d",a); Small = %d",b);

Big = %d",b); Small = %d",a);

3. Nested if-else statement : An if-else statement can be written with in another if-else statement and so on. Syntax : if (condition) { <if else statement > } else { <if- else statements> } Program 31: /* Finding greatest of 3 numbers */

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;

Output: Enter 3 numbers : 4 8 3 Biggest number : 8

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> else if (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

>35 - III Class otherwise - 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; Output: Enter student number : 101 avg = (float)tot/3; Enter marks in 3 subjects : 60 printf("\n Number : %d",sno); 70 80 printf("\n Marks : %d %d %d",m1,m2,m3); printf("\n Total : %d",tot); Number : 101 printf("\n Average : %f",avg); Marks : 60 70 80 printf("\n Result : "); Total : 210 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:
Average : 70.000000 Result : I Class

The switch statement is a special multi way decision maker that tests 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>; }

Program 33: /* Accept grade 1/2/3 and display designations 1 - Officer 2-Manager 3-Clerk */ Output:

main() { Designation is 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 the statements following the ? will be processed otherwise the statements following the : will be processed. Syntax : (condition) ? <statement /expression> : <statement / expression>

Enter grade 1/2/3 2

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 Big number = 8

} Looping structures : The structures which are used to iterate the statements conditionally 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 the condition is checked at the bottom of the loop. The loop iterates minimum once. The control directly enters into the loop, executes the statements and then checks the condition. The condition specified can be simple condition or multiple conditions with logical operators. The loop can be nested. Syntax : do { <statements /expressions > } while(<condition>); Program 35: /* Natural numbers from 1 to 5 */ main() { Output: int i=1; 1 2 3 4 clrscr(); 5 do { printf(%5d ,i); i++; } while(i<=5); getch(); } 2). while looping structure : This is the loop with top programming approach. Here the condition 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 condition or multiple conditions with logical operators. The loop can be nested.

Syntax : while(<condition>) { <statements /expressions > } Program 36: /* Example on while loop Program to print 1 to 5 numbers */ main() { int i; Output: clrscr(); Numbers from 1 to 5 : printf("\n Numbers from 1 to 5 :\n\n"); 1 2 3 4 5 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) Output: { Enter 2 numbers : 5 10 printf("%5d",n1); The numbers between 5 and n1++; 10 : } getch(); } Program 38: /* Accept a number and find sum of digits in it eg: 346 = 3+4+6 =13 */

Output: Enter a number : 346 Sum of digits in 346 = 13

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(); }

Output: Enter 2 numbers : 16 40 The G.C.D is 8

3). for looping structure : This is the most common loop of C language. This loop consists of three expressions. The first expressions is used to

initialize the variables. If multiple initializations are to be done then 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 with logical operators. If condition is not specified the loop iterates infinitely. The third expression is increment or decrement part where the processing statements can be written. If multiple statements are to be written then comma is the delimiter. This is optional part. The above three parts are separated by semi colon (;). If the for loop is terminated with semicolon, then self looping takes place i.e loop iterates with in itself. For loop can be nested. When multiple statements are to processed with for loop then those statements should be made as a 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() Output { Sum is 15 int sum,i; clrscr(); for(i=1,sum=0 ; i<=5 ; sum+=i, i++) ; printf(Sum is %d,sum);

Output
1 2 3 4 5

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() { Output: int i; i=1 clrscr(); i=2 i=1; i=3 i=4 while(i<=10) The loop breaked at i { =5 if(i==5) break; printf("\n i = %d",i); i++; } printf("\n The loop breaked at i = %d",i); getch(); }
Output 1 1 1 2 2 2 3 3 3

continue: The control transfers to condition part by skipping all the statements after "continue" Program 44: /* Example on continue */ main() { clrscr(); for(i=1;i<10;i++) { if(i%2==0) continue; printf("%3d",i); } getch(); }
Output: 1 3 5 7 9

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 Prime numbers between 1 and 30 : 2 3 5 7 11 13 17 19 23 29

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, display teenage */ main() { int age; clrscr(); printf(Enter age ); scanf(%d,&age); if(age>=13 && age<=19) printf(\nTeen age); else printf(\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 ); else printf(\nResult is FAIL); getch(); }

Output Enter age 16 Teen age

Output Enter marks in two subjects 60 30 Result is PASS

Program 48: /* Accept two numbers n1,n2. If n1 < n2 and if n1 is even number then display natural numbers from n1 to n2 */ main() { int n1,n2,count; Output clrscr(); Enter any two numbers 4 printf(\n Enter any two numbers ); 9 4 5 6 7 8 9 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 digit

in 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 n numbers. 4. Accept a number and find whether it is Prime or not. ( Prime number : The number with two factors only and which can 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

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 3 Input is 5 --> Output is 11 5th prime no. is 11)

7. Write a program to display the given format.


1 2 3 4 5 2 3 4 5

3 4 5

4 5

8. Write a program to display the given format.


0 2 2 2 2 1 0 2 2 2 1 1 0 2 2 1 1 1 0 2 1 1 1 1 0

9. Write a program to display the give format.


1 2 3 1 1 1 1 1 2 2 2 1 2 3 3

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.e the number which is neither big nor small.

Arrays Array is a collection of similar elements (Homogenous elements) stored in adjacent memory locations sharing a common name. Array is represented by a variable called subscripted variable. The variable is always represented by its subscript which is the index number of the element. Every element in an array is identified by the index. The index starts from 0 . Hence the index of first element is 0 and last element is size - 1. The elements of array are always stored in contiguous memory locations. Hence it is sequential data structure. Before using an array its type and size must be declared. An array 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};

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 single dimensional array. int a[5]; 'a' is a single dimensional array. Double dimensional array: An array with two subscripted values is called a double dimensional 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 a 0 1 2 3 4

In the above example 'a' is an array of 5 single dimensional arrays each of size 3. Multidimensional arrays: An array with multiple subscripted values is called a multi dimensional 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}; Output int i; The elements of a : clrscr(); 10 20 30 /* Printing the array elements */ The elements of b : printf("\n The elements of a :\n\n"); 100 200 300 400 for(i=0;i<3;i++) 500 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 */

main() { Output int a[3], i; The elements of a : 10 20 30 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; Output clrscr(); Enter size of array below 10 : printf("\n Enter size of array below 10 : "); 4 Enter 4 elements : scanf("%d",&n); 30 printf("\n Enter %d elements :\n\n ",n);90 50 80 The elements of a : for(i=0;i<n;i++) 30 90 50 80 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 Enter 5 elements : 40 20 90 60 50 The elements from last to first : 50 60 90 20 40

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() Output { Enter size of array : 4 int a[15],n,i,sum; Enter element 1 : 23 clrscr(); Enter element 2 : 45 printf("\n Enter size of array : "); Enter element 3 : 56 Enter element 4 : 67 scanf("%d",&n); for(i=0;i<n;i++) The elements of the array : { 23 45 56 67 printf("\n Enter element %d : ",i+1); of elements of array : Sum scanf("%d",&a[i]); 191 } 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 and odd numbers */

main() Output { Enter size of array : 4 int a[15], n, even, odd, i; Enter element 1 : 34 clrscr(); Enter element 2 : 55 Enter element 3 : 17 printf("\n Enter size of array : "); Enter element 4 : 26 scanf("%d",&n); for(i=0;i<n;i++) Even sum : 60 { printf("\n Enter element %d : ",i+1); sum : 72 Odd 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();

Output

Enter 4 elements : 20 40 10 30 printf("\n Enter 4 elements :\n\n "); The elements of the array : for(i=0;i<4;i++) 20 40 10 30 100

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 and copy all these elements into another array */

main() { int a[5],b[5],i; clrscr();

Output Enter 5 elements : 20 40 30 80 10 The elements of a : 20 40 30 80 10 The elements of b : printf("\n Enter 5 elements :\n\n "); 20 40 30 80 10

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 and copy all these elements into another array in reverse order */ main() { Output int a[5],b[5],i; Enter 5 elements : 30 10 20 60 50 clrscr(); printf("\n Enter 5 elements :\n\n "); The elements of a : 30 10 20 60 50 for(i=0;i<5;i++) The elements of b : scanf("%d",&a[i]); 50 60 20 10 30 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:

/* Accept n elements into an array and reverse its contents with out using any temporary array */ Output main() Enter no. of elements : 4 { Enter 4 elements : int a[15],n,i,t; 40 20 80 60 clrscr(); The elements before reversing printf("\n Enter no. of elements : "); a : scanf("%d",&n); 40 20 80 60 The printf("\n Enter %d elements :\n\n ",n); elements after reversing 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 */

Output The Fibonacci series : 0 1 1 2 3 5 21 34

8 13

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++) Output scanf("%d",&a[i]);

Enter elements of array a : :\n\n "); printf("\n Enter 5 elements of array b 10 40 70 60 30 for(i=0;i<5;i++) Enter elements of array scanf("%d",&b[i]); b: 15 75 25 35 55 The elements of array c : for(i=0;i<5;i++) 25 115 95 95 85 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() { Output int a[5],i,j,t; Enter 5 values : 40 20 10 90 clrscr(); 60 Sorted values printf("\n Enter 5 values : "); 10 20 40 60 90 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]);

getch(); } Program 62: /* Bubble Sorting Arrange the values of array in ascending order */ main() { Output int a[5],i,j,t; Enter 5 values 40 10 20 90 clrscr(); 60 printf("\n Enter 5 values "); Sorted values for(i=0;i<5;i++) 10 20 40 60 90 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() { Output Elements int a[2][3] = { {10,20,30}, {40,50,60} }; of a : int b[3][2] = { 10,20,30,40,50,60 }; 10 20 30 40 50 60 int c[2][2]; Elements of b : c[0][0] = 10; c[0][1] = 20; 10 20 c[1][0] = 30; c[1][1] = 40; 30 40 clrscr(); 50 60 Elements of c : printf("\n\n Elements of a :\n"); 10 20 printf("\n%3d%3d%3d",a[0][0],a[0][1],a[0][2]); 30 40 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]);

printf("\n%3d%3d",c[1][0],c[1][1]); getch(); } Program 64: /* Accept elements into 3x3 2D array and display the same */ main() { Output int a[3][3],i,j; Enter elements of A : Enter element (1,1) : clrscr(); printf("\n Enter elements of A :\n"); 12 Enter element (1,2) : for(i=0;i<3;i++) 23 for(j=0;j<3;j++) Enter element (1,3) : { 34 printf("\n Enter element (%d,%d) : ",i+1,j+1); (2,1) : Enter element 45 scanf("%d",&a[i][j]); Enter element (2,2) : } 56 printf("\n\n Elements of A :\n\n"); Enter element (2,3) : for(i=0;i<3;i++) 67 { Enter element (3,1) : for(j=0;j<3;j++) 78 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]); Output }

Enter elements of A : Enter element (1,1) : 12 printf("\n\n The elements of A along Enter element (1,2) : 23 with row sum :\n\n"); Enter element (1,3) : 34 for(i=0;i<3;i++) Enter element (2,1) : 45 Enter element (2,2) : 56 Enter element (2,3) : 67 Enter element (3,1) : 78 Enter element (3,2) : 89 Enter element (3,3) : 90 The elements of A along with row sum : 12 23 34 69 45 56 67 168 78 89 90 257

{ 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 row Store the column sum into last row i.e., 4th row of each column Store 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) :

Output Enter elements of A : Enter element (1,1) : 12 Enter element (1,2) : 23 Enter element (1,3) : 34 Enter element (2,1) : 45 Enter element (2,2) : 56 Enter element ",i+1,j+1); (2,3) : 67 Enter element (3,1) : 78 Enter element (3,2) : 89 Enter element (3,3) : 90 The elements of A along with row,column, diagonal sum : 12 23 34 69 45 56 67 168 78 89 90 257

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++) Output for(j=0;j<3;j++) Enter elements of A : Enter element (1,1) : { 12 printf("\n Enter element (%d,%d) : ",i+1,j+1); Enter element (1,2) : scanf("%d",&a[i][j]); 23 } Enter element (1,3) :
34 Enter 45 Enter 56 Enter 67 Enter 78 Enter 89 Enter element (2,1) : element (2,2) : element (2,3) : element (3,1) : element (3,2) : element (3,3) :

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 digit numbers Accept values into double dimension array of 3 x 3. Sort the entire array. Accept values into double dimension array and transpose them i.e change 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 are constructed using character arrays. The procedure of declaring character array is almost like other data types such as integer and floats. Syntax : Char array_name[size];

Example : char name[20]; char line[80]; The basic structure of character arrays is as follows char name[7] = PREM; name P R E M \0 0 1 2 3

Character string always ends with NULL character i.e \0. Program 68: /* Example on string declaration */ Output: main() The string a is : Infotech { The string b is : Computers 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; Output: char a[10]; Enter a single character : I clrscr(); The printf("\n Enter a single character : "); character is : I scanf("%c",&ch); Enter a name : prem printf("\n The character is : %c",ch); The name is : prem 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;

char sna[20]; clrscr(); printf("\n Enter student number : "); Output: scanf("%d",&sno); printf("\n Enter student name : "); Enter student number : 1 Enter student name : prem scanf("%s",sna); Enter marks in 3 sub : 67 78 printf("\n Enter marks in 3 sub : "); 89 scanf("%d%d%d",&m1,&m2,&m3); Number : 1 tot = m1+m2+m3; Name : prem printf("\n Number : %d",sno); Total : 234 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 a sentence : Infotech Computer Centre The sentence is Infotech Computer

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() Output: { Enter a character : I The character is : I 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() */ Press any key : U have pressed I main() { Press another key : char ch; A clrscr(); U have pressed A 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:

/* Finding length of string */ /* Every string is terminated by NULL character i.e., '\0' */ main() { Output: char a[20]; Enter a string : INFOTECH int l; The length of string is : clrscr(); 8 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(); }

Output: Enter a string : INFOTECH Length of a is : 8

Program 76:

/* 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(); }
Output: Enter a string : INFOTECH The string a is : INFOTECH The string b is : INFOTECH Output: Enter a string : INFOTECH The new string is : INFOTECH

Program 78:

/* Example on reversing a string without using other temporary string */ main() { Output: int i,l; Enter a string : char a[20], ch; INFOTECH clrscr(); The reverse of a is puts("Enter a string :"); : gets(a); HCETOFNI /* 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 : INFOTECH Reverse of a is : HCETOFNI

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() Output: { Enter string a : INFO char a[20],b[20]; Enter string b : clrscr(); TECH puts("Enter string a :"); gets(a); String a is : INFOTECH puts("Enter string b :"); String b is : TECH 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 is the same as s2. > 0 if s1 is greater than s2. Program 81: /* Example on strcmp() - To compare two accepted strings */ #include <string.h> main() { Output: char a[20],b[20]; Enter string a : int res; INFO clrscr(); Enter string b : puts("Enter string a :"); TECH gets(a); The 2 strings are puts("Enter string b :"); unequal gets(b); res = strcmp(a,b); if(res == 0) printf("\nThe 2 strings are equal."); else printf("\nThe 2 strings are unequal.");

getch(); } Program 82: /* Accept a string from key board. Find whether it is palindrome or not */ #include <string.h> main() Output: { Enter a string : char a[20],b[20]; MALAYALAM int res; clrscr(); The string is puts("Enter a string :"); palindrome. gets(a); strcpy(b,a); strrev(b); res = strcmp(a,b); if(res == 0) printf("\nThe string is palindrome."); else printf("\nThe string is not palindrome."); getch(); } ASCII : It stands for American Standard Code for Information Interchange There are 0 to 255 ASCII characters. It is developed by ANSI (American National Standard Institution). Every character is having its corresponding ASCII number. Example : A to Z - 65 to 90 a to z - 97 to 122 0 to 9 - 48 to 57 Blank - 32 Program 83: /* Printing ASCII chart - 0 to 255 */ Output main() { int i; clrscr(); for(i=0;i<=255;i++) printf("%d %c ",i,i);
0 1 2 3 4 5 6 7 8 9 10 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30

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() Output { Enter a string : int i; INFOTECH COMPUTER CENTRE 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);
Lower case string is : infotech computer center

Output

Enter a string : INFOTECH COMPUTER CENTRE Number of blank spaces : 2 Number of words : 3

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(); } Output
Enter a string : infotech computer centre Title case string : Infotech Computer

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') { 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++; } }

|| (a[i]>='a' && a[i]<='z')) Output


Enter a string : Infotech Computer Centre 2007! Number Number Number Number of of of of blanks : 3 digits : 4 vowels : 8 consonants : 14

else ns++; } printf("\nNumber printf("\nNumber printf("\nNumber printf("\nNumber printf("\nNumber getch(); } Program 88:

of of of of of

blanks : %d",nb); digits : %d",nd); vowels : %d",nv); consonants : %d",nc); special characters : %d",ns);

/* 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; else a[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() Output
Enter name 1 : info Enter name 2 : tech Enter name 3 : prem Enter name 4 : kumar Enter name 5 : srinu The names are : info tech

Output

Enter a string : INFOTECH COMPUTERS The encoded string : NSKTYJHM%HTRUZYJWX

{ 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 consonants present in it. Example : Accepted string : INFOTECH new string : NFTCH Accept any string and display its abbreviation. Example : Accepted string : Andhra Pradesh State Road Transport Corporation. Abbriviation : APRTC Accept any sentence and display all palindrome words present in it. 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 alphabetical order.

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 header files. There are 29 header files with approximately 400 functions. Header files contains predefined functions, global variables. They are with file extension .h Header files are not compiled separately. The header files can be included 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 files built in header files user defined header files Built in header files are as follows alloc.h dir.h assert.h dos.h bios.h errno.h conio.h fcntl.h ctype.h float.h

graphics.h math.h stddef.h sys\types. h

io.h setjmp.h stdio.h sys\timeb. h

limits.h share.h stdlib.h time.h

mem.h signal.h string.h values.h

process.h stdarg.h sys\stat.h

alloc.h : Memory allocation built in functions are available in header file alloc.h Functions are as follows. calloc malloc free

assert.h : To test conditions and take action i.e program diagnostics Functions are as follows. assert bios.h : Functions related to basic input output operations related to bios Functions are as follows. bioscom biosequip biosmemory biostime biosdisk bioskey biosprint

conio.h : Functions related to console input output operations Functions are as follows clreol getch gotoxy getche clrscr putch cprintf puttext cputs gettext window kbhit Textbackgrou nd

wherex textcolo wherey textmod r e

ctype.h: Functions related to character type identification. Functions are as follows isspac isalnu isupper e m isxdigit iscntrl toascii isdigit tolowe islower isprint toupper r isacii isalpha isgraph ispunct

dir.h : Functions related to directories, subdirectories and disk operations Functions are as follows chdir getdisk findfirst findnex mktemp fnmerge t fnsplit searchpath getcurdir getcwd mkdir rmdir setdisk

dos.h : Functions related to disk operating system and interrupt programming. Functions are as follows. graphics.h : Functions related to graphical programs. Functions are as follows bar circle floodfill cleardevice bar3d getarccoor ds getbkcolor getaspectra tio getcolor

learviewpo rt closegraph getdefaultpa detectgrap lette h getfillpatter ellipse getfillsettin n gs fillpoly getimage getlinesetti ngs getx getmaxmod gety e getmaxy grapherrorm getmodena sg me rectangle getpalette graphresult getpixel registerbgi driver moverel outtextxy setcolor setgraphbu fsize setvisualpa ge

getdriverna drawpoly me fillellipse Getgraphm ode Getviewset getmaxcolo tings r getmaxx Graphdefau lts getmodera Installuserf nge ont getpalettes Imagesize ize initgraph gettextsetti installuserd Line ngs river linerel registerbgif lineto Restorecrt ont mode sector moveto outtext Setallpalett e setaspectrati pieslice setbkcolor Putimage o putpixel setfillpatter setfillstyle settextstyle n Setuserchars setgraphm setviewport setlinestyle ize ode setpalette setwritemo setrgbcolor textheight de

setrgbpalet te

textwidth

settextjusti fy

io.h : The functions related with general input output operations. Functions are as follows limits.h : Functions or constants related with checking the limits of data types. They are as follows math.h : Functions related to mathematical calculations They are as follows abs atan cabs matherr pow10 floor hypot log cosh sqrt acos atan2 ceil modf sin fmod labs log10 exp tan asin atof cos poly sinh frexp ldexp fabs Pow 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, in multi user environment signal.h : Functions related with signal sending or receiving. stdarg.h : Functions related with standard argument list stddef.h : definitions. Functions or constants related with Standard

stdio.h : The functions related with standard input output operations. The functions are as follows. clearerr fdopen fflush fgetpos flushall fputc fread fseek fclose feof fgetc fgets fopen fputchar freopen fsetpos fcloseall ferror fgetchar fileno fprintf fputs fscanf ftell

putw rewind setvbuf puts ungetc

fwrite gets printf strerror vscanf

remove scanf sprintf tmpfile unlink

getc getw putc vfscanf vsprintf

rename setbuf sscanf tmpnam vfprintf

Getcha r perror putcha r vprintf vsscan f

stdlib.h : Functions frequently used are available in standard library.

string.h : Functions related with string manipulations. They are as follows memccp strchr y memcpy strcpy memset strlen strrev strstr moveda ta stpcpy memchr strcmp memicm strcspn p strerror movmem strlwr strcat strncpy strupr memcmp memmov e stricmp strncat strspn strrchr strcmpi strdup setme m strncm p strnicm p

strncmpi strset strnset strtok

sys \ stat.h : Functions related with file status bits and stat structure time.h : Time manipulating functions are available in this header file. sys\timeb.h: Functions to store the current system time. values.h: Defines UNIX compatible constants for limits to float and double values. Functions or constants are as follows. Progarms on <math.h> header file Program 90: /* abs() - Returns absolute value */
Output abs(-5) = 5

# include <math.h> main() { clrscr(); printf("abs(-5) = %d",abs(-5)); getch(); } Program 91: /* acos() - Returns arc cos value asin() - Returns arc sin value atan() - 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 value floor() Lower integer of the real value */ Output # include <math.h> ceil(7.2) = 8.000000 main() floor(7.2) = 7.000000 { 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 value pow() - returns power of number sqrt() - returns square root of number */ Output # include <math.h> main() { clrscr();
Output acos(1) = 0.000000 asin(1) = 1.570796 atan(1) = 0.785398

exp(5) = 148.413159 pow(5.0,3.0) = 125.000000 sqrt(625.0) = 25.000000

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> Output main() Enter character I It is alphanumeric { character char ch; clrscr(); printf("Enter character "); ch=getchar(); if(isalnum(ch)>0) printf("It is alphanumeric character "); else printf("It is special character"); getch(); } Program 95: /* isalpha() - Returns 1 if alphabet isdigit() - Returns 1 if digit iscntrl() - Returns 1 if control character islower() - Returns 1 if lower case character isupper() - Returns 1 if upper case character */ # include <ctype.h> # include <stdio.h> Output main() Enter character I { It is alphabetic char ch; character clrscr(); It is upper case printf("Enter character "); character ch=getchar(); if(isalpha(ch)>0) printf("It is alphabetic character \n"); else if(isdigit(ch)>0) printf("It is Numeric character \n"); else printf("It is special character \n"); if(islower(ch))

printf("It is lower case character \n"); else if(isupper(ch)) printf("It is upper case character"); getch(); } Program 96: /* ispunct() - Returns 1 if puctuation isspace() - Returns 1 if space */ Output # include <ctype.h> Enter character ; # include <stdio.h> It is punctuation main() character { char ch; clrscr(); printf("Enter character "); ch=getchar(); if(ispunct(ch)>0) printf("It is punctuation character \n"); else if(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 with required file name but with file extension .h. Develop a file with any file name and with extension .h. Write global variables and functions in it. Save it. Example : MyFun.h Now open another file where we write the main() function. Include the 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
Output x=5 Welcome to INFOTECH

/* 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 specific task. When a program is lengthy, it is advised to divide the program into smaller units (routines) called functions. When a set of statements are to be executed frequently, then those statements are written as separate programming unit called function. 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 lever logic

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 in header 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 function which does not return any value is called void function. Before using a function, its prototype must be specified. This is called function declaration. Function prototype is also called signature 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 write the 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 be invoked in the program by including the header file.

We can send parameters to functions. Arguments written in the program while calling the function are called "actual parameters" and the arguments used in the function are called "formal parameters". The values of actual parameters are received by the formal parameters (receiving parameters)

The number of actual parameters should be equal to the number of formal parameters and their corresponding data types should match. 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 formal parameter. If the value of formal parameter is changed, it will not affect the corresponding values of actual parameter. This implies that the formal and actual parameters maintain separate memory locations to hold data. In Call by Reference, the address of actual parameter is passed to formal. This implies that the formal and actual parameters refers to the same memory location. If the value of formal parameter is changed, it affects the corresponding actual parameter. This happens 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 , it assumes int.

Program 98: /* Example on void functions */

main() { void show(); /* prototype */ clrscr(); show(); getch(); } /* The function show */ void show() { printf("\n Welcome to Infotech."); } Program 99:

Output

Welcome to Infotech

/* 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); }

Output Enter 2 numbers : 5 2 Sum of 2 numbers :

Program 100: /* Example on function returning a value*/

main() Output { Enter 2 numbers : 5 int a,b,c; 2 int sum(int , int ); Sum of 2 numbers : 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 : 5 2 Sum is 7

/* Example on multiple functions */ main() { int a,b,r1,r2,r3; Output float r4; Enter 2 numbers : 10 int sum(int,int), diff(int,int), mul(int,int); 5 float div(int,int); Sum = 15 clrscr(); Difference = 5 Product = 50 printf("\n Enter 2 numbers : "); Division = 2.000000 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:

/* Example on function calling another function */ main() { int a,b,c; Output int sum(int,int); Enter 2 numbers : 10 5 clrscr(); Product is : 50 printf("\n Enter 2 numbers : "); Sum is : 15 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; Output int fact(int ); Enter a number : 5 clrscr(); Factorial of 5 = printf("\n Enter a number : "); 120 scanf("%d",&a); res = fact(a); printf("\n Factorial of %d = %d",a,res); getch(); }

/* 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() Output { Enter values for n,r : 5 2 int n,r,res; The binomial co-efficient = 10 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 */ Output main() Enter 2 numbers : 5 10 { The values in function : int a,b; x = 105 y = 110 void change(int , int ); The values after function call clrscr(); : printf("\n Enter 2 numbers : "); a = 5 b = 10 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);

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() { Output int a,b; Enter 2 numbers : 5 10 void change(int *, int *); clrscr(); The values in function : printf("\n Enter 2 numbers : "); x = 105 y = 110 scanf("%d%d",&a,&b); The values after function call : change(&a,&b); /* & refers to address */ = 105 b = 110 printf("\n\n The values after functiona 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; Output int sum(int ); Enter a number : 487 clrscr(); Single digit sum of 487 = printf("\n Enter a number : "); 1 scanf("%d",&a); s = a; while(s>9) { s = sum(s);

} 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 */
Output main() Enter 5 elements : { 5 6 7 8 9 int a[5],i; void change(int []); The array elements in function : 15 16 17 18 19 clrscr(); The "); printf("\n Enter 5 elements :\n\narray elements after function call : for(i=0;i<5;i++) 15 16 17 18 19 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]); }

Note: Using passing by address, implicitly we can return more values .

Program 110: /* Example on passing 2D array as parameter - Call by reference */ /* Sorting strings */ #include <string.h> main() Output { Enter number of strings : int n; 5 Enter 5 names : char a[10][10]; void input(char [10][10], int ); Enter name 1 : prem Enter name 2 : srinu void sort(char [10][10], int ); Enter name 3 : kumar void output(char [10][10], int ); Enter name 4 : vasu clrscr(); Enter name 5 : info printf("\n Enter number of strings : "); The sorted names : scanf("%d",&n); info printf("\n Enter %d names :\n",n); kumar input(a,n); prem sort(a,n); srinu printf("\n The sorted names :\n"); vasu 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;

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() Output { Enter a number : 4 int a,res; Factorial of 4 = int fact(int ); 24 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; else return (x * fact(x-1)); } Program 112: /* Example on recursion */ /* Finding sum of first n natural numbers */

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; else return (no + sum(no-1)); } Exercise:

Output Enter a number : 5 Sum = 15

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 same as 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 arrays of 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.

STORAGE CLASSES The scope of variable refers to how widely it is known among a set of functions in a program. Every identifier optionally has a storage class that provides information about its visibility, lifetime and 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 the control leaves the block.The local variables of a function are often referred as automatic variables. The default storage class is auto. Memory is automatically allocated when ever a variable is declared to particular storage class. Automatic variables can be declared not only at the beginning of function but also at the beginning of a compound statement. Syntax : auto <data type> <variables> The declaration int a,b; is exactly same as auto 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 garbage

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); Output int i=100; i=300 in inner most block clrscr(); i=2000 (parameter of infotech(200); function) printf("i=%d in function main\n",i); i=100 in function main 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 variables are stored in CPUs registers. Register variables are faster in execution as they are part and parcel of processor. The variables frequently used for processing can be declared as register variables. Syntax:

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 same scope of rules of automatic variables but in this case the contents of the variables will be retained throughout the program. The static variables are initialized to zero by default. They are initialized 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
Output a= 0 a= 1 a= 2 Output 0 1 2 3 4

x= x= x=

50 50 50

x = %5d\n",a,x);

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 elsewhere in the program, but can be used in the current block. External variables are declared out of main function. They resemble the global 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() {
Output We are in main We are in static fun

Output a= 0 b=0 Inside function a= 0 b=0

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 type because a structure variable can hold multiple values. Structure contains multiple fields, each of which is called as member of structure. Some times the member of structure can be a structure variable. That is structures can be nested. Arrays can be used inside the structure as members and arrays can be created using structures that is array of structures. Structures help to organize the complex data in a more meaningful way. They increase the speed of program execution as the memory allocated for the members of structure is in sequential memory locations. Structures are convenient to handle the logically related data items. This provides the packing of data as a unit. Syntax: struct [<structure name>] { <members of structure> }; Note : Naming the structure is optional.

Program 119: /* Example on Structure global declaration The structure student */ struct student { int sno,tot; char sna[20]; }; /* The main program */ main() { Output struct student s; Enter student number : 1 clrscr(); Enter student name : prem printf("\n Enter student number : ");Enter total marks : 800 scanf("%d",&s.sno); printf("\n Enter student name : "); Student details : Number : 1 scanf("%s",s.sna); Name : prem printf("\n Enter total marks : "); Total : 800 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 ship operator. Program 120: /* Example on structure with local declaration Structure 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 : ");

Output Enter employee number : Enter name : PREM Enter salary : 10000

: Number : 1 ");
Name Salary HRA DA TAX

Employee details : : PREM : 10000.000000 : 1200.000000 : 1000.000000 : 500.000000

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 printf("\n printf("\n printf("\n printf("\n printf("\n printf("\n printf("\n getch(); } Employee details :\n"); Number : %d",e.eno); Name : %s",e.ena); Salary : %f",e.sal); HRA : %f",hra); DA : %f",da); TAX : %f",tax); Net sal : %f",nsal);

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();
Output Enter number of students below 10 : 2 Enter details of student 1 : Enter number : 1 Enter name : prem Enter total : 800 Enter details of student 2 : Enter name : srinu Enter total : 900 Student details : Number : 1 Name : prem Total : 800 Number : 2 Name : srinu Total : 900

Enter number printf("\n Enter number of students below 10 : "); : 2

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; };

Output Enter student number, name, total : 1 PREM 900 Enter house number, street name : 57 BhagyaNagar Student details : Number : 1 Name : PREM Total : 900 House no : 57

/* 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 printf("\n printf("\n printf("\n printf("\n printf("\n getch(); } Student details :\n"); Number : %d",S.sno); Name : %s",S.sna); Total : %d",S.tot); House no : %d",S.A.hno); Street : %s",S.A.strna);

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;

Output Enter student number, name, total : 1 Srinivas 900 Enter house number, street : 20 MaddurNagar Number : 1 Name : Srinivas Total : 900 HNo : 20 Street : MaddurNagar

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 printf("\n printf("\n printf("\n printf("\n getch(); } Number : %d",S.sno); Name : %s",S.sna); Total : %d",S.tot); HNo : %d",S.A.hno); Street : %s",S.A.strna);

Assigning structure variables : Assigning structure variables of similar structure is possible but the structure variables belonging to different structures is not possible. In this case the structure member of one structure can be assigned to another structure.

Program 124: /* Assigning structure variables */ /* The structure student */ Output struct student { Enter Student number, name, int sno,tot; total : char sna[10]; 1 PREM 900 }; /* The main program */ main() { struct student S1, S2;
The student details : Number : 1 Name : PREM Total : 900

clrscr(); printf("\n Enter Student number, name, total :\n "); scanf("%d%s%d",&S1.sno,S1.sna,&S1.tot); S2 = S1; printf("\n printf("\n printf("\n printf("\n getch(); } Program 125: #include <string.h> /* Assigning structure variables */ Output: /* The structure student1 */ Enter Student number, name, struct student1 total : 1 PREM 900 { The student details : int sno,tot; Number : 1 char sna[10]; Name : PREM };
Total : 900

The student details :\n"); Number : %d",S2.sno); Name : %s",S2.sna); Total : %d",S2.tot);

/* 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; */

S2.sno = S1.sno; strcpy(S2.sna, S1.sna); S2.tot = S1.tot; printf("\n printf("\n printf("\n printf("\n getch(); } Program 126: /* Passing structure as parameter to function */ /* Call by value */ /* The structure test */ Output 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(); }
Structure values in function : a = 20 b = 30 Structure values after function change : a = 10 b = 20

The student details :\n"); Number : %d",S2.sno); Name : %s",S2.sna); Total : %d",S2.tot);

/* 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:

/* 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 memory location, where as in unions all the union members share common memory location. Unions allocate memory for the member with largest data type in which the values of other members can be stored. Ultimately, the value of only one member can be stored in

Output Structure values in function : a = 20 b = 30 Structure values after function change : a = 20 b = 30

union identified. Unions can be nested. Apart from primitive data types, 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; };

Memory allocation diagram


X 1000 1001 1002 1003

4 bytes of memory int a 2 bytes can be stored in 4 bytes float b- 4 bytes can be stored in 4

Output a = -26739 b = 0.000000 c= d = 1.234500

/* The main program */ main() size of T = 8 { 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 assigned item is available from union variable T. structure within union Program 129:

/* Example on structure within union*/ main() { struct date { int day,month,year; Output }; X.i = 22 union value X.f = 0.000000 { Structure : int i; 20 - 3 2007 float f; Size of union 6 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 used to declare user defined data types. Enumeration is a set of values represented by user defined constants called enumeration constants.

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 to prem, 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 };

Output 0 1 2 3

main() { enum courses i; clrscr(); for(i=java;i<=msoffice;i++)

printf("%d ",i); getch(); } Program 131: /* example on enumaration */ enum StaffCode{prem=101,srinu=201,sunil=301,rajasekhar=401}; main() { Output enum StaffCode code; Enter staff code clrscr(); 101/201/301/401 201 printf("Enter staff code 101/201/301/401 "); Srinu got experience of 16 years scanf("%d",&code); if (code==prem) printf("Prem got experience of 15 years "); else if (code==srinu) printf("Srinu got experience of 16 years "); else if(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 per programmers convenience. # define We can define our own constants in program. These constants may appear repeatedly in our program. The macro definitions are also called pre processors because before processing, the constants are replaced by respective values by pre processors. These programs increase readability, understandability and modifiability of program. Even we can design new programming language with # define statements. Syntax # define <symbolic-name> <value of constant> Example # define Max 100 # define PI 3.14159

Program 132: /* # # # # Example on # define */ define min 101 define max 105 define inc i++ define display printf("%5d",i) Output
101 102 103 104 105

main() { int i; clrscr(); for(i=min; i<=max; inc) display; getch(); }

Type def : This allows user to define an identifier that would represent an existing data type. The user defined data type identifier 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; Output
Enter student name PREM Enter marks in 3 subjects 70 80 90

main() { Student name PREM string name[20]; Marks are 70 80 90 marks m1,m2,m3,total; Total is 240 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();

} Command Line Arguments In these programs, arguments are supplied to the program as parameters from the command prompt at the time of program execution. When C program is compiled, an executable file will be created with file extension .exe. This file can be executed from command prompt with out loading C software or compiler. The arguments passed from the command prompt will be taken by the 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 character type pointer array. The 0th cell of argv array always contains the program name as its value. Example main(int argc, char *argv[]) { <statements> } Program 134: /* Example on command line arguments D:\>CMDEX prem srinu info 1.Save the program with name CMDEX .C tech 2. compile the program and make Exe */ main(int argc,char *argv[]) { int i; clrscr(); printf("Total number of arguments printf("\nThe arguments are \n"); for(i=0;i<argc;i++) printf("\n%s",argv[i]); getch(); } Exercise Output
Total number of arguments 5 The arguments are

%d",argc); D:\CMDEX.EXE
prem srinu info tech

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 memory location where the data is stored. The pointer is a powerful technique to access the data by indirect reference because it holds the address of that variable where it has been stored in the memory. The power of C lies in pointers. This is because of two resigns. powerful memory manage techniques are with pointers. The dynamic memory allocation and deallocation can be done with pointer programs. The memory can be released if not necessary. Speed of program execution increases because the pointer programs maintains addresses of memory locations. Pointers are called Dynamic variables. A dynamic variable can be created or disposed at any time during the program execution. The binding of a dynamic variable is done at runtime. Binding means allocating memory to a variable. All normal variables get their memory allocation at compile time. This is known as early binding or static binding. But pointers get their memory allocation at runtime as per the request. This is known as Late binding or dynamic binding. The pointer variable consists of two parts such as the pointer operator and the address operator Pointer operator : A pointer operator can be represented by the 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 an integer data type. The following declarations are all valid declarations

float *fptr; double *dptr; char *cptr; Address operator: An address operator can be represented by the combination of &(ampersand) with a pointer variable. Example: m = &ptr; Note that the pointer operator & will return the address of the variable following it. So in the above example m receives the address of ptr but not its value.

Pointer Expressions The general rule to assign a value to pointer is same as any other variable data type. Example: int x=100; int *ptr; ptr = &x; In the above example the address of x is assigned to pointer variable 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();
Output Value of a : 5 Address of a : 65504 Value of a : 5

/* 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(); }

In the above example &a will return the address of normal variable a. *(&a) :- &a will represent the address of memory location a and * preceding it indicated the content of memory location. That is data 5. Programs on normal variables and pointer variables Program 136: /* Pointer variable getting address of normal variable */ void main() { Output int a, *b; 50 50 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 is assigned to pointer variable b by the statement b = &a Program 137: /* Assigning address of one pointer variable to 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 address referred by b is given to pointer variable c.
Output 50 50 50

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;

Output 50 50 50 50

/* 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;

Output 150 75 50 150 50

printf("%5d%5d%5d%5d%5d",a,b,c,*d,*e); getch(); } malloc() : Allocates memory of specified size dynamically by the request made at runtime from heap memory. Prototype in alloc.h, stdlib.h

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 which denotes the integer pointer. Program 141: /* Example on malloc - scanf */ void main() Output { Enter a number : 50 int *a,b; clrscr(); 50 50 a = (int *) malloc (sizeof(int)); printf("\n Enter a number : "); scanf("%d",a); /* in the above input & is ignored before variable a because it is already 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. Output
50 50

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 content of pointer variables a and b is stored as content of pointer variable c

Output Enter 2 numbers : 50 25 Sum is 75

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 10 20 30 40 50 10 20 30 40 50 10 20 30 40 50 10 20 11

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 array element can be represent as a[ i] or i[a]. Pointer arithmetic : In general the variable are incremented and decremented. The mathematical expressions are constructed with of variables. Apart from that C supports pointer arithmetic. As per this, the address can be incremented or decremented. No other operations like multiplications and divisions can be performed with addresses. These are best used with Arrays.

Programs on Pointer Arithmetic Program 144: /* Example on pointer arithmetics */ main() { Output int a[3] = {10,20,30}; The array int *b; elements : int i; clrscr(); 10 20 30 b = a; printf("\n The array elements :\n\n"); for(i=0;i<3;i++) { printf("%d ",*b); b++;

} getch(); } In the above example by the statement b=a; the address of 0 th cell of array a is assigned to b. In for looping structure the statement b++; denotes the address incrementation. By this the pointer variable b will be pointing to different elements of array in different iterations of for loop. Program 145: /* Creating array using malloc() */ main() { int *a, n, i; clrscr(); printf("\n Enter size of the array : "); Output scanf("%d",&n); Enter size of the array : 4 a = (int *) malloc (sizeof(int) * n); printf("\n Enter %d elements :\n ",n); Enter 4 elements : 10 20 30 40 for(i=0;i<n;i++) scanf("%d",(a+i)); The array elements : printf("\n The array elements :\n"); 10 20 30 40 for(i=0;i<n;i++) The array elements : printf("%5d",*(a+i)); 10 20 30 40 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)*n will allocate memory for required number of elements, each of size two 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();

Output The array elements : 10 20 30 40 50

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 statement printf("%5d",*a); a++; */ printf("%5d",*p); p++; } getch(); } Programs on Pointer to Pointer Program 147: /* Pointer to a pointer */ main() Output { 50 50 50 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 is given to pointer variable b and by the statement c=&b, the address 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
Enter a number : 50 The number is : 50

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 which address 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); Output Enter number of rows and columns : for(i=0; i<r; i++) a[i] = (int *) malloc (sizeof(int) * 3 3 c); printf("\n Enter %d elements :\n ",(r*c)); Enter 9 elements : for(i=0; i<r; i++) 10 20 30 40 50 60 70 80 90 for(j=0; j<c; j++) scanf("%d",(*(a+i)+j)); The elements of array : 10 20 printf("\n The elements of array :\n\n"); 30 for(i=0;i<r;i++) 40 50 60 { for(j=0;j<c;j++) 70 80 90 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;

Output
a = 10

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 which internally contains a pointer member *a. The memory is allocated to the pointer member with the statement T.a = (int *) malloc (sizeof(int));. The statement *T.a = 10; is used to assign value to pointer member of structure. Program 152: /* Example on structure pointer and structure with pointer variable */ struct test { int *a; }*T; Output
a = 10

Output
a = 10

/* 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)); is used 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() Output { Enter a number : int *a; 50 clrscr(); a = (int *) malloc (sizeof(int)); The number is : 50 printf("\n Enter a number : "); Memory scanf("%d",a); printf("\n The number is : %d",*a); deallocated. 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:

/* 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 can take integer as parameter. The statement ptr = sum; makes the function pointer ptr to point to the function sum. The statement s = (*ptr)(3); call the function sum by passing the parameter 3 which is received by the formal parameter x.

Output

Sum = 6 Sum = 6

Program 155:

/* 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 : 10 20 Result is : 30 Result is : 30 Result is : 30

Files File programs are used to store the data permanently on secondary storage devices and access it when required. The data stored on secondary storage is permanent. File programs are generally used to do data transactions in large volume. Buffers are used to access data files. A Buffer is memory area that is reserved for any input/output device. There are some standard buffers for keyboard, monitor ,printer etc., For disk files we need to create our own buffers. That is done in C language by a struct type called FILE. FILE *pointer; The *pointer is called a buffer or stream. C language data files are also called as stream data files. A stream is a continuous flow of data where we can write into or read from any number of characters. File is the place on the secondary media where a group of related data is stored. The programs related with files are 1. Data creation program 2. Appending program 3. Processing program Data creation program: The program which is used to store the data into disk is called data creation program. Appending program: The program which is used to add new data for the existing data. Processing program: The program which is used to read the data from disk and process it is called processing program or accessing program. The functions used for file operations are defined in stdio.h header file. fprintf(): Writes set of data values to file according to the format specified. Syntax int fprintf(FILE *fp, const char *format [,arguments]); fscanf(): Reads set of data values from file as per the format specified. Syntax int fscanf(FILE *fp, const char *format, arguments);

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 Syntax int fclose(FILE *fp) feof(): This function checks for end of file while reading data from a disk file. It returns a 1 when the file comes to an 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 subjects in 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);

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);

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 student and read the data

Program 158: /* Data creation program Write 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(); }

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); }

Data of any text file can be read by C file program fgetc() : Gets character from a stream Syntax int 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); }

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') {

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 into another 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);

} 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

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');

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 same file structure can be merged and made as single file.

Program 166: #include<stdio.h> /*MERGING FILE Read the data from stud1.data file , stud2.dat file and store it in student.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);

} 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); else fprintf(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*/

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 to read 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 by whence. Whence Sets seek starting points as follows SEEK_SET / 0 - seeks from beginning of file SEEK_CUR /1 - seeks from current position SEEK_END /2 - seeks from end of file Returns 0 if successful or nonzero on failure. ftell() : Returns the current file pointer Syntax 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 from required character */ # include <stdio.h> main() { FILE *fp; int no; char ch; /* To store data into file. Press ^z or F6 to stop */

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 from required position Explain fprintf, fscanf, fgetc, fputc.

Data Structures Organizing and accessing the data in a methodical way with efficient memory management and processing speed is the central concept of data structures. The data structuring can be done in two ways:

Non Pointer programming

Pointer programming In Non pointer programming, the set of data is organized and accessed in methodical order using arrays, structures and combination. In pointer oriented programming the set of data is organized and accessed with the help of pointers and address references. This style is preferred for its speed and storage management. Some example programs on pointer data structures are Linked lists, stacks, queues, trees etc. The header files stdlib.h and alloc.h are included for pointer based programs. Some of the functions of these header files are as follows alloc() : This function allocates specified number of bytes in heap of memory and fill it with zeros. Syntax Char *alloc(size) Example: struct student *ptr; prt = (struct student*)alloc(sizeof(struct student)); malloc() : This function allocates specified number of bytes in heap 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); Example sturct student *ptr;

prt = (sturct student*)calloc(5,sizeof(struct student)); realloc(): This function is used to increase or decrease the size of memory. Syntax char *realloc(old block,size) Example ptr =realloc(prt,5); free(): This is used to free the allocated memory space. Syntax int free(pointer) Example free(ptr); Linked list : The dynamic allocation of memory for data and de allocation can be done with linked lists. The problem with arrays is, it is with static memory allocation. The specified number of elements are allocated and they cannot be increased or decreased. Dynamic insertion and deletion of elements is not possible with array based programs. We can over come the above problems with pointer based linked list programs. Linked list contains self referencing structures. Each structure is called node. Every node is with two parts. The first part is called information part and the second part is called pointer part. The information part contains the data to be stored and the pointer part contains the address of the next node to point. The last node of linked lists pointer part contains NULL. The single linked list is also called a linear linked list or one way linked list. Example

Linked list

10

222

40

null

222 Adding node with data 80


10 222 40 333 80 null

222

333

Inserting node with data 60 in between 40 and 80


10 222 40 444 60 333 l

80

null

111 333

222

444

Deleting node with data 40


10 444 60 333 80 null

111 Programs on Linked lists : Single Linked list : Program 169:

444

333

/* Single linked list program */ /* Program to implement Single Linked List */ Output #include <stdio.h> Enter ur choice as #include <conio.h> shown: #include <stdlib.h> 1. Insert #include <alloc.h> 2. Delete /* The structure slist */ 3. Display 4. Exit struct slist { Enter ur choice here : 3 int no; struct slist *next; }; typedef struct slist node; node *start = NULL, *n = NULL, *ptr = NULL; void insert(); void delete();

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;

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; }

} } /* 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"); }

Double Linked list : It is similar to single linked list but with an added facility of bi -directional traversing. That is one can traverse from 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 part is called before pointer which contains the address of previous node. The second part is called information part which contains the data. The third part is called next pointer which contains the address of next node. The address in the before pointer of very first node and the address in the next pointer of last node is NULL.

Example: Double linked list


null 10 222

11 1

40

null

11

222

Adding node to double linked list


null 10 222

11 1

40

333

22 2 222

90

null

111

333

Deleting node with data 40 from double linked list


null 10 333

11 1

90

null

111 Program 170: /* Double Linked List */ #include #include #include #include <stdio.h> <conio.h> <alloc.h> <stdlib.h>

333

Output

/* The struct dlist */ struct dlist {

Enter ur choice as shown below: 1. Insert 2. Delete 3. Display 4. Exit Enter ur choice here : 1

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); } } }

/* 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; }

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; else start = start->next; free(n); return; } if(tail->no == m) { n = tail; tail = tail->prev; tail->next = NULL; return; }

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 last node will be referring to the first node. Example 111 444
10 222 40 333 60 444 80 111

222

333

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; else l->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(); }

Queues : Queue is an ordered group of elements in which elements are added at last called rear end and elements are deleted from front. This is first in first out (FIFO) concept. Operations on queue are 1. adding elements 2. deleting elements 3. Displaying elements Example Queue
10 222 40 null

222 Adding node with data 80 to queue


10 222 40 333 80 null

111

222

333

Deleting node from queue


40 333 80 null

222 Program 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);

333

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; else l->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;

} } while(c<4); } Stack : Stack is an ordered set of elements in which elements are added and deleted at same end of stack called stack top. Adding elements is called pushing and deleting elements is called poping. This follows last in first out (LIFO) concept. So the element which is added last will be removed first and the element which is added first will be removed last. Different operations on stack are 1.pushing elements 2.poping elements 3. displaying elements. Example Stack Stack top
40 222 80 null

111

222

Pushing node with data 10 to stack stack top


10 111 40 222 80 null

333 Poping from stack Stack top


40 222 80

111

222

null

111

222

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); }

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); }

You might also like