GE6151 – COMPUTER PROGRAMMING REG.
2013 NOTES
Q January 14 May 14 January 15 May 15
1. Adv - 5th generation (110100111101)2 = (?)8 What is Flow chart? What is super computer?
computers
2. What is pseudo code? Flowchart for biggest of 2 number Define algorithm Define pseudo code
3. What are operators in C? What are data types in C? What is a variable? Define keywords
4. Print from 10 to 1 Program for factorial What is ternary operator? Write any 4 I/O statements
5. What is array? What is 2D array? Declare float array with Define array
5values
6. Write 4 string handling Write 4 string handling functions What is string array? What is character string
functions
7. Define functions Define recursion Define functions Actual and formal parameter?
8. Define pointer call by value/call by reference What is address operator? Define pointer
9. Define pre-processor What is the Purpose of union? What is static storage class? Define structure
10. Difference b/w struct & union What are pre-processor What is #define pre-processor? Define pre-processor
directives?
11a Generation of computers(16) Generation of computers(10) Organization of computer(10) Generation of computers(8)
Flowchart for factorial (6) PseudoCode-swap two Number system problem(8)
numbers(6)
11b Organization of computer(16) Organization of computer (8) Number system problem(10) Organization of computer (8)
Flowchart for 1+2+3+....+100 (8) Need of Logical analysis? (6) Flowchart–find +/-/0
number(8)
12a Looping in C(16) Prgm - prime or not (8) Explain operators in C (16) Explain operators in C (8)
Prgm - sum of digits of a Explain looping in C (16) Explain constants in C (8)
number(8)
12b Branching in C(16) Prgm - Roots of quadratic eqn(8) Sort an array of numbers (8) Explain looping in C (8)
Prgm - Entry/exit checked loop(8) Program using strlen (8) Prgm-Roots of quadratic
eqn(8)
13a Program to reverse a Prgm - call by reference(8) Matrix multiplication (8) Matrix addition(8)
string(8) Prgm – factorial (8) Search an element in array(8) Search an element in
Program for fibbonacci(8) array(8)
13b Matrix addition(16) Prgm – factorial (8) Call by value / reference (16) Sort an array of numbers (8)
Prgm – pointers (8) String handling functions(8)
14a How function is declared? (8) Prgm – bubble sort (16) Recursion (8) Pgrm - Factorial (8)
Call by value & reference(8) Prgm – pass by reference(8)
14b Function prototypes(8) Matrix subtraction(16) Prgm–find power of a Prgm-sum of digits of a
Recursion(8) number(8) number(8)
Prgm-pointer decrement (8)
15a Storage class (8) Explain storage class (16) Explain struct with example(16) Book details using struct(16)
Structure(8)
15b Student Mark sheet using Employee details using structure(16) Explain register storage class(6) Explain storage class (8)
structure(16) Explain union(6), pre-processor(4) Explain union with ex(8)
UNIT 1 UNIT 2 UNIT 3 UNIT 4 UNIT 5
Application & system s/w What is a variable? What is an array? Define function Define structure
Adv–5th generation comp Define keywords String handling functions Define pointers What is pre-processor
Digital computer What are the data types? What is 2D array? Define recursion #define pre-processor
Super computer Program for factorial What is string array? Call by value / reference What is a macro?
Compare RAM and ROM Operators in C Diff b/w struct&union
What is algorithm? Ternary operator Purpose of struct
What is pseudo code? Break and continue Purpose of union
What is flow chart? Program – odd or even Types of storage class
Number problem Diff b/w while & do..While Static storage class
Biggest among 2 numbers Extern storage class
Print from 10 to 1
Generation of computers Looping in C Bubble sort Pgrm – sum of digits Mark sheet – struct
Organization of computer Branching in C Insertion sort Function prototypes Employee – struct
Flowcharts Arithmetic&relational Merge sort Recursion (factorial) union
Number problem Logical&assignment Linear search Call by value&reference Storage classes
Increment/decrement Pgrm – fibbonacci Arithmetic op (pointers) Pre-processor
Formatted/unformatted IO Pgrm – factorial
Pgrm – prime or not Pgrm – matrix add
Pgrm – quadratic eqn Pgrm – matrix sub
Pgrm – matrix multiply
Pgrm-string functions
Pgrm –entry&exit checked
Underlined questions are the most probable questions expected to come for Dec 2015 exam
Prepared by V.Balamurugan, Assistant professor / Dept of IT
GE6151 – COMPUTER PROGRAMMING REG.2013 NOTES
UNIT 1 INTRODUCTION TO COMPUTERS
1. What is a computer?
The computer is an electronic machine that takes input from the user and processes it to generate the output in the
form of useful information.
2. What is a program?
A program is a set of instructions that can be executed one-by-one in the computer.
Each program performs certain task that is created by the user.
3. What is Hardware and Software?
Hardware of the computer means, all the visible components of a computer that are needed for proper functioning.
It is the framework. Software is applied on the hardware of the computer. E.x: CPU, monitor, etc
Software of the computer means, the set of programs that can be executed one by one in a computer.
It controls all the operations of a computer. Ex: OS, games softwares, etc
4. What is the difference between application software and system software?
System softwares are inbuilt softwares that are required to start the computer.
Without system software, a computer cannot work properly. Ex : Windows OS, Linux OS, DOS, etc
Application softwares are optional softwares that are needed to perform certain task needed for user.
Without application software, a system can work. Ex: Tally, Games softwares, etc
5. What are the advantages and disadvantages of first generation of computers?
Advantages: Disadvantages:-
Based on vacuum tube technology Large space is needed.
During that time, these type of computers It takes more power
were the fastest. Very costly
Calculations are done in milliseconds. No reliability
Programming is difficult
6. What are the advantages and disadvantages of second generation of computers?
Advantages: Disadvantages:-
Based on transistor technology Very costly
Small in size It needed AC
Less heat produced Production was difficult
Calculations are done in microseconds
Better reliability
7. What are the advantages and disadvantages of third generation of computers?
Advantages: Disadvantages:-
Based on IC (Integrated Chip) technology It needed AC
Calculations are done in nano seconds Production was difficult
Less power needed
Less maintenance cost
More reliability
8. What are the advantages and disadvantages of fourth generation of computers?
Advantages: Disadvantages:-
Based on Processor technology Production was difficult
Small in size
Portable and very much reliable
Less maintenance cost
All programming languages are supported
9. What are the advantages and disadvantages of fifth generation of computers?
Advantages: Disadvantages:-
Portable There is no program that makes the computer to
User friendly operate completely automatic.
Supports many OS
Supports parallel programming
High speed calculations
Large storage capacity.
Prepared by V.Balamurugan, Assistant professor / Dept of IT
GE6151 – COMPUTER PROGRAMMING REG.2013 NOTES
10. What are the characteristics of a digital computer?
They have large memory space
They are suitable for business
High processing speed
Discrete value outputs are got
It is versatile in nature.
11. What are the differences between analog and digital computers?
Analog computer Digital computer
Less speed High speed
Less memory More memory
Limited usage Many number of usage
Output is in the form of graph Output is in the form of discrete values
Less accurate calculation More accurate calculation
12. What are the advantages and disadvantages of micro and mini computers?
Advantages – Micro computers Disadvantages – Mini computers
Small in size Less memory capacity
Very cheap in cost, compared to Mini computers Difficult in maintenance
Highly reliable
Advantages – Mini computers Disadvantages – Mini computers
Small in size, compared to mainframe computers Calculation speed is less than mainframe computers
Cheap in cost, compared to mainframe computers Memory capacity is small, compared to mainframe
13. What are the advantages and disadvantages of mainframe and super computers?
Advantages – mainframe computers Disadvantages – mainframe computers
Many OS can be installed in mainframe It is very much costly
computer
It can be used instead of 1000s of small servers Its size is very big
It can store large amount of data
Advantages – super computers Disadvantages – Super computers
Processing speed is : trillions per second Its size is large
Many processors can work at the same time It is also very costly
It has more main memory
14. Compare RAM and ROM
RAM ROM
It is a volatile memory It is a non-volatile memory
It is used for both READ and WRITE operations It is used for READ operation only
It has small storage capacity It has large storage capacity
It is temporary It is permanent
Its cost is high It is cost effective
Processing speed is high Processing speed is low
15. What is an algorithm?
An algorithm is defined as a step by step procedure for solving a problem.
It is a set of rules to solve a problem.
16. What are the characteristics of an algorithm?
It has a finite number of inputs
Every instruction is clear and short
It should have a proper ending
Each step should be important.
Overall output should be got only after the algorithm ends.
It should contain the steps one-by-one to solve the problem
17. What is a pseudo code?
Pseudo = copy (or) Duplicate, Code = instructions
It cannot be compiled or executed
It is written in natural language such as English, etc
It is used to concentrate on algorithm
Prepared by K.Balasubramanian, Assistant professor / CSE
GE6151 – COMPUTER PROGRAMMING REG.2013 NOTES
18. What are the advantages and disadvantages of pseudo code?
Advantages Disadvantages
It can be easily prepared in Word processor It does not have pictures
software
Easily modified There is no rules for preparation
It is simple because it is written in English It cannot be compiled or executed
No confusing symbols are used
No rules are followed
It is easy to understand the problem
19. What is a flow chart?
A flow chart is a diagrammatic representation that illustrates the operations to be performed one-by-one.
It contains different symbols.
20. What are the advantages and disadvantages of flow charts?
Advantages Disadvantages
It is easy to understand It cannot be prepared for difficult programs
A problem can be analysed easily with flowchart Alterations and modifications cannot be done easily
It gives clear idea of a program It is not typed, so its preparation is little difficult
It acts as a guide during the program development
It helps to clear the errors in coding
It helps in maintenance of code
PART – B
1. What are the characteristics of a computer?
a. Speed:-
Computers are very fast in processing
They solve large problems in less time
They are faster than humans
They do millions of calculations per second
b. Accuracy:-
They perform calculations accurately; accuracy means, without any error
They process large amount of data without error
c. Storage:-
A computer can store large amount of data in primary memory and secondary memory
Storage is calculated in BYTES. 1 BYTE = 8 BITS. 1 BIT = 0 or 1
8Bits = 1 BYTE, 1024 Bytes = 1KB, 1024KB=1MB, 1024 MB = 1GB, 1024GB = 1TB
d. Versatility:-
Computers are versatile; versatile means, perform many works at same time
They are used for doing arithmetic and logical operations
e. Diligence:-
They do not get tired even after performing many calculations
They perform all the tasks with same accuracy and speed
f. Automation:-
The computers perform operations without stopping.
They do the process one by one according to the instructions
2. What are the applications of a computer?
It is used to store, display, send and receive information
It is used to draw graphs, pictures
It is used in medical clinic and labs
It is used to control rockets and aeroplanes
It is used for banking purpose also
It is used in horoscope
It is used in Crime investigation
It is used to control Robots
Education:-
Prepared by V.Balamurugan, Assistant professor / Dept of IT
GE6151 – COMPUTER PROGRAMMING REG.2013 NOTES
It is used in education, online classrooms, online library, etc
Marketing:-
It is used in preparing advertisements
Banking:-
It is used in banking to store the account details of customers
It is used in ATM, internet banking
Video games:-
It is used in playing video games, online games, etc
Training:-
Computers are used to give training to the workers
Hospitals:-
It is used in hospitals to help the doctors to find the disease and give treatment
It stores the record of patients Ex: Scan, blood test, ECG, etc
Railways:-
It is used in online ticket reservation, see the schedule of trains, etc
Science:-
It is used in research by scientists
It helps in finding earth quake, Tsunami, etc
3. Explain the generation of Digital computers in detail. (or) Explain the Generation of computers in detail.
First Generation:-
The first generation of computers were used only for certain task.
Each computer has a machine language ( 0’s and 1’s)
They are difficult to process
They are not versatile, they have limited speed.
They used VACUUM TUBES and MAGNETIC DRUMS for data storage.
It consumed 100kW power, weight of many 1000kilos.
It performed 5000calculations per second.
Ex: EDSAC, UNIVAC, etc
Advantages: Disadvantages:-
Based on vacuum tube technology Large space is needed.
During that time, these type of computers It takes more power
were the fastest. Very costly
Calculations are done in milliseconds. No reliability
Programming is difficult
Second generation of computers:-
They are used in business, university, government, etc because of its success.
They used TRANSISTORS for memory storage
They are small and consume less power
Thermionic valves are used instead of heated tubes
They also contained components such as printers, tape, disk storage, memory, OS, etc
Ex: IBM 1401, 1620, UNIVAC 1108
Advantages: Disadvantages:-
Based on transistor technology Very costly
Small in size It needed AC
Less heat produced Production was difficult
Calculations are done in microseconds
Better reliability
Third generation of computers:-
Integrated Chip (IC) Technology is used for memory storage
Quartz rock is used to remove the heat.
IC is a combination of three components on a small disc
Semiconductor was also introduced.
Because ICs are small in size, the size of the computers became small
In this generation of computers, many operating systems can be installed.
Prepared by V.Balamurugan, Assistant professor / Dept of IT
GE6151 – COMPUTER PROGRAMMING REG.2013 NOTES
Ex: IBM 360 series, ICL 1900 series, CDC 1700
Advantages: Disadvantages:-
Based on IC (Integrated Chip) technology It needed AC
Calculations are done in nano seconds Production was difficult
Less power needed
Less maintenance cost
More reliability
Fourth generation of computers:-
IBM introduced Personal Computers (PC) that can be used in home / office / schools
The size of the computer became still smaller
Number of personal computers doubled from 1million in 1981 to 5.5million in 1982
After 10years, 65millions PC were used.
Apple’s MacIntosh OS also introduced in 1984, that is user friendly design.
Ex: Intel 400L, Apple series I and II, IBM
Advantages: Disadvantages:-
Based on Processor technology Production was difficult
Small in size
Portable and very much reliable
Less maintenance cost
All programming languages are supported
Fifth generation of computers:-
Many advances came in science and technology in this generation
Parallel processing is used, it means, many CPU work as one CPU
Superconductor technology is used in this generation
Information flow is fast because of superconductor
Ex: Expert systems help doctors to cure the patient’s disease
Artificial intelligence is a branch of computer science that makes the computers behave like humans
Artificial intelligence is used in: Games, Expert systems, Natural language, Neural networks
Advantages: Disadvantages:-
Portable There is no program that makes the computer to
User friendly operate completely automatic.
Supports many OS
Supports parallel programming
High speed calculations
Large storage capacity.
4. Write the differences between analog and digital computers
Analog computers:-
Analog computers represent the data as physical quantities
It performs operation based on measuring
It is designed to process data of varying quantities
It solves problems in voltage, current, etc
They are useful in simulation and evaluation of dynamic situations
It contains operational amplifier
Computer’s capacity is determined by number of amplifiers
They are used in speedometres, watt-hour metres
Ex: Electronic weighing scale, patient heart beat, blood pressure
Characteristics of analog computers:-
Low speed
Limited applications
Less memory space
Not suitable for business
Output is not accurate
Digital Computers:-
They process the information digitally.
It stored and processes the data in digital form
Data is stored as 0’s and 1’s
Output produced by digital computers is in Digital form.
Prepared by V.Balamurugan, Assistant professor / Dept of IT
GE6151 – COMPUTER PROGRAMMING REG.2013 NOTES
Ex: Palmtop, Laptop, Super computer, etc
Characteristics of a digital comouter:-
Large memory space
Suitable for business applications
Processor speed is high
Versatile in nature
5. Explain about mainframe and super computers
Mainframe computers:-
It is an ultra-high performance computer, made for high storage.
It contains high quality computer processor, processor, hardwares
It is used for storing large volumes of data, highly important online transaction, etc
It is very powerful and large computer
Its operating speed is MIPS – Million instructions per second
Ex: IBM ES000, VAX8000, CPC6600
Advantages – mainframe computers Disadvantages – mainframe computers
Many OS can be installed in mainframe It is very much costly
computer
It can be used instead of 1000s of small servers Its size is very big
It can store large amount of data
Super Computers:-
They are most powerful computers than mainframe computers
The simplified form of mainframe computer is called as super computer
It is the top level computer used for high processing capacity
It can process Trillions of instructions per second ( 10,00,000 = 1million, 10,00,00,000=1trillion)
Applications of super computers:-
This computer cannot be used at home
It is used in heavy jobs such as Government use, etc
They are useful in weather forecasting.
Advantages – super computers Disadvantages – Super computers
Processing speed is : trillions per second Its size is large
Many processors can work at the same time It is also very costly
It has more main memory
6. Explain the basic organization of a computer.
The organization of a computer has four major parts:- They are
a. Input Unit
b. CPU
c. Output Unit
d. Memory unit
Input Unit Memory Unit Output Unit
Cache memory
Registers
CPU
ALU
Control Unit
Prepared by V.Balamurugan, Assistant professor / Dept of IT
GE6151 – COMPUTER PROGRAMMING REG.2013 NOTES
Basic operations of a computer:-
It ACCEPTS the data or instruction through INPUT
It STORES the data or information
It can PROCESS data as instructed by the user
It GIVES results through OUTPUT
It CONTROLS all the operations
Input Unit:-
Input devices get the data from the user and converts to the machine understandable form.
Ex: Keyboard, Mouse, Scanner, Joystick, Lightpen, Card reader, Webcam, Microphone
Keyboard:-
It is a standard input device attached to all type of computers
It contains keys arranged in the form of QWERTY
It contains many keys such as TAB, CAPSLOCK, SPACE BAR, ALT, CTRL, ENTER, HOME, END, etc
It contains 101 to 104 keys
If we press the keys in the keyboard, electrical signals are sent to the computer.
Mouse:-
It is used with personal computer
Old type of mouses have magnetic ball at the back.
Nowadays, Infrared mouses are used, that works on infrared light at the back of the mouse
We can move cursor to any direction with the help of a mouse
It is used for easy and fast operations.
Scanner:-
Keyboard can give input only the characters
Scanners can give a picture as input to the computer
Scanner is an optical device that takes a picture and gives as input to the computer
Ex: MICR, OMR, OCR
MICR – Magnetic Ink Character Recognition
They are used in bank cheques
Magnetic ink is printed on the cheque. If the cheque is passed through magnetic field, the information is read
OMR – Optical Mark reader
They are used in objective type tests
Students have to shade the rounds for the correct answer
OCR – Optical Character Recognition
Reads a paper and takes the information from it, gives as input to the computer
They are costly than MICR
Joystick:-
It is an online device
We can move the cursor fastly with the help of joystick
They are used to play games, etc
Light Pen:-
It is a light-sensitive device
It is used with CRT monitor
It is used in CAD
Using light, it moves the cursor
Photo-sensor is used
Card Reader:-
It was punched cards to give information to the computer
The computer program which is to be fetched, transformed into punched cards by the process known as
card punching
After punching all cards, they are given to card reader, computer reads one by one
Webcam:-
It is a video camera that gives image or video to the computer that can be transferred online
It is connected to the system with USB cable
It us used for video chatting, video conferencing, etc using WWW
Microphone:-
It is an acoustic-to-electric transducer or sensor that converts sound signals to electric signals
They are used in Telephones, hearing aids, recording audio engineering, Radio and TV broadcasting, etc
It uses electromagnetic inductance capacitance change to produce electric signal from mechanical
vibration
Prepared by V.Balamurugan, Assistant professor / Dept of IT
GE6151 – COMPUTER PROGRAMMING REG.2013 NOTES
CPU:-
It is called as brain of the computer
It performs taks such as arithmetic and logical operations
CPU is divided into three parts: ALU, Control Unit, Registers
ALU:-
After the system gets input data, it is stored in primary storage.
The actual processing of data takes place at Arithmetic Logic Unit (ALU)
It performs addition, subtraction, multiplication, division, logical comparison, etc
It also performs AND, OR, NOT, XOR, etc operations
Control Unit:-
It acts like the supervisor of a computer
It controls the overall activities of a computer components
It checks all the operations of a computer are going correctly or not
It determines how the instructions are executed one by one
It controls all the input and output operations of a computer
For executing an instruction, it performs the following steps:-
o Address of the instruction is placed in address bus
o Instruction is read from the memory
o Instruction is sent for decoding
o Data from that address is read from the memory
o These data and address are sent to the memory
o Again the next instruction is taken from the memory
Registers:-
They are high speed memory units for storing temporary data
they are small in size
it stores data, instruction, address, etc
ALU is also a register
Types: Accumulator, GPR, SPR( PC, MAR, MBR, IR)
Accumulator: to store the operands before execution. It receives the result of ALU operation
GPR: General Purpose Registers are used to store data and intermediate results
SPR:Special Purpose Registers are used for a certain purpose.
PC: Program counter, MAR: Memory Address Bus, MBR: Memory Buffer Register
Output Unit:-
It is a medium between computer and the human
After the CPU finishes operation, the output is displayed in the output unit
They take the input from CPU and converts to human readable form
Types of output:- Hardcopy, softcopy
Hardcopy: The output that can be seen physically using a printer is called as hardcopy
Softcopy: The electric version of output that is stored in a computer or a memory card, or a hard disk
Ex: Monitor, Printer, Plotter
Monitor:-
It is the most popular output device
It is also called as Visual Display Unit (VDU)
It is connected to a computer through a cable called Video cord
It can be monochrome or color monitor
LCD: Liquid Crystal Display monitors
o They are flat type of screen. Liquid crystals are used for display in the screen
CRT: Cathode Ray Tube monitors
o They are old-fashioned TV set like monitor
Printer:-
The output of a computer can be printed using Printer, to get the hardcopy
Laser printer, Inkjet printer: Impact printers. They give fast printouts with good quality using LASER
Dot matrix printer: non-impact printers. Their quality is poor, they are used for billing purpose
Plotter:-
They are used for printing graphics
They are used in CAD/CAM
Pen plotters take printout by moving a pen across the surface of a piece of paper
Prepared by V.Balamurugan, Assistant professor / Dept of IT
GE6151 – COMPUTER PROGRAMMING REG.2013 NOTES
Memory Unit:-
memory
Primary Secondary
memory memory
Magnetic Semiconductor Semi-random
Thin-film Serial access
memory access memory
core memory memory
memory
RAM ROM
Static Dynamic PROM EPROM EEPROM
RAM RAM
Primary storage:-
It is a part of CPU
Its storage capacity is limited
It contains magnetic core or semiconductor cells
It is used for temporary storage
Magnetic core memory:
o It contain a small dough-nut shaped objects made of ferromagnetic material
o Current is passed through wire in one direction, magnetized in one direction
Semiconductor memory:
o It contains IC chips on silicon
o They are small, high processing speed, low power is used, cheap, easy to assemble
ROM:
o Major type of memory in a computer is called ROM
o Read Only Memory
o It can be read, cannot be written
o It is used for storing permanent values
o ROM does not gets erased, even after the power is switched off
o They are non-volatile ( information cannot be erased)
o We can store the important data into the ROM
o Ex: Hard disk
PROM:
Programmable Read Only Memory
They contain 1000 of fuses burnt, applying 12V to the memory boxes
These fuses say 0 or 1
EPROM:
Erasable Programmable Read Only Memory
They can be deleted
This chips have glass panel, UV rays are passed
Fuses are rearranged in UV rays (all bits become 1)
EEPROM:-
Electrically Erasable Programmable Read Only Memory
They can be erased using electric current
RAM:-
o They are used for storing programs and data that are executed
o It is different from ROM
o Random Access Memory
o It can be read and written
o It is volatile
Prepared by V.Balamurugan, Assistant professor / Dept of IT
GE6151 – COMPUTER PROGRAMMING REG.2013 NOTES
o When the power is turned off, its contents are erased
o It is also called as RWM (Read Write Memory)
o It is faster than ROM
o Static RAM (SRAM) and Dynamic RAM (DRAM) are its types
o Its cost is high
o Its processing speed is also high
Cache memory:-
o It is a very small memory used to store intermediate results and data
o It stores the data that are more frequently called for processing
o It is present inside the CPU, near the processor
o It is used for the faster execution
Secondary Storage:-
o The speed of primary memory is fast, but secondary memory is slow
o But the memory capacity of primary memory is low. So, secondary memory is used
o It contains large memory space
o It is also called as additional memory or auxiliary memory
o Data is stored in it permanently
o Ex: Magnetic tape, Hard disk, Floppy, Optical Disc, USB drives
o Magnetic tape:-
It is used for large computers like mainframe computers
Large volume of data is stored for a long time
It is like a old tape-recorder cassette
They are cheap
They store data permanently
Its diameter is 12.5mm to 25mm, length is 500M to 1200M
It is compact, low cost, portable, unlimited storage, easy to handle
o Hard disk:-
Hard disks are disks that store more data and works faster
It can store 10GB to 2TB
It consists of platters
Two heads are there for read and write
It is attached to single arm
Information in hard disk is stored in tracks
A track location that cuts across all platters is called as a cylinder
All platters have same no.of tracks
o Floppy Disk
They can store 1.4MB of data
They are 5.25 to 3.5 inch in diameter
They are cheap, portable
o Optical Disk:-
CD-ROM:
Compact Disk
They are made of reflective material
High power laser beam is passed to store data onto CD
Cost is low, storage capacity is 700MB
Its size is 4.5inches in diameter
It can only be READ, cant be written
Only a single side can be used for storage
DVD:
Digital Video Disk
It is the improved version of CD
It can store 4.7GB of data
Both the sides are used for storage
They cannot be scratched or damaged like CD
USB drives:-
They are commonly called as PEN DRIVES
They are removable storage
They are connected to the USB port of a computer
They are fast and portable
They store larger data when compared to CD, DVD (1GB to 64GB pendrives)
Prepared by V.Balamurugan, Assistant professor / Dept of IT
GE6151 – COMPUTER PROGRAMMING REG.2013 NOTES
UNIT – 2 ‘C’ Programming Basics
Part – A (2mark questions) 8. What is a variable?
1. What are the advantages and disadvantages of A variable is an identifier for memory
C language? location
Advantages:- Data can be stored in it and taken when
Suitable for creating application software and needed.
system software 9. What is user-defined datatype? What are its types?
Easy, simple and fast. User can define a new kind of datatype to declare
It can be used for general purpose variables. It is called as user-defined datatype
Powerful language Types: Typedef, Enumerated
Flexible and portable 10. What is the difference between local variable and
Disadvantages:- global variable?
LOCAL VARIABLE GLOBAL VARIABLE
It is a weakly typed language
Defined at starting of a Declared before the main
It needs extra memory space
block function
It is not object oriented language It can be used only within It can be used anywhere in
2. What are the characteristics of C language? that block the program
It has many in-built functions ex:- ex:-
Pointers can be used int a=10; void main()
It is a structured language void main() {
Small and easy to understand { int i=10;
Efficient programming language printf(“%d”,i); printf(“%d”,i);
It can be used in many types of computers } }
3. Give the structure of a C program o/p:- 10 o/p:- 10
Documentation section
Preprocessor section 11. What ate the data types available in C?
Definition section In-built data type (int, char, float, …)
Global declaration section User defined data type( typedef, enum,struct)
Main function() Derived data type (array, pointer, function)
{ No data type (void)
Declaration part; 12. What are the basic (or) fundamental datatypes?
Executable statements; Int – to store numbers without decimal point
} Float – to store numbers with decimal point
User defined function() Char – to store a single character
{ Double – To store a big decimal point number
Executable statements; 13. Write any 6 escape sequences in C.
} \n – move to next line
4. What are the steps to execute a C program? \t – move one space horizontally
Create a C program \v- move in space vertically
Compile the program (Alt+F9) \f – move to next page
Link that program to library \r – move to starting of that line
Execute the program(Ctrl+F9) \b – backspace
5. What is a token? What are the types of Tokens? 14. What is an operator? What are its types?
The smallest individual unit of a program An operator is a symbol that tells computer to
is called as Token perform certain task.
Identifiers, keywords, constants, strings, Types:-
operators Arithmetic operators (+, -, *, /, % )
6. Mention some keywords in C language Relational operators ( <, >, <=, >=, ==, != )
If, else, while, do, for, continue, break, include, Logical operator ( &&, ||, !)
main, int, float, char, void Assignment operator ( +=, -=, *=, /=, %=, = )
7. What is a constant? Increment/decrement operator (i++, ++i, i--, --i)
A constant is a fixed value that cannot be changed Conditional operator ( ? : )
in the C program execution. Bitwise operator ( &, |, ^, <<, >>, ~)
Special operator ( sizeof() )
Prepared by V.Balamurugan, Assistant professor / Dept of IT
GE6151 – COMPUTER PROGRAMMING REG.2013 NOTES
15. Write differences between operator and operands. 20. What is a ternary operator?
OPERAND OPERATOR It is also called as conditional operator
It contains Data values It is a symbol for It is also called as question-colon operator
operation It checks the condition.
Operation is performed on Operation is performed by If condition is true, first part will be executed
operands operators If condition is false, second part is executed
Ex:- Ex:- Ex:-
C = a + b; C = a + b; C = (a < b) ? a : b
Here, a, b, c = operands Here, +, = are operators If (a < b) is true, then c = a
16. What are formatted and unformatted I/O if (a > b) is false, then c = b
functions? 21. Write a program to check a number is odd/even
Formatted I/O functions #include<stdio.h>
They follow certain format #include<conio.h> O/p:-
% symbol is used in input and output statements void main() Enter a number
Ex:- { 311
Input – scanf(“%d”,&n); It is odd number
clrscr();
Output – printf(“%d”, n); int n;
Unformatted I/O functions printf(“enter a number”);
They do not have any format scanf(“%d”,&n);
% symbol is not used. if ( n % 2 = = 0 )
Ex:- printf(“it is even number”);
Input – getc(), gets(), getch(), getchar() else
Output – putc(), puts(), putch(), putchar() printf(“it is odd number”);
17. What are the types of control structures in C? getch();
If statement }
If…else statement 22. Write a program using sizeof() operator
If..else ladder #include<stdio.h>
Switch statement O/p:-
#include<conio.h> 2
Goto statement void main() 1
18. What is the difference between break and continue
{ 4
statement?
clrscr(); 8
BREAK CONTINUE
To stop the current To stop the current printf(“%d”, sizeof(int));
iteration and get out of iteration and continue for printf(“%d”, sizeof(char));
that block next iteration printf(“%d”, sizeof(float));
Break; keyword is used Continue; keyword used printf(“%d”, sizeof(double));
It is used in switch case, It is used in for, while getch();
for, while, do }
23. Write a program to find biggest among two number
Statements after the Statements after
#include<stdio.h>
BREAK statement will not CONTINUE statement will O/p:-
#include<conio.h>
be executed not be executed in current void main()
iteration { A is big
19. What is the difference between while and do- clrscr();
while? int a=10, b=20;
WHILE DO..WHILE if(a>b) printf(“a is big”);
Entry check loop Exit check loop else printf(“b is big”);
Condition is checked at Condition is checked at getch();
entry point exit point }
Loop will not run if Loop will run ONE TIME if 24. Write a Program to print the numbers from 10 to 1 using for loop
#include<stdio.h> O/p:-
condition is false the condition is false #include<conio.h> 10
Ex:- Ex:- void main() 9
8
While (condition) Do { 7
{ { int i; 6
for(i=10; i>0; i--) 5
Body of the loop Body of the loop 4
printf(“%d”,i);
} } while ( condition); 3
getch(); 2
} 1
Prepared by V.Balamurugan, Assistant professor / Dept of IT
GE6151 – COMPUTER PROGRAMMING REG.2013 NOTES
PART – B ( 8 and 16 mark questions) 2. Explain different types of data types in C.
1. Explain the structure of a C program In-built data type (int, char, float, …)
Documentation section User defined data type( typedef, enum, struct)
Preprocessor section Derived data type (array, pointer, function)
Definition section No data type (void)
Global declaration section In-built data type:-
Main function() They are the created already within C compiler
{ If we want, we can use them directly
Declaration part; Keyword int, float, char, double is used.
Executable statements; Int – integer ( to store numbers)
} Float – to store decimal point number
User defined function() Char – character ( to store a single character)
{ Double – to store a big decimal point number
Executable statements; User-defined data type:-
} User is going to create a new data type
Documentation section:- Cannot be used directly like in-built data types
We can add any comments, description Typedef – to redefine the name of data type
It will not be executed Typedef int a;
Ex:- Enum – enumerated data type
/* program to add two numbers*/ Enum days{1=”sun”, 2=”mon”, 3=”tue”, 4=”wed”,
Preprocessor section:- 5=”thu”, 6=”fri”, 7=”sat”}
Pre-processor statements are used Struct – structure to hold different members
To link the program to library struct mech
Ex:- {
#include<stdio.h> int roll;
Definition section:- char name[20];
We can define all constants here. float marks;
These values will not be changed in the program }
Ex:- Derived data type:-
#define a 10 These are the data types that are derived from the
Global declaration section:- already existing data type.
We can declare global variables that can be used Ex:- Arrays, pointer, functions
anywhere in the program Int Array[10]; to store 10 integers one-by-one
It is outside of all the other functions Pointer int * a; to store address of other
Ex:- variable
Int a=10; Functions() to do a part of work
Void main() No data type:-
{ Void
….. Void is a data type that is not actually a data type
….. It does not contain any values
}
It is also called as empty data type
Main function()
It is must for all the programs 3. Explain arithmetic and relational operators in C.
A program cannot run without main() Arithmetic operators:-
Main – keyword is used Operators that do arithmetic operations such as
Program starts to run from main() only addition, subtraction, multiplication and division are
Declaration part:- called as arithmetic operators
We can declare values to the variables Operator Name Operation
Ex: a=10; * Asterisk Multiplication
Executable section:- / Slash Division
Execute the statements in this section + Plus Addition
C=a+b; printf(“%d”, c); - Minus subtraction
User defined function:- % Percentage modulus
User can write the functions if needed.
Prepared by V.Balamurugan, Assistant professor / Dept of IT
GE6151 – COMPUTER PROGRAMMING REG.2013 NOTES
Program for arithmetic operator:- 4. Explain logical and assignment operator in C
#include<stdio.h> Logical operator:-
#include<conio.h> It is used to do logical operations such as logical
void main() AND, OR and NOT
{ It is also binary operators because it takes two
clrscr(); operands.
int a,b; It returns 1 if TRUE, 0 if FALSE
printf(“enter values for a and b”); Operator Name Return value
scanf(“%d%d”,&a,&b); o/p:- && Logical AND 1 or 0
printf(“answer is”); Enter values || Logical OR 1 or 0
printf(“%d”, a+b); for a and b ! Logical NOT 1 or 0
printf(“%d”, a-b); 4
2 o/p:-
printf(“%d”, a*b); Program for logical operator:- Enter values for a,b,c
Answer is
printf(“%d”, a/b); 6 #include<stdio.h> 2
printf(“%d”, a%b); 2 #include<conio.h> 4
getch(); 8 6
void main()
2 Answer is
} { 1
0
clrscr(); 1
Relational operators:- int a,b; 13
Operator Name Return value printf(“enter values for a, b and c”);
< Less than 1 or 0 scanf(“%d%d%d”,&a,&b,&c);
> Greater than 1 or 0 printf(“answer is”);
<= Less than or equal to 1 or 0 printf(“%d”,( a < b ) && ( a < c ) );
>= Greater than or equal to 1 or 0 printf(“%d”,( a < b ) || ( a < c ) );
== Equality 1 or 0 printf(“%d”,(!a));
!= Not equal to 1 or 0 getch();
}
These operators are binary operators because
they want two operands to operate. Assignment operators:-
They return 1 if TRUE, 0 if FALSE They are used to assign values to the variables
Program for relational operator:- Values can be assigned after the expression
#include<stdio.h> Shorthand assignment operators is also there.
#include<conio.h> Operator Name Meaning assign value
void main() += Short-hand a+=b Add a + b and
{ add a=a+b store in a
clrscr(); -= Short-hand a - =b sub a - b and
int a,b; sub a=a–b store in a
printf(“enter values for a and b”); *= Short-hand a*=b multiply a * b
scanf(“%d%d”,&a,&b); o/p:- multiply a=a*b and store in a
printf(“answer is”); Enter values for a /= Short-hand a/=b divide a / b and
printf(“%d”, a<b); and b divide a=a/b store in a
4
printf(“%d”, a>b); == Equality 1 or 0
2
printf(“%d”, a<=b); Answer is != Not equal 1 or 0
printf(“%d”, a>=b); 0 to
printf(“%d”, a==b); 1
printf(“%d”, a!=b); 0
1
getch(); 0
} 1
Prepared by V.Balamurugan, Assistant professor / Dept of IT
GE6151 – COMPUTER PROGRAMMING REG.2013 NOTES
5. Explain the increment and decrement operators 6. Explain the formatted and unformatted I/O statements
and conditional operators in C. I/O Functions
Increment operator:-
Pre-increment operator (+ + i )
Post-increment operator ( i + +) Unformatted statements
Decrement operator:- Formatted statements INPUT OUTPUT
Pre-decrement operator (- - i ) INPUT OUTPUT getch() putch()
Post-decrement operator ( i - -) scanf() printf() getchar() putchar()
Pre-increment operator: increment first, and assign value gets() puts()
Post-increment operator: assign value first and then increment
Pre-decrement operator: decrement first, then assign value Formatted statements:-
Post-decrement operator: assign value first, then decrement. They can read all types of values
Example:- But the format should be specified
#include<stdio.h> Printf() to print any value to the o/p
#include<conio.h> Scanf() to get any value from the i/p
void main()
O/p:- Format specifiers for printf() and scanf():-
{
printf() scanf()
clrscr(); 10 %c print a character %c Read a character
int a=10;
12 %d print a decimal integer %d Read a decimal integer
printf(“%d”,a++);
%e print floating point %e Read floating point
printf(“%d”,++a); 12 exponent exponent
printf(“%d”,a - -); %f print a floating point %f Read a floating point
printf(“%d”,- - a); 10
%h print a short int %h Read a short int
getch(); %I print a %I Read a
} decimal/hexadecimal/octal decimal/hexadecimal/octal
In the above example, value of a = 10 %o print an octal integer %o Read an octal integer
printf(“%d”,a++); in this line, the value of a is printed %s print a string %s Read a string
first, and then it is incremented. (a = 10 + 1 = 11) %u print an unsigned decimal %u Read an unsigned
integer decimal integer
printf(“%d”,++a); in this line, the value of a is
incremented first, and then it is printed. (a = 11 + 1 = 12) Example Program:-
printf(“%d”,a - -); in this line, the value of a is printed #include<stdio.h>
first, and then it is decremented. (a = 12 - 1 = 11) #include<conio.h> O/p:-
printf(“%d”,- - a ); in this line, the value of a is void main() Enter value for x and y 10 20
Printf = 25
decremented first, and then it is printed. (a = 11 - 1 = 10) { Scanf = 2
Conditional operator:- clrscr();
It is also called as question-colon operator int a,b,x,y;
It is also called as ternary operator a=printf("Enter value for x and y \n");
It contains question mark and colon. b=scanf("%d%d",&x,&y);
It contains 1 condition and two executable statements printf("printf = %d",a);
If condition is TRUE, statement1 will be executed printf("scanf = %d",b);
If condition is FALSE, statement2 will be executed getch();
Syntax:- }
Condition ? statement 1 : statement 2 ;
Program:- Unformatted statement:-
#include<stdio.h> No format is followed here
#include<conio.h> Any kind of data will be processed here
void main() getch() To get one character or number or anything
{ getchar() To get one variable
clrscr(); gets() To get a string
int a=10,b=20; getc() To get one character
a>b ? printf(“a is bigger”) : printf(“b is bigger”);
getch();
putch() To print one character or number or anything
}
putchar() To print one variable
o/p:-
puts() To print a string
b is bigger
putc() To print one character
Prepared by V.Balamurugan, Assistant professor / Dept of IT
GE6151 – COMPUTER PROGRAMMING REG.2013 NOTES
Program:- O/p:-
8. Explain switch-case statement and perform
#include<stdio.h> Enter a string arithmetic operations using it.
#include<conio.h> MECH It is used to take decision from a number of choices
void main() Answer = MECH One switch statement should be there, many cases
{ can be there
clrscr(); Inside every case, break statement should be there
char a[10]; All cases should be unique (not same)
puts(“Enter a character”); Syntax:-
gets(a); o Switch ( variable)
puts(“Answer=”); {
puts(a); Case 1: statement 1; break;
getch(); Case 2: statement 2; break;
} Case n: statement n; break;
Program:- }
#include<stdio.h> O/p:- Example program:-
#include<conio.h> Enter a character B #include<stdio.h>
void main() B
Answer = #include<conio.h>
{ void main()
B
clrscr(); {
char a; clrscr();
printf(“Enter a character”); int a, b, choice;
a = getchar(); a=10, b=20;
printf(“Answer=”); printf(“enter 1 for addition”);
putchar(c); printf(“enter 2 for subtraction”);
getch(); printf(“enter 3 for multiplication”);
} printf(“enter 4 for division”);
printf(“enter your choice”);
7. Write a C program to check a number is Armstrong scanf(“%d”,&choice);
or not. switch(choice)
{
#include<stdio.h> case 1: printf(“%d”,a + b); break;
#include<conio.h> case 2: printf(“%d”,a - b); break;
void main() case 3: printf(“%d”,a * b); break;
{ case 4: printf(“%d”,a / b); break;
clrscr(); default: printf(“invalid choice”);
int n,r,arm,sum; }
printf(“enter the number”); getch();
scanf(“%d”,&n); }
O/p:- O/p:-
arm=n;
enter 1 for addition
sum=0; Enter the number enter 2 for subtraction
while(n>0)
153 enter 3 for multiplication
{
enter 4 for division
r=n%10; Armstrong number Enter your choice
sum=sum+r*r*r; 1
n=n/10; 30
} Enter your choice
If(arm==sum) printf(“Armstrong number”); 2
Else printf(“Not an Armstrong number”); -10
getch(); Enter your choice
} 3
200
Enter your choice
4
0
Prepared by V.Balamurugan, Assistant professor / Dept of IT
GE6151 – COMPUTER PROGRAMMING REG.2013 NOTES
9. Write a C program to find the sum of the series
1+2+3+…….+N
#include<stdio.h>
#include<conio.h> O/p:-
void main()
{ Enter the number
clrscr();
int n,i,sum; 10
printf(“enter the number”);
Answer = 55
scanf(“%d”,&n);
for(i=0; i<=n; i++)
{
sum = sum + i;
}
printf(“answer=%d”,sum);
getch();
}
10. Write a C program to print the reverse of a
number
#include<stdio.h>
#include<conio.h>
void main()
{
clrscr();
int n,r,rev;
printf(“enter the number”);
scanf(“%d”,&n);
rev=0; O/p:-
while(n>0)
{ Enter the number
r=n%10;
123
rev=rev*10+r;
n=n/10; Reverse = 321
}
printf(“reverse=%d”,rev);
getch();
}
11. Write a c program to check whether a number is
palindrome or not
#include<stdio.h>
#include<conio.h>
void main()
{
clrscr();
int n,r,rev,pal;
printf(“enter the number”);
scanf(“%d”,&n);
rev=0; O/p:-
while(n>0)
{ Enter the number
r=n%10;
121
rev=rev*10+r;
n=n/10; palindrome
}
If(pal==rev) printf(“palindrome”);
Else printf(“Not a palindrome”);
getch();
}
Prepared by V.Balamurugan, Assistant professor / Dept of IT
GE6151 – COMPUTER PROGRAMMING REG.2013 NOTES
UNIT – 3 Arrays and Strings
Part – A (2mark questions) 5. List out any six string handling functions.
1. What is an array? (or) Define array. Strcat() to concatenate a string (join)
An array is a collection of same data type elements Strupr() to change to Upper case (Capital letters)
All elements are stored in continuous locations Strlwr() to change to Lower case ( Small letters)
Array index always start from ‘0’ Strlen() to find length of string
It is represented using [ ] – square brackets Strrev() to reverse a string
Strcmp() to compare two strings
2. Write a program to find sum of array elements.
Strcpy() to copy one string to another string
#include<stdio.h>
#include<conio.h>
void main()
{
clrscr();
int i, n,sum, a[10];
printf(“enter how many numbers”);
scanf(“%d”,&n);
printf(“enter numbers one by one:”);
for(i=0; i<n; i++)
scanf(“%d”,&a[i]);
for( i=0; i<n; i++)
sum = sum + a[i];
printf(“answer = %d”, sum);
getch();
}
O/p:-
Enter how many numbers 5
Enter numbers one by one
10
20
30
40
50
Answer = 150
3. What is a two-dimensional array?
It is an array in which rows and columns are the two
dimensions
Two square brackets are used for rows and columns
More number of elements can be stored
Ex:-
Int a[2][2] = { {20,30}, {40,50} };-
Rows / A[0] A[1]
Columns
A[0] A[0][0] = 20 A[0][1] = 30
A[1] A[1][0] = 40 A[1][1] = 50
4. What is a string?
A string is a one dimensional array to store characters
It is represented inside double quotes “ “
It is also called as “sequence of characters”
Array is used to store the string.
Ex:- char a[10] = “Mechanical”;
M e c h a n i c a l
A[0] A[1] A[2] A[3] A[4] A[5] A[6] A[7] A[8] A[9]
Prepared by V.Balamurugan, Assistant professor / Dept of IT
GE6151 – COMPUTER PROGRAMMING REG.2013 NOTES
Part – B ( 8 and 16 mark questions) 2. Write a C program for addition of two matrices
1. Write a C program to arrange numbers in #include<stdio.h>
ascending order and descending order. #include<conio.h>
Ascending order:- void main()
#include<stdio.h> {
#include<conio.h> clrscr();
void main() int i, j;
{ int a[3][3], b[3][3], c[3][3];
clrscr(); printf(“enter matrix a in 3 x 3”);
int i, j, temp;
int a[10] = { 7, 2, 9, 5, 3, 4, 8, 1, 6, 0 }; for( i=0; i<3; i++)
for( i=0; i<10; i++) {
{ for(j=0; j<3; j++)
O/p:-
for(j=i+1; j<10; j++) {
Answer = scanf(“%d”,&a[i][j]);
{
0 }
if ( a[i] > a[j] )
1 }
{
2
temp = a[i];
a[i] = a[j]; 3 printf(“enter matrix b in 3 x 3”);
a[j] = temp; 4 for( i=0; i<3; i++)
} 5 {
} 6 for(j=0; j<3; j++)
} 7 {
printf(“answer=”); 8 scanf(“%d”,&b[i][j]);
for( i=0; i<10; i++) 9 }
{ }
printf(“%d”, a[i]);
} for( i=0; i<3; i++)
getch(); {
} for(j=0; j<3; j++)
Descending order:- {
#include<stdio.h> c[i][j] = a[i][j] + b[i][j];
#include<conio.h> }
void main() }
{
clrscr(); printf(“answer = ”);
int i, j, temp; for( i=0; i<3; i++)
int a[10] = { 7, 2, 9, 5, 3, 4, 8, 1, 6, 0 }; {
for( i=0; i<10; i++) for(j=0; j<3; j++)
{ {
for(j=i+1; j<10; j++) printf(“%d”,c[i][j]);
{ O/p:- }
if ( a[i] < a[j] ) Answer = }
{ 9 getch();
temp = a[i]; 8 }
a[i] = a[j]; 7 O/p:-
a[j] = temp; 6 Enter matrix Enter matrix Answer =
} 5 A in 3 X 3 B in 3 X 3 2
} 4 1 1 4
} 3 2 2 3
printf(“answer=”); 2 3 3 8
for( i=0; i<10; i++) 1 4 4 10
{ 0 5 5 12
printf(“%d”, a[i]);
6 6 14
}
getch();
7 7 16
} 8 8 18
9 9
Prepared by V.Balamurugan, Assistant professor / Dept of IT
GE6151 – COMPUTER PROGRAMMING REG.2013 NOTES
3. Write a C program for subtraction of two matrices 4.Write a program for multiplication of two matrices
#include<stdio.h> #include<stdio.h>
#include<conio.h> #include<conio.h>
void main() void main()
{ {
clrscr(); clrscr();
int i, j; int i, j, k;
int a[3][3], b[3][3], c[3][3]; int a[3][3], b[3][3], c[3][3];
printf(“enter matrix a in 3 x 3”); printf(“enter matrix a in 3 x 3”);
for( i=0; i<3; i++)
for( i=0; i<3; i++) {
{ for(j=0; j<3; j++)
for(j=0; j<3; j++) {
{ scanf(“%d”,&a[i][j]);
scanf(“%d”,&a[i][j]); }
} }
} printf(“enter matrix b in 3 x 3”);
for( i=0; i<3; i++)
printf(“enter matrix b in 3 x 3”); {
for( i=0; i<3; i++) for(j=0; j<3; j++)
{ {
for(j=0; j<3; j++) for(k=0; k<=3; k++)
{ {
scanf(“%d”,&b[i][j]); c[i][j] = c[i][j] + a[i][j] * b[i][j];
} }
} }
}
for( i=0; i<3; i++) for( i=0; i<3; i++)
{ {
for(j=0; j<3; j++) for(j=0; j<3; j++)
{ {
c[i][j] = a[i][j] - b[i][j]; c[i][j] = a[i][j] - b[i][j];
} }
} }
printf(“answer = ”);
printf(“answer = ”); for( i=0; i<3; i++)
for( i=0; i<3; i++) {
{ for(j=0; j<3; j++)
for(j=0; j<3; j++) {
{ printf(“%d”,c[i][j]);
printf(“%d”,c[i][j]); }
} }
} getch();
getch(); }
} O/p:-
O/p:- Enter matrix Enter matrix
Enter matrix Enter matrix A in 3 X 3 B in 3 X 3 Answer =
A in 3 X 3 B in 3 X 3 Answer = 1 1 30
2 1 1 2 2 36
4 2 2 3 3 42
3 3 3 4 4 66
8 4 4 5 5 81
10 5 5 6 6 96
12 6 6 7 7 102
14 7 7 8 8 126
16 8 8 9 9 150
18 9 9
Prepared by V.Balamurugan, Assistant professor / Dept of IT
GE6151 – COMPUTER PROGRAMMING REG.2013 NOTES
5. Write a C program for transpose of a matrix for( i=0; i<3; i++)
#include<stdio.h> {
#include<conio.h> for(j=0; j<3; j++)
void main() {
{ if(i==j) sum = sum + a[i][j];
clrscr(); }
int i, j; }
int a[3][3];
printf(“enter matrix A in 3 x 3”); printf(“answer = %d”, sum);
getch();
for( i=0; i<3; i++) }
{ O/p:-
for(j=0; j<3; j++) Enter matrix
{ in 3 X 3 Answer =
scanf(“%d”,&a[i][j]); 1 15
} 2
} 3
4
printf(“answer = ”);
5
for( j=0; j<3; i++)
{
6
for(i=0; i<3; j++) 7
{ 8
printf(“%d”,a[i][j]); 9
}
}
getch(); 6. Write a C program to find determinant of a matrix
} #include<stdio.h>
O/p:- #include<conio.h>
Enter matrix void main()
in 3 X 3 Answer = {
1 1 int i, j, det;
2 4 int a[2][2];
3 7 printf(“enter matrix in 2 x 2”);
4 2
for( i=0; i<2; i++)
5 5
{
6 8 for(j=0; j<2; j++)
7 3 {
8 6 scanf(“%d”,&a[i][j]);
9 9 }
}
6. Write a program to find sum of diagonal
elements of a matrix det = a[0][0] * a[1][1] - a[1][0] * a[0][1];
#include<stdio.h> printf(“answer = %d”, det);
#include<conio.h> getch();
void main() }
{
int i, j, sum;
int a[3][3];
printf(“enter matrix in 3 x 3”); O/p:-
for( i=0; i<3; i++) Enter 2 x 2 matrix
{ 4
for(j=0; j<3; j++) 8
{ 3
scanf(“%d”,&a[i][j]); 9
} Answer = 12
}
Prepared by V.Balamurugan, Assistant professor / Dept of IT
GE6151 – COMPUTER PROGRAMMING REG.2013 NOTES
8.Explain some string handling functions with strupr() to change letters to upper case (Captials)
example C programs. #include<stdio.h>
Strcat() to concatenate two strings (join) #include<conio.h> O/p:-
#include<stdio.h> void main()
#include<conio.h> O/p:- { MECHANICAL
void main() clrscr();
{ mechengg
char s[10]=”mechanical”;
clrscr(); printf(“%s”,strupr(s) );
char s1[10] = “mech”; getch();
char s2[10] = “engg”; }
strcat(s1,s2);
printf(“%s”,s1); strlwr() to change letters to lower case (small letter)
getch(); #include<stdio.h>
} #include<conio.h> O/p:-
void main()
Strlen() to find length of a string { mechanical
#include<stdio.h> clrscr();
#include<conio.h> char s[10]=”MECHANICAL”;
void main() O/p:-
printf(“%s”,strlwr(s) );
{ 10 getch();
clrscr(); }
int a;
char s[10]=”mechanical”; strset() to change letters to some other letters
a=strlen(a); #include<stdio.h>
printf(“%d”,a); #include<conio.h> O/p:-
getch(); void main()
} { zzzzzzzzzz
clrscr();
Strcpy() to copy one string to another string char s[10]=”mechanical”;
#include<stdio.h> strset(s,z);
#include<conio.h> O/p:-
printf(“%s”,s );
void main() getch();
{ mechanical
}
clrscr();
char s1[10]=”mechanical”; 9. Explain binary search with an example.
char s2[10]=” ”; It follows divide and conquer technique.
strcpy(s2,s1); Key means, search element.
printf(“%s”,s2); Key is compared with middle element.
getch(); If key > middle, ignore first half of elements
}
If key < middle, ignore second half of elements
This process is repeated recursively.
strrev() to reverse a string Until the element is found.
#include<stdio.h> Input: sorted array of elements
#include<conio.h> O/p:-
Output: element found (or) not found.
void main()
{ lacinahcem Sorted array Element Found
clrscr(); Binary search
Key Element not found
char s[10]=”mechanical”;
printf(“%s”,strrev(s) ); Steps:-
getch(); Find middle element of array
} Compare it with key
If middle < key, repeat steps 1 and 2 for 1st half of array
If middle > key, repeat steps 1 and 2 for 2nd half of array
if middle == key, element is found.
Prepared by V.Balamurugan, Assistant professor / Dept of IT
GE6151 – COMPUTER PROGRAMMING REG.2013 NOTES
Example:-
Sorted array: 10, 20, 30, 40, 50, 60 10. Explain linear search with an example.
The process of finding the key from the collection.
Key : 50
Compare all the elements one by one.
Here, left = 10, right = 60, mid = (10 + 60) / 2 = 35 No technique is used
Therefore, mid = 30 or 40. We take mid = 30 Input: unsorted array of elements
30 = 50 ? (false). Output: element found (or) not found
30 < 50 ? (true)
So, take second half of elements: 40, 50, 60 unsorted array element found
linear
Sorted array: 40, 50, 60
Key : 50 key search element not found
Here, left = 40, right = 60, mid = (40 + 60) / 2 = 50
50 = 50 ? (true) Steps:-
Therefore, element found at 5th position. Read the first element
Compare with key
Program:- If true, element is found.
#include<stdio.h> If not true, compare next element.
#include<conio.h> Continue step 2, 3, and 4 till the last element.
void main() Example:-
{ Unsorted array: 9, 7, 3, 6, 8, 1, 20
clrscr(); Key : 8
int a[10], i, n, key, c, left, right, mid;
printf(“enter number of elements”); 9 7 3 6 8 1 20
scanf(“%d”,&n);
printf(“enter the sorted array elements”); 8 ? (false). Go to next
for(i=0; i<n; i++)
{ 9 7 3 6 8 1 20
scanf(“%d”,&a[i]);
}
8 ? (false). Go to next
printf(“enter the key”);
scanf(“%d”,&key);
9 7 3 6 8 1 20
right = n-1;
while(left<=right)
8 ? (false). Go to next
{
mid = (left+right)/2;
9 7 3 6 8 1 20
if(key==a[mid] c=1;
else if(key < a[mid]) right = mid -1;
else left = mid +1; 8 ? (false). Go to next
}
if ( c ==0 ) printf(“element not found”); 9 7 3 6 8 1 20
else printf(“element found”);
getch(); 8 ? (true) element found
} Program:-
#include<stdio.h>
O/p:- #include<conio.h>
Enter number of elements 6 void main()
Enter sorted array 10 20 30 40 50 60 {
Enter key 50 clrscr();
int a[10], key, c, i;
Element found
printf(“enter number of elements”);
scanf(“%d”,&n);
Advantages Disadvantages printf(“enter the sorted array elements”);
Efficient and faster Not suitable for unsorted for(i=0; i<n; i++)
array {
Uses divide and conquer Not suitable for dynamically scanf(“%d”,&a[i]);
changing data }
Suitable for large elements printf(“enter the key”);
scanf(“%d”,&key);
Prepared by V.Balamurugan, Assistant professor / Dept of IT
GE6151 – COMPUTER PROGRAMMING REG.2013 NOTES
2 1 3 4 5
for(i=0; i<n; i++)
{
if(a[i] = = key)
{ 1 2 3 4 5
c = 1;
break; 1 2 3 4 5
}
} 1 2 3 4 5
if( c ==0) printf(“element not found”);
1 2 3 4 5
else printf(“element found”);
getch();
Program:-
}
#include<stdio.h>
O/p:- #include<conio.h>
Enter number of elements 7 void main()
Enter sorted array 9 7 3 6 8 1 20 {
Enter key 8 clrscr();
Element found int n, temp, i, j, a[10];
printf(“enter number of elements”);
scanf(“%d”,&n);
Advantages Disadvantages
printf(“enter the elements”);
Easy and faster Not suitable for large
number of elements for(i=0; i<n, i++)
Array can be unsorted Slower method {
Suitable for small number of Very basic technique scanf(“%d”,&a[i]);
elements }
11. Explain bubble sort with an example for(i=n-1; i>0; i--)
It the oldest and easiest sorting. {
In this sorting, the elements are arranged in some for(j=0; j<=i; j++)
technique. {
Take first element, compare it with next element. if(a[j]>a[j+1])
If first > second, swap the elements. {
Then, again compare 1st element with next element temp = a[j];
Continue this process until, each element is a[j] = a[j+1];
compared with every other element. a[j+1]= temp;
}
Unsorted array Sorted array
Bubble }
sort }
printf(“answer=”);
Example:-
for(i=0; i<n; i++)
4 2 3 1 5
{
printf(“%d”,a[i]);
2 4 3 1 5
}
getch();
2 3 4 1 5 }
O/p:-
2 3 1 4 5 Enter number of elements 6
Enter elements 8 9 6 2 3 7
Answer = 2 3 6 7 8 9
2 3 1 4 5
Advantages Disadvantages
2 1 3 4 5 Easy technique Not suitable for large number
of elements
2 1 3 4 5 simple Not efficient
Suitable for small number of Very basic technique
elements
Prepared by V.Balamurugan, Assistant professor / Dept of IT
GE6151 – COMPUTER PROGRAMMING REG.2013 NOTES
12. Explain insertion sort with example Advantages Disadvantages
Insertion sort is the process of taking elements from Easy technique Not suitable for large
the list one by one and inserting them at correct number of elements
position in the array. Simple and stable method expensive
It is the simplest sorting. Suitable for small number of
elements
Unsorted array Insertion Sorted array 13. Explain selection sort with example
sort It is one of the basic sorting technique.
It is used to sort the elements in ascending order
Steps:- It is based on comparison and swapping.
Take first element in the list Take the first element and compare it with all the
Then take 2nd element in the list other elements.
Check if it is less than 1st The elements are swapped if first one is greater
Insert at correct position than the other element.
Then take next element, insert at correct position
Repeat this process till all elements are sorted. selection
Example:- Unsorted array sorted array
sort
20 10 60 40 30 15
10 20 60 40 30 15
Steps:-
10 20 60 40 30 15
Take first element
10 20 40 60 30 15
Compare it with next element
10 20 30 40 60 15
If 1st < 2nd, compare 1st element with 3rd
10 15 20 30 40 60
element
If 1st > 2nd element, swap them.
Program:-
#include<stdio.h> Continue this process till all the elements are
#include<conio.h> in ascending order.
void main() Example:-
{ 4 2 3 1 5
clrscr();
int n, temp, i, j, a[10]; 2 4 3 1 5
printf(“enter number of elements”);
scanf(“%d”,&n); 2 4 3 1 5
printf(“enter the elements”);
for(i=0; i<n, i++)
1 4 3 2 5
{
scanf(“%d”,&a[i]);
}
For(i=0; i<s; i++)
{ 1 4 3 2 5
Temp = a[i];
J = i=1; 1 3 4 2 5
While( ( temp < a[j] ) && (j>=0) )
{ 1 2 4 3 5
A[j+1] = a[j];
J= j-1;
} O/p:-
A[j+1]=temp; Enter number of elements
} 1 2 4 3 5
6
printf(“answer=”);
for(i=0; i<n; i++) Enter elements 1 2 3 4 5
{ 20 10 60 40 30 15
printf(“%d”,a[i]);
Answer=10 15 20 30 40 60
}
getch(); 1 2 3 4 5
}
Prepared by V.Balamurugan, Assistant professor / Dept of IT
GE6151 – COMPUTER PROGRAMMING REG.2013 NOTES
Program:- Example:-
#include<stdio.h> 9 6 3 7 4 2 5 1
#include<conio.h>
void main()
{ 9 6 3 7 4 2 5 1
clrscr();
int n, temp, i, j, a[10];
printf(“enter number of elements”);
scanf(“%d”,&n); 9 6 3 7 4 2 5 1
printf(“enter the elements”);
for(i=0; i<n, i++)
{ 9 6 3 7 4 2 5 1
scanf(“%d”,&a[i]);
}
for(i=0; i<n; i++) 6 9 3 7 2 4 1 5
{
for(j=i+1; j<n; j++)
{
3 6 7 9 1 2 4 5
if(a[i] > a[j])
{
temp = a[i];
a[i]=a[j]; 1 2 3 4 5 6 7 9
a[j]=temp;
} Program:-
} Refer book page number: 3.44
}
printf(“answer=”); O/p:- 15. Differentiate entry checked and exit checked
for(i=0; i<n; i++) Enter number of elements conditional constructs with an example.
{ 5 (or)
printf(“%d”,a[i]); Differentiale WHILE loop and Do..WHILE loop
} Enter elements
4 2 3 1 5
constructs with an example.
getch();
}
Answer= 1 2 3 4 5 WHILE loop
Entry checked loop
Top-tested loop
Condition is checked at the entry
Advantages Disadvantages Loop will not execute if condition is FALSE
Easy technique Not suitable for large Execute loop until condition is satisfied
number of elements While(condition)
Simple method Slow process {
Suitable for small number of Body of the loop
elements }
Example:-
14. Explain merge sort with example #include<stdio.h>
It uses divide and conquer technique #include<conio.h> O/p:-
Any number of elements can be sorted void main() 0
The unsorted array is divided into smaller pieces. { 1
Divided until single element. clrscr(); 2
Then it is merged (joined) in the increasing order. int a=0; 3
Both dividing and merging is done recursively. while(a<5) 4
{
printf(“%d”,a);
Unsorted array Merge sort Sorted array a++;
}
getch();
}
Prepared by V.Balamurugan, Assistant professor / Dept of IT
GE6151 – COMPUTER PROGRAMMING REG.2013 NOTES
Do..While loop:-
Exit checked loop
Bottom tested loop
Condition is checked at the end
If condition is false, loop will execute one time
Execute the loop until the condition is true.
Do
{
Body of the loop;
} while(condition);
Example program:-
#include<stdio.h>
#include<conio.h> O/p:-
void main() 0
{ 1
clrscr(); 2
int a=0; 3
do 4
{
printf(“%d”,a);
a++;
} while(a<5);
getch();
}
16. Write a C program to generate Fibbonacci series
#include<stdio.h>
#include<conio.h>
void main()
{
clrscr();
int n, fib, f1, f2, i;
printf(“enter number of elements”);
scanf(“%d”,&n);
for(i=1; i<=n;i++)
{
fib = f1 + f2; O/p:-
Enter number of elements
printf(“%d”,fib);
7
f2 = f1;
f1 = fib;
0 1 1 2 3 5 8
}
getch();
}
Prepared by V.Balamurugan, Assistant professor / Dept of IT
GE6151 – COMPUTER PROGRAMMING REG.2013 NOTES
UNIT 4 Functions and Pointers
Part – A (2mark questions) 3. Define pointer in C.
A pointer is a variable that is used to store the
1. Define Function in C address of another variable
A function is a self-contained program, or a sub- It is declared with *
program of one or more statements which is used It is used to make the program small and save
to do some particular task. memory space
Types of functions: i)User defined, ii)pre-defined. Ex:-
2. What are pre-defined functions? Give ex. int a;
int *b;
Pre-defined functions are functions that are
b = &a;
created already and stored in the C – library.
They perform certain operations. 4. What is the use of pointers in C?
Ex: printf(), scanf(), getch(), sqrt(), cos(), sin().. To make the program simple
3. What is RETURN statement? To make the size of the program small.
It is used to return the control from calling function To save memory space
to the next statement in the program. To access array elements easily
It can also return some values. To pass information between function
Ex:- To increase the speed of execution of program
return; return 0; return(a+b); 5. Write the differences betweencall by value
4. What are the types of functions based on and call by reference.
return values?
(or) Call by value Call by reference
What are the types of function prototypes?
Values are passed in Address or pointers are
Function with arguments, with return values function call passed in function call
Function with arguments, without return values
Functions without arguments, with return values If the values of the formal If the values of the formal
Functions without arguments, without return values parameters changed, parameters changed,
5. Define recursion. values of the actual values of the actual
A function calls itself again and again parameters will not parameters will also
Until a condition is TRUE change change.
This process is called as Recursion. Part – B (8 and 16 mark questions)
Ex:-
function() 1. Write a C program to print the sum of digits of a
{ number using recursion.
function();
} #include<stdio.h>
#include<conio.h>
6. What are the advantages and disadvantages void main()
of recursion? {
clrscr();
Advantages Disadvantages int n, r, sum;
printf(“enter a number”);
Less number of Difficult to clear errors
scanf(“%d”,&n);
statements
while(n>0) O/p:-
It needs less number of Difficult to think the logic of { Enter a number
variables a function r = n % 10; 234
sum = sum + r;
It is useful in branching Not easy to write code n = n /10;
process }
printf(“answer=%d”,sum);
getch();
}
Prepared by V.Balamurugan, Assistant professor / Dept of IT
GE6151 – COMPUTER PROGRAMMING REG.2013 NOTES
2. Explain predefined function and user-defined 3. Explain function prototypes with an example.
function with an example. Function with arguments, with return values
Pre-defined function:- Function with arguments, without return values
Pre-defined functions are functions that are Functions without arguments, with return values
created already and stored in the C – library. Functions without arguments, without return values
They perform certain operations.
Ex: printf(), scanf(), sqrt(), cos(), sin(), … Function with arguments, with return values:-
This type of function contains arguments and return values.
stdio.h printf() To print to the console output Return statement is used, arguments are used.
scanf() To get values from user Called function will return some value to the calling function
getch() To stay in console screen until Program:-
a key is pressed #include<stdio.h>
string.h strlen() To find length of a string #include<conio.h>
strrev() To reverse a string int add(int, int);
void main()
strcmp() To compare two strings {
math.h sin() To perform sine operation clrscr();
cos() To perform cosine operation int a = 5, b = 10;
sqrt() To perform square root operation printf(“%d”, add ( a, b) );
stdlib.h malloc() To allocate memory getch();
O/p:-
}
exit() To exit the execution
int add(int a, int b) 15
{
Example program:-
return a+b;
#include<stdio.h> }
O/p:-
#include<conio.h> Function with arguments, without return values:-
Mechanical This type of function contains arguments and no return values.
#include<string.h> 10
#include<math.h> Return statement is not used, arguments are used.
100 Called function will not return any value to the calling function
void main() 4 Program:-
{
#include<stdio.h>
clrscr(); #include<conio.h>
printf(“%d”, printf(“Mechanical”) ); void add(int, int);
printf(“%d”, sqrt ( 10 ) ); void main()
printf(“%d”, strlen(“mech”) ); {
getch(); clrscr();
exit(0); int a = 5, b = 10;
} add ( a, b);
User defined function:- getch();
O/p:-
They are defined by the user }
User can create their own function void add(int a, int b) 15
{
Function prototype should be mentioned before Printf(“%d”,a+b);
main() function }
They perform certain operations. Function without arguments, with return values:-
#include<stdio.h> This type of function contains no arguments, with return values.
#include<conio.h> Return statement is used, arguments are not used
int add(int, int); Called function will return some value to the calling function
void main() Program:- int add()
{ {
#include<stdio.h>
clrscr(); return a+b;
#include<conio.h>
printf(“%d”, add(10, 20) ); }
int add();
getch(); O/p:- void main()
}
{ O/p:-
int add ( int a, int b) 30
clrscr();
{ 15
printf(“%d”,add() );
return a+b ;
getch();
}
}
Prepared by V.Balamurugan, Assistant professor / Dept of IT
GE6151 – COMPUTER PROGRAMMING REG.2013 NOTES
Function without arguments, without return values:- 5._Write a C program to sort the array elements in
This type of function contains no arguments, no return values. ascending order
Return statement and argument are not used. #include<stdio.h>
Called function will not return any value to the calling function #include<conio.h>
Program:- void sort(int *, int);
#include<stdio.h> void main()
#include<conio.h> {
void add();
clrscr();
void main()
{ int n, a[10], i;
clrscr(); printf(“enter number of elements”);
add ( a, b) ; scanf(“%d”,&n);
getch(); printf(“enter elements”);
O/p:-
} for(i = 0; i < n; i++)
void add() 15 {
{ scanf(“%d”,&a[i]);
int a = 5, b = 10; }
printf(“%d”,a+b); sort(a,n);
} getch();
}
4._Explain recursion with an example.
void sort( int a[], int n)
(or)
{
Write a program to find the factorial of a number using
int i, j, temp;
recursion.
for(i = 0; i<n; i++) O/p:-
A function calls itself again and again
{ Enter number of elements
Until a condition is TRUE 5
for( j = 0; j<n; j++)
This process is called as Recursion. { Enter elements
Ex:- if ( a[j] > a[j+1])
6 2 3 8 9
function() { Answer = 2 3 6 8 9
{ temp = a[j];
function(); a[j] = a[j+1];
} a[j+1]=temp;
}
Advantages Disadvantages }
}
Less number of Difficult to clear errors printf(“answer = “);
statements for( i = 0; i < n; i++)
{
It needs less number of Difficult to think the logic of printf(“%d”, a[i]);
variables a function }
}
It is useful in branching Not easy to write code
process
6. Write a C program to explain pointers.
A pointer is a variable that is used to store the
Program:- int factorial(int n)
address of another variable
#include<stdio.h> {
#include<conio.h> if ( n = = 1) It is declared with *
int factorial ( int);
return 1; It is used to make the program small and save
else memory space
void main() return (n*factorial(n-1) );
{ } Ex:-
clrscr(); int a;
int n, f; int *b;
printf(“enter a number”); O/p:- b = &a;
scanf(“%d”,&n); Enter a number 5
printf(“answer =”); Answer = 120
printf(“%d”,factorial (n) );
getch();
}
Prepared by V.Balamurugan, Assistant professor / Dept of IT
GE6151 – COMPUTER PROGRAMMING REG.2013 NOTES
Use of pointers:- Pointer addition:- Pointer subtraction:-
To make the program simple #include<stdio.h> #include<stdio.h>
To make the size of the program small. #include<conio.h> #include<conio.h>
To save memory space void main() void main()
{ {
To access array elements easily
clrscr(); clrscr();
To pass information between function int a = 5, b = 10; int a = 5, b = 10;
To increase the speed of execution of program int *x, *y; int *x, *y;
Program:- x = &a, y = &b; x = &a, y = &b;
printf(“%d”, (*x + *y)); printf(“%d”, (*x - *y));
#include<stdio.h> getch(); getch();
#include<conio.h> } }
void main()
{ O/p:- O/p:- O/p:-
clrscr();
5 15 -5
int a;
int *b; 5 8. Explain call by value and call by reference.
a = 5;
b = &a; fff0 Call by value Call by reference
printf(“%d”,a); Values are passed in Address or pointers are
fff0
printf(“%d”,*b); function call passed in function call
printf(“%x”,&a);
If the values of the formal If the values of the formal
printf(“%x”,b);
parameters changed, parameters changed,
getch();
} values of the actual values of the actual
7._Explain pointer arithmetic in C. parameters will not parameters will also
(or) change change.
Explain the arithmetic operations using pointers in C. Slow process Fast process
There are four arithmetic operations that can be Different memory Same memory locations
done using pointers. They are:- locations used used
++ Pointer increment No chance or wrong Chances of wrong
-- Pointer decrement calculation calculation
+ Pointer addition Program:- Program:-
- Pointer subtraction #include<stdio.h> #include<stdio.h>
#include<conio.h> #include<conio.h>
void swap(int, int); void swap(int, int);
Pointer increment:- Pointer decrement:-
void main() void main()
#include<stdio.h> #include<stdio.h>
{ {
#include<conio.h> #include<conio.h>
clrscr(); clrscr();
void main() void main()
int a=5, b=10; int a=5, b=10;
{ {
printf(“before %d%d”,a,b); printf(“before %d%d”,a,b);
clrscr(); clrscr(); swap(a,b); swap(&a,&b);
int a[3] = { 10, 20, 30 }; int a[3] = { 10, 20, 30 }; printf(“after %d%d”,a,b); printf(“after %d%d”,a,b);
int i, *ptr; int i, *ptr; getch(); getch();
ptr = a; ptr = a; } }
for(i = 0; i < 3; i++) for(i = 3; i > 0; i - -) void swap(int x, int y) void swap(int *x, int *y)
{ { { {
printf(“address=%x”,ptr); printf(“address=%x”,ptr); int t; int t;
printf(value=%d”,*ptr); printf(value=%d”,*ptr); t = x; t = *x;
ptr++; ptr++; x = y; *x = *y;
} } y = t; *y = t;
getch(); getch(); printf(“inside %d%d”,x,y); printf(“inside %d%d”,*x, *y);
} } } }
O/p:- O/p:- O/p:- O/p:-
Address = fff0 value=10 Address = fff4 value=30 Before 5 10 Before 5 10
Address = fff2 value=20 Address = fff2 value=20 Inside 10 5 Inside 10 5
Address = fff4 value=30 Address = fff0 value=10 After 5 10 After 10 5
Address = fff0 value=10 Address = fff0 value=10
Prepared by V.Balamurugan, Assistant professor / Dept of IT
GE6151 – COMPUTER PROGRAMMING REG.2013 NOTES
UNIT 5 Structures and Unions
Part – A (2mark questions) 5. What are the differences between a structure and
an union?
1. Define structure. Structure Union
It is a user define data type. Memory space allocated Memory space allocated for
It contains variables of different data type. for all members the highest size member
Variables inside the structure = structure members Each member has own All members share same
We can store int, float, char, etc in a struct memory space memory space
Memory space is created for all members It is used when all It is used when members
Struct keyword is used. members are are not accessed at same
Ex:- independently used time
struct student Members can be accessed Members cannot be
{ at the same time accessed at the same time
int roll; 6. What are the different types of storage classes in
char name[10]; C?
float marks; (or)
} What are the different types of variable scope?
2. What is the purpose of structures? Storage class Keyword
(or) Automatic variables auto
What is the use of structured data type? Static variables static
External variables extern
In arrays, same data type elements are stored. Register variables register
In struct, Different data type elements can be stored.
Difficult data types can be handled 7. Define preprocessor in C.
We can create pointers to the structure It is a program that converts C program with pre-
User can define their own data type. processor directives to the modified version
That modified version can be converted to object
3. Mention the differences between structure and
code by the compiler
arrays
It gives three facilities:-
Structure Array
o Include header files
Contains different data Contains same data type
o Macro expansion
type elements elements
o Conditional compilation
Dynamic memory Static memory allocation
allocation C Program Preprocessor Modified version
(.) dot operator is used to Array index is used to Of C program
access structure members access array members
It is not a pointer It is a base pointer
compiler
4. Define Union in C.
It is a user define data type
It contains variables of different data type Object code
Variables inside the union = union members 8. Write a C program to use macro expansion
We can store int, float, char, etc in an union #include<stdio.h>
Memory space is not created for all members. #include<conio.h>
Memory space is created for Highest Byte size #define area(r) (3.14* (r) * (r) )
member void main()
{
That memory will be shared by all members
clrscr();
Union keyword is used int r = 2;
Ex:- printf(“%f”, area(r) );
union student getch();
{ O/p:-
}
int roll; 12.56
char name[10];
float marks;
}
Prepared by V.Balamurugan, Assistant professor / Dept of IT
GE6151 – COMPUTER PROGRAMMING REG.2013 NOTES
9. What is the use of #define pre-processor? struct student
It is used to define a macro {
The substitution value should be mentioned char name[20];
The macro will be substituted by its value char reg[20];
Ex:- int avg;
char grade;
#include<stdio.h>
} s[50], *p;
#include<conio.h> printf(“enter number of students”);
#define a 10 scanf(“%d”,&n);
O/p:-
void main() for(i = 0; i < n; i + + )
{ 10 {
printf(“%d”,a); printf(“enter name”);
getch(); scanf(“%s”,s[i].name);
} printf(“enter register number”);
10. Define static storage class. scanf(“%s”,s[i].reg);
To declare variables statically printf(“enter average”);
scanf(“%d”,s[i].avg);
Static variables are stored in main memory
}
It can be used locally or globally p = s;
Static variables are automatically initialized to 0 for(p = s; p < s +n; p ++)
Ex:- {
#include<stdio.h> if(p - > avg < 50) p - > grade = ‘u’;
#include<conio.h> else if(p - > avg < 55) p - > grade = ‘e’;
void main() else if(p - > avg < 60) p - > grade = ‘d’;
{ O/p:- else if(p - > avg < 70) p - > grade = ‘c’;
847(garbage value) else if(p - > avg < 80) p - > grade = ‘b’;
int a;
static int b;
0 else if(p - > avg < 90) p - > grade = ‘a’;
else p - > grade = ‘s’;
printf(“%d”,a);
}
printf(“%d”,b); for(p = s; p < s +n; p ++)
getch(); {
} printf(“%s”, p - > name);
printf(“%s”, p - > reg);
Part-B ( 8 and 16 marks) printf(“%d”, p - > avg);
printf(“%c”, p - > grade);
1. What is a structure? Write a C program to create a }
mark sheet for students using structure. getch();
It is a user define data type. }
It contains variables of different data type. O/p:-
Variables inside the structure = structure members Enter number of students
We can store int, float, char, etc in a struct 2
Memory space is created for all members Enter name
Sachin
Struct keyword is used. Enter register number
Ex:- 001
struct student Enter average
{ 91
int roll;
char name[10]; Enter name
float marks; Tendulkar
} Enter register number
002
Program:- Enter average
#include<stdio.h> 82
#include<conio.h>
void main() Sachin 001 91 S
{ Tendulkar 002 82 A
int i, n;
Prepared by V.Balamurugan, Assistant professor / Dept of IT
GE6151 – COMPUTER PROGRAMMING REG.2013 NOTES
2. What is a structure? Write a C program to store 3. What are the storage classes in C? Explain them in
and display employee details using structure. detail with example.
It is a user define data type. Storage class Keyword
It contains variables of different data type. Automatic variables auto
Variables inside the structure = structure members Static variables static
We can store int, float, char, etc in a struct External variables extern
Memory space is created for all members Register variables register
Struct keyword is used. Automatic variables:-
Ex:- Ordinary variables
struct employee O/p:- Defined inside a function or a block
{ Enter number of employees Default storage class
char name[10]; 2 “auto” keyword is used
char id[10]; Its lifetime is, within that function or block
Enter name
float salary; Rahul
After execution, they are erased from memory.
} Enter ID Ex:-
Program:- 001 #include<stdio.h>
#include<stdio.h> Enter salary #include<conio.h>
#include<conio.h> 39000 void f1();
void main() void f2();
{ Enter name void main()
Dravid {
int i, n;
Enter ID
struct employee clrscr();
002
{ Enter salary int a = 10; O/p:-
char name[10]; 51000 printf(“%d”, a);
char id[10]; f1(); 10
float salary; Rahul 001 39000 associate f2();
20
char post[10]; Dravid 002 51000 chairman getch();
} s[50], *p; } 30
for(i = 0; i < n; i++) void f1()
{ {
printf(“enter name”); int a = 20;
scanf(“%s”,s[i].name); printf(“%d”,a);
printf(“enter ID”); }
scanf(“%s”,s[i].id);
void f2()
printf(“enter salary”);
{
scanf(“%f”,s[i].salary);
} int a = 30;
p = s; printf(“%d”,a);
for(p = s; p < s +n; p ++) }
{ Static variables:-
if (p - > salary < 10000) p - > post=”trainee”; To declare variables statically
else if(p - > salary <20000) p -> post=”executive”; Static variables are stored in main memory
else if(p - > salary <30000) p -> post=”associate”; It can be used locally or globally
else if(p - > salary <40000) p -> post=”director”; “static” keyword is used
else if(p - > salary <50000) p -> post=”manager”;
Static variables are automatically initialized to 0
else p -> post=”chairman”;
} Ex:-
for(p = s; p < s +n; p ++) #include<stdio.h>
{ #include<conio.h>
printf(“%s”, p - > name); void main()
printf(“%s”, p - > id); { O/p:-
printf(“%d”, p - > salary); int a; 847(garbage value)
printf(“%c”, p - > post); static int b; 0
} printf(“ %d ” ,a);
getch(); printf(“ %d ” ,b);
} getch();
}
Prepared by V.Balamurugan, Assistant professor / Dept of IT
GE6151 – COMPUTER PROGRAMMING REG.2013 NOTES
External variables:- Include header files:-
They are like global variables They are used to include header files
They can be used anywhere in the function Program will be linked with that header file
They are declared outside the functions Ex:- printf() and scanf() are present in “stdio.h”
They are declared before main() function #include<stdio.h> Printf() and scanf()
“extern” keyword is used #include<conio.h> Getch(), gets(), puts(), …
Ex:- #include<string.h> Strlen(), strrev(), strcmp(), …
#include<stdio.h> #include<math.h> Sin(), cos(), sqrt(), …
#include<conio.h>
int n = 10; O/p:- Macro expansion:-
void main() 10 It is defined by #define pre-processor directive.
{ Macro contains an item with its associated text.
clrscr(); In the program,macro will be substituted by its value
printf(“%d”, n);
This is called as Macro substitution
getch();
It is done before compilation of program.
}
#define To define a macro
Register variables:-
#undef To undefined a macro
They are stored in registers
Example:-
They are not stored in main memory
#include<stdio.h>
“Register” keyword is used
#include<conio.h>
For the purpose of fast access #define area(r) (3.14 * (r) * (r) )
More variables cannot be stored in register. void main()
Ex:- { O/p:-
#include<stdio.h> clrscr();
#include<conio.h> int r = 2;
12.56
O/p:-
void main() printf(“area = %f”, area(r) );
0
{ getch();
1
clrscr(); }
2
register int a = 1; 3 Conditional compilation:-
for(a=0;a<5;a++) 4 #ifdef If macro is defined
{ #ifndef If macro is not defined
printf(“%d”,a); #endif To end the macro “if”
} #if “if” conditional compilation
getch(); #elif “else if”
} #else “else”
4. What are pre-processor directives? Explain any
four directives with example. “#ifdef” and “#ifndef” #if...#elif...#else
It is a program that converts C program with pre- #include<stdio.h> #include<stdio.h>
processor directives to the modified version #include<conio.h> #include<conio.h>
That modified version can be converted to object void main() void main()
code by the compiler { {
It gives three facilities:- clrscr(); clrscr();
o Include header files #define A 10 #define A 10
o Macro expansion #ifdef A #if A<0
o Conditional compilation printf(“defined”); printf(“negative”);
#endif #elif A>0
C Program Preprocessor Modified version printf(“positive”);
Of C program #undef A #else
#ifndef A printf(“Zero”);
compiler printf(“undefined”); #endif
#endif O/p:- getch(); O/p:-
getch(); Defined } positive
Object code } undefined
Prepared by V.Balamurugan, Assistant professor / Dept of IT