0% found this document useful (0 votes)
7 views47 pages

Unit - I Programming in C

The document outlines the curriculum for a B.Sc. I Year I Semester course in Programming in C at Avanthi Degree & P.G College, covering computer fundamentals, programming concepts, and C language basics. It includes practical assignments and detailed explanations of computer components, memory hierarchy, and operating systems. The content is structured into units that progressively build on programming skills and concepts essential for computer science students.

Uploaded by

asrilaxmi7
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
7 views47 pages

Unit - I Programming in C

The document outlines the curriculum for a B.Sc. I Year I Semester course in Programming in C at Avanthi Degree & P.G College, covering computer fundamentals, programming concepts, and C language basics. It includes practical assignments and detailed explanations of computer components, memory hierarchy, and operating systems. The content is structured into units that progressively build on programming skills and concepts essential for computer science students.

Uploaded by

asrilaxmi7
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

Avanthi Degree & P.

G College
Narayanaguda –Hyderabad

Department of Computer Science


[Link]. I Year I Semester

Programming in C

Name : ________________________________

Roll No : ________________________________

Group : ________________________________

The expert in anything was once a beginner


Paper – I : Programming in C
Unit – I
Computer Fundamentals: Introduction of Computers, Classification of Computers, Anatomy of
a Computer, Memory Hierarchy, Introduction to OS, Operational Overview of a CPU.
Program Fundamentals: Generation and Classification of Programming Languages, Compiling,
Interpreting, Loading, Linking of a Program, Developing Program, Software Development.
Algorithms: Definitions, Different Ways of Stating Algorithms (Step-form, Pseudo-code,
Flowchart), Strategyfor Designing Algorithms, Structured Programming Concept.
Basics of C: Overview of C, Developing Programs in C, Parts of Simple C Program, Structure of a
C Program,Comments, Program Statements, C Tokens, Keywords, Identifiers, Data Types,
Variables, Constants,Operators and Expressions, Expression Evaluation–precedence and
associativity, Type Conversions.
Unit – II
Input-Output: Non-formatted and Formatted Input and Output Functions, Escape Sequences,
Control Statements: Selection Statements – if, if-else, nested if, nested if-else, comma operator,
conditional operator, switch; Iterative Statements–while, for, do-while; Special Control
Statement–goto, break, continue, return, exit.
Arrays and Strings: One-dimensional Arrays, Character Arrays, Functions from ctype.h, string.h,
Multidimensional Arrays.
Unit – III
Functions:
Concept of Function, Using Functions, Call-by-Value Vs Call-by-reference, Passing Arrays to
Functions, Score of Variables, Storage Classes, Inline Functions, and Recursion.
Pointers:
Introduction, Address of Operator (&), Pointer, Uses of Pointers, Arrays and Pointers, Pointers
and Strings, Pointers to Pointers, Array of Pointers, Pointer to Array, Dynamic Memory Allocation
Unit – IV
User-defined Data Types: Declaring a Structure (Union) and its members, Initialization Structure
(Union),Accessing members of a Structure (Union), Array of Structures (Union), Structures verses
Unions, Enumeration Types.
Files: Introduction, Using Files in C, Working with Text Files, Working with Binary Files, Files of
Records, Random Access to Files of Records, Other File Management Functions.

References :

1. Pradip Dey, Manas Ghosh, Computer Fundamentals and Programming in C (2e)

1
Practical : Programming in C Lab

1. Write a program to find the largest two (three) numbers using if and conditional
operator.
2. Write a program to print the reverse of a given number.
3. Write a program to print the prime number from 2 to n where n is given by user.
4. Write a program to find the roots of a quadratic equation using switch statement.
5. Write a program to print a triangle of stars as follows (take number of lines from user):
*
***
*****
*******
*********
6. Write a program to find largest and smallest elements in a given list of numbers.
7. Write a program to find the product of two matrices..
8. Write a program to find the GCD of two numbers using iteration and recursion.
9. Write a program to illustrate use of storage classes.
10. Write a program to demonstrate the call by value and the call by reference concepts.
11. Write a program that prints a table indicating the number of occurrences of each
alphabet in the text entered as command line arguments.
12. Write a program to illustrate use of data type enum.
13. Write a program to demonstrate use of string functions string.h header file.
14. Write a program that opens a file and counts the number of characters in a file.
15. Write a program to create a structure Student containing fields for Roll No., Name, Class,
Year and Total Marks. Create 10 students and store them in a file.
16. Write a program that opens an existing text file and copies it to a new text file with all
lowercase letters changed to capital letters and all other characters unchanged.

2
Unit – I
Chapter – 1
Computer Fundamentals

1.1 Introduction to Computers:


Computer is an electronic device that receives input , stores or processes the input as per
user instructions and provides output in desired format.
(OR)
A computer can take data from the user through input devices (Input), process the user
given data (Processing), produces the result to the user through output devices (Output)and
stores data (Information) for future use.

Every computer mainly consists of three things and those are...


1. Hardware
2. Software
3. User

Here the user interacts with the software, and the software makes the computer hardware
parts to work for the user.

1.1.1 History of Computers (Evolution of Computers) :


• Abacus is the first mechanical calculating device, which was developed by Egyptians in
10th century B.C, but the final shape was given in 12th century A.D.

• Charles Babbage is called the "Father of the computer”. The First mechanical computer
designed by Charles Babbage was called Analytical Engine. It includes some features
which is used in today’s computers.

1.1.2 Generations of Computers :


Following table shows the technology used in the different generations of computers. With
advancement in the generation, the performance of computers improved not only due to
the implementation of better hardware technology but also superior operating systems and
other software utilities.

3
Generation Operating Year Of
Technology Specific Computers
Number System introduction
1 Vacuum Tube None 1945 Mark 1
IBM 1401, ICL 1901, B5000,
2 Transistor None 1956
MINSK-2
IBM S/360/370, UNIVAC
3 SSI and MSI Yes 1964 1100,
HP 2100A, HP 9810
ICL 2900, HP 9845A, VAX
4 LSI and VLSI Yes 1971 11/780, ALTAIR 8800,
IBM PC
Artificial Present and
5 Yes –
Intelligence beyond

1.2 Classification of Computers:


Most designs of computers today are based on concepts developed by John von Neumann
and are referred to as the von Neumann architecture. Computers can be classified in variety
of ways on the basis of various parameters such as usage, cost, size, processing power, and
so on. The classification of computers is presented below based on their power and their
use.
1.2.1 Supercomputer :
➔ The highly calculation-intensive tasks can be effectively performed by means of
supercomputers.
➔ These are employed for specialized applications that require immense amounts of
mathematical calculations.
➔ For example, weather forecasting requires a supercomputer. Other uses of
supercomputers include animated graphics, fluid dynamic calculations, nuclear energy
research, and petroleum exploration.
Ex. PARAM (Parallel Machine) developed in India.
1.2.2 Mainframe :
➔ A very large and expensive computer capable of supporting hundreds, or even
thousands, of users simultaneously.
➔ Apart from providing multi-user facility, it can process large amounts of data at very
high speeds and support many input, output and auxiliary storage devices.
➔ These computers are very large in size, and expensive.
➔ The main difference between a supercomputer and a mainframe is that a
supercomputer can execute a single program faster than a mainframe, whereas a
mainframe uses its power to execute many programs concurrently.
➔ The IBM 370 and IBM 3090 are examples of mainframe computers.
4
1.2.3 Minicomputers :
➔ A minicomputer is powerful enough to be used by multiple users (between 10 to 100)
but is smaller in size and memory capacity and cheaper than mainframes.
➔ Minicomputers are also called mid-range systems.
➔ Corporation VAX and IBM AS/400 are examples of minicomputers.
1.2.4 Microcomputers :
➔ A computer with a microprocessor and its central processing unit is known as a
microcomputer
➔ It typically consists of a microprocessor chip, a memory system, interface units and
various I/O ports, typically resided in a motherboard. There are many types of
microcomputers available.
Desktop computer : A micro computer sufficient to fit on a desk.
Laptop computer : A portable microcomputer with an integrated screen and
keyboard.
Palmtop computer/Digital diary/Notebook/PDAs :
A hand-sized microcomputer having no keyboard. The screen serves both as an input
and output device.
1.3 Anatomy of a Computer :
A computer system is usually defined as a combination of hardware and software. Computer
hardware is the physical equipment. Software is the collection of programs that make the
hardware do its job.

The Block diagram of computer consists mainly

1.3.1 Hardware :
Hardware is the physical components of a computer that includes all mechincal, electrical,
electronic and magnetic parts attached to it. A computer consists of the following major
hardware components:
• Input and Output Devices
• Central Processing unit (CPU)
• Memory Unit and Storage devices
• Interface Unit
5
1. Input unit – Input unit is a unit that accepts any input device. The input device is used to
input data into the computer system.
Function of input unit:
• It converts the data based on the program into computer acceptable form
through an input interface.
• It supplies the converted instructions and data to the computer system for
further processing

Some examples of input devices include Keyboard, Mouse, Scanner, Touch screen, etc

Keyboard :
The most common input device is the keyboard. Keyboard
is like a type-writer. A keyboard, normally, consists of 104
keys.
These keys are classified into different categories
which are briefly described below.

Character keys: These keys include letters, numbers, and


punctuation marks. On pressing any character key, the
corresponding character is displayed on the screen.

Function keys There are 12 functional keys above the key


board which are used to perform certain functions
depending on the operating system or the software
currently being executed. These keys are placed at the top
of the key board and can easily be identified with the letter
F followed by a number ranging from 1 to 12.

Control keys : Alt, Ctrl, Shift, are control keys. It change the functionality of other keys . We
can call control keys as modifier keys.
Navigation keys : These include four arrows, Page Up and Page Down, Home and End. These
keys are normally used to navigate around a document or screen.
Toggle keys : Scroll Lock, Num lock, Caps Lock are three toggle keys. The toggle state is
indicated by three LEDs at the right-top side of the keyboard.
Miscellaneous keys : These keys include Insert, delete, escape, print Screen etc.

Mouse :
A mouse is the pointing device attached to a computer. It is used to move the cursor
around the screen and to point to an object (such as icon, menu, command button etc.) on the
computer video screen for the purpose of selecting or activating objects

6
Scanner :
A scanner is a device that captures pictures or documents so that they can be stored
in storage devices.

2. Output unit – The device that receives data from a computer system for display, physical
production, etc., is called output device. It converts digital information into
humanunderstandable form. For example, monitor, projector, headphone, speaker, printer,
etc..

Monitor :
Computer display devices are commonly known as Visual
Display Unit (VDU) or monitor. It operates on a principle
similar to that of a normal television set.
Various technologies have been used for computer monitors.
They are also of different sizes.
CRT (Cathode-ray tube) and LCD (liquid crystal display)
monitors are the two common types which are widely used.

Printer:
The printer is a device that prints any data, report, document,
picture, diagrams, etc.
Printers are categorized based on the physical contact of the
print head with the paper to produce a text or an image.
Ex: Laser Printer , Dot Matrix Printer, etc

3. Central Processing Unit (CPU) –


CPU is called the brain of a computer. An electronic circuitry that carries out the instruction
given by a computer program.

CPU can be sub classified into three parts.


i . Control unit (CU) ii. Arithmetic & Logic unit (ALU)
iii. Memory Unit (MU)

i. Control unit (CU) -


The control unit manages the various components of the computer. It reads instructions from
memory and interpretation and changes in a series of signals to activate other parts of the
computer. It controls and co-ordinate is input output memory and all other units.

ii. Arithmetic & Logic unit (ALU) –


The arithmetic logic unit (ALU), which performs simple arithmetic operation such as +,-, *, /
and logical operation such as >, <, =<, <= etc.

7
iii. Memory Unit (MU) –
Memory is used to store data and instructions before and after processing. There are
mainly two types of memory that are used in a computer system.
One is called primary memory and the other secondary memory.

Primary memory is the area where data and programs are stored while the program is being
executed along with the data. This memory accessed directly by the processor. Primary
Memory is also known as internal memory or main memory.

Secondary memory is used to store date permanently, which is also known as auxiliary
memory, stores a huge number of data bytes at a lesser cost than primary memory devices.

Function of CPU-
1. It controls all the parts and software and data flow of computer.
2. It performs all operations.
3. It accepts data from input device and it sends information to output device.
4. Executing programs stored in memory
5. It stores data either temporarily or permanent basis.
6. It performs arithmetical and logical operations.

Registers :
The register is a special, high-speed storage area within the CPU. All data must be
represented in a register before it can be processed.
For example, if two numbers are to be multiplied, both numbers must be in registers, and the
result is also placed in a register. (The register can contain the address of a memory location
where data is stored rather than the actual data itself.)

Unit of memory:
A computer system uses binary numbers to store and process data. The binary digits 0 and 1,
which are the basic units of memory, are called bits. Further, these bits are grouped together to
form words.
A 4-bit word is called a Nibble. Examples of nibble are 1001, 1010, 0010, etc.
A two nibble word, i.e., 8-bit word is called a byte, for example, 01000110, 01111100, 10000001,
etc.
Table 1.1 shows different measurement units for digital data stored in storage devices.

8
1.4 Memory Hierarchy:
The various types of memory used in a computer system differ in speed, cost, size, and volatility
(permanence of storage). They can be organized in a hierarchy.

Above Figure shows that on moving down the hierarchy, the cost per bit of storage decreases
but access times increases (i.e., devices are slow). In other words, from top to bottom, the speed
decreases while the capacity increases and the prices become much lower.
The various memories specified in the hierarchy, those above the secondary memory are volatile
and the rest are non-volatile.

9
1.5 INTRODUCTION TO OPERATING SYSTEMS

➔ An operating system may be defined as a system software which acts as an


Intermediary or Interface between USER and Hardware.
➔ The operating system is a collection of programs that control the operation of all
hardware and other resources in the computer system.
➔ The common functions of an operating system includes –
Process(or) management
Memory management
Device management
File management

Process(or) management :
➔ Program at the execution is called process.
➔ The operating system decides which process gets to run, for how long and
perhaps at what priority or level of importance.

Memory management :
➔ Memory management refers to management of primary memory or main memory
➔ Operating System also Manages the Memory of the Computer System means Provide
the Memory to the Process and Also Deallocate the Memory from the Process.
➔ It allocates the memory when a process requests and deallocates the memory when
a process has been terminated.
Device management :
➔ The operating system allocates the various devices to the processes and initiates the
I/O operation.
➔ It also controls and schedules accesses to the input/output devices among the
processes.
File management :
➔ A file is just a sequence of bytes.
➔ Files are storage areas for programs, source codes, data, documents etc.

10
➔ The file system is an operating system module that allows users and programs to
create, delete, modify, open, close, and apply other operations to various types of
files.
➔ It also allows users to give names to files, to organize the files

Apart from these functions, an operating system must provide the facilities for controlling the
access of programs, processes, memory segments, and other resources.

➔ The kernel is that part of operating system that interacts with the hardware directly.
➔ Kernel is small in size but it provides the essential services require to operating
system and application.
➔ Mostly the kernel is responsible for memory managements, process management
and device management.

1.6 OPERATIONAL OVERVIEW OF A CPU

➔ Any processing executed by central processing unit is directed by the instruction.


➔ The processing required for a single instruction is called an instruction cycle.
➔ Instruction cycle follows the four steps those are fetch, decode, execute, and store.

1.7 Software
• Software refers to the instructions, or programs, that tell the hardware what to do.
• set of instructions is called a computer program.
• Software guides the computer at every step where to start and stop during a particular
job. The process of software development is called programming.
• Computer software is normally classified into two broad categories.
Application Software & System software
11
Application Software:

➔ It is designed to perform specific usage of user


➔ They are two categories of application softwares. They are Custom Software and Pre
Written Software Packages
➔ Software that is developed for a specific users or organisations with the users need is
called custom software.
➔ Pre written software package is ready to use and pre defined specifications that may
or may not meet the user requirement.

Ex: DBMS Software, Page Maker , MS Office.

System Software:

➔ System software may be defined as a set of one or more programs designed to control
the operation of computer system.
➔ System software are general programs designed for performing tasks such as
controlling all operations required to move data into and out of the computer. It
communicates with printers, card reader, disk, tapes etc.
➔ System Software allows application packages to be run on the computer with less time
and effort. Remember that it is not possible to run application software without system
software.
Ex: Loader , Linker, Operating Systems, etc.

12
Chapter – 2
Program Fundamentals
2.1 Generation and Classification of Programming Languages
➔ Programming Language is a formal language design to communicate and instruction to
the computer.
➔ Every computer programming language contains a set of predefined words and a set of
rules (syntax) that are used to create instructions of a program.
➔ Generations of Programming Languages classified based on the level of interaction with
the machine.
There are five generation of Programming languages. They are:

1) First Generation Languages (Machine Language)


2) Second Generation Languages (Assemble Language)
3) Third Generation Languages (High-Level Language)
4) Fourth Generation Languages (Non-procedural languages)
5) Fifth Generation Language (Natural Languages)
2.1.1 Machine Language ( First Generation Languages )
➔ Machine Language is considered as First Generation Language.
➔ The instructions in Machine Language are written in the form of Binary Codes that can
immediately executed by the processor.
➔ Machine Language is the native language of computer. Processor(CPU) can directly
executing machine language instructions.

A sample code in machine language is shown below:


0001000000000010011101100001100
➔ Machine language is faster in executions since the computer directly starts executing it
but at the same time it is very difficult to write and understand

2.1.2 Assembly Language ( Second Generation Languages )


➔ As it was very difficult to generate code in machine language, the assembly language was
developed which consisted of small meaningful terms. This is considered to be the second
generation language.
➔ An example of an assembly language program for adding two numbers X and Y and storing
the result in some memory location:

LDA A Load value of A in accumulator


ADD B Add value of B in the value of accumulator
OUT A Display the content of accumulator on output device

13
➔ A machine cannot execute an assembly languages program directly as it is not in a binary
form. An assembler is needed in order to translate an assembly language program into
the object code executable by the machine.
A machine cannot execute an assembly languages program directly as it is not in a binary form.
An assembler is needed in order to translate an assembly language program into the object code
executable by the machine.

2.1.3 High Level Language ( Third Generation Languages )


➔ High-level languages are called third generation languages (3GLs).
➔ High-level programming languages were developed to make programming easier and less
error-prone.
➔ Languages like C, C++, COBOL, FORTRAN, BASIC, PASCAL etc., have instructions that are
similar to English language that makes it easy for a programmer to write programs and
identify and correct errors in them.
➔ Advantages of High level languages are Readability, Portability, Easy debugging and Ease
in development of software.
A high level source program must be translated first into a form which the machine can
understand; this is done by a software called Compiler.

2.1.4 Fourth Generation Languages ( Non-Procedural Language )


➔ The Fourth Generation Language (4GL) is a non-procedural language that allows the user
to simply specify what is wanted without describing the steps that the computer has to
follow to produce the result.
➔ A query language is used as a database user interface and hides the specific details of the
database from the user.
➔ Like third generation languages, fourth generation languages are mostly machine
independent. They are primarily used mainly for developing business applications.
➔ Most of the fourth generation languages can be easily learnt and employed by end-users.

2.1.5 Fifth Generation Languages ( Natural Language )


➔ Fifth generation programming languages will permit the user to give commands in a more
conversational way. These will use voice input devices rather than traditional keyboards
or pointing devices.
➔ Fifth generation languages are used mainly in artificial intelligence research. Example of
fifth generation languages: PROLOG, OPS5, and MERCURY are the best known fifth
generation languages.

14
2.2 Compilation Process
The compilation process can be divided into a number of phases
➔ In the first phase of compilation, termed as lexical analysis, each statement of a
program is analyzed and broken into individual lexical units termed tokens and
constructs a symbol table for each identifier.
➔ The second stage of translation is called syntax analysis; tokens are combined into
syntactic units according to the syntax or grammar of the source language.
➔ In the third stage of compilation, the parsed statements are analysed further to
make sure that the operators and operands do not violate source language
specifications
➔ Next, an intermediate representation of the final machine language code is
produced. Optionally, the intermediate code is optimized to produce an optimized
code.
➔ The last phase of translation is code generation whereby the optimized intermediate
code is converted into target code.

15
2.2.1 Translators
A program written in high-level language is called as source code. To convert the source code
into machine code, translators are needed.
A translator takes a program written in source language as input and converts it into a program
in target language as output.
It also detects and reports the error during translation.

Different type of translators


There are three types of translators, namely Assembler, Compiler and Interpreter.
Assembler: Assembler converts one assembly language statement into a single
machine language instruction.

Compiler: Compiler is a translator which is used to convert programs in high-level language to


low-level language. It translates the entire program and also reports the errors in source
program encountered during the translation.

Interpreter : Interpreter is a translator which is used to convert programs in high-level language


to low-level language. Interpreter translates line by line and reports the error once it
encountered during the translation process.
It directly executes the operations specified in the source program when the input is given by
the user.
It gives better error diagnostics than a compiler.

16
Differences between compiler and interpreter

SI. No Compiler Interpreter


1 Performs the translation of a program Performs statement by statement
as a whole. translation.
2 Execution is faster. Execution is slower.
3 Requires more memory as linking is Memory usage is efficient as no
needed for the generated intermediate intermediate object code is
object code. generated.
4 Debugging is hard as the error It stops translation when the first
messages are generated after scanning error is met. Hence, debugging is
the entire program only. easy.
5 Programming languages like C, C++ uses Programming languages like Python,
compilers. BASIC, and Ruby uses interpreters.

Linker: It is the program which links the object code with some additional library files (header
files) and creates executable file with .exe extension.

➔ This executable directly runs on computer.


➔ Linking is automatically performed when the program is executed.
Loader: Loader is a System Software, Loading is the process of bringing a program from
secondary memory into main memory.

2.3 Developing a Program


Seven important steps towards creating effective programs:
1. Define the problem.
2. Design the problem solution.
3. Code the program
4. Test the program
5. Documentation of the program
6. Implementation
7. Maintenance

17
2.4 Software Development
• Software development is more than programming. A large number of people are involved
in software development.
• Programming is one of the activities of software development.
• Other activities include requirement analysis, design, testing, deployment, maintenance,
etc.

2.4.1 Steps in Software Development


The entire process of software development and implementation involves a series of steps.

Requirement Analysis
• Requirement analysis is a key part of the software development . Requirement analysis is
the activity is to collect all relevant information of developing software.
Design
• Design involves developing a logical model or basic structure of the new software. It
establishes overall system architecture.

Implementation
• The code for the different modules of the new software is developed according to the
design specifications for each module.

Testing
• Testing is the process of executing a program to find errors. To make
our software perform well it should be error-free.
Deployment
• Software deployment is the process that makes software available for use. Software
documentation is handled over to the users.
Maintenance
• Maintenance is the process of modifying a software product after it has been delivered
to the customer.

18
Chapter – 3
Algorithm
An algorithm is a step by step procedure for solving a problem. An algorithm is very useful for
finding the right answer to a problem or Breaking the difficult problem into simple cases.

Computer scientist Niklaus Wirth stated that

Program = Algorithms + Data

Steps for Algorithm Development:-


1. Initially understand the problem
2. Then, identify the expected output for the problem
3. Identify the necessary input for the problem.
4. Develop the logic that produces the expected output from the selected input.
5. Finally, test the algorithm with various set of inputs.
Characteristics of Algorithm
An Algorithm must process the following characteristics
1. Finiteness : An Algorithm should terminate in a finite number of steps
2. Definiteness : Each step of algorithm must be clear and unambiguous
3. Effectiveness : Each step must be effective, in the sense that, it should be easily
convertible into program statement and can be performed exactly in a finite amount
of time
4. Input : Each algorithm must take Zero, one or more quantities as input data
5. Output : Each algorithm must produce at least one output

For example, algorithm to add two numbers can be simply described in a few steps given below:
1. Start
2. Accept first number as A
3. Accept second number as B
4. Take a number C = A + B
5. Display C
6. End
19
Different ways of stating Algorithms
We can represent algorithm mainly in 3 ways. They are illustrated as follows.
1. Step-form
2. Pseudo Code
3. Flowchart

Step-Form:-

➔ Step form consists of the statements written sequentially.


➔ These statements represent a procedure in order to solve a problem.
➔ They will be in normal language
➔ Each statement solves the part of the problem.
➔ All the statements together solve the problem.

Example:- To count the pages in a book

1. Get Book
2. Open Book
3. Find next page
4. If there is no next page go to step7
5. Increment count
6. Go to Step3
7. Finish
Pseudo Code:-

➔ The word pseudo means imitation and code means instructions written some programming
language.
➔ Pseudo code describes the structure of program in simple English language.
➔ Pseudo code describes the complete logic of some program so that implementation become
easy
➔ It does not use any syntax or symbols.

Example: Adding two numbers


Step1: Start
Step2: Read input variable ‘A’.
Step3: Read input variable ‘B’.
Step4: compute the sum of A,B
Step5: Store the sum value in ‘C’.
Step6: Print value ‘C’
Step7: End

20
FLOWCHARTS:-

➔ A Flowchart is a type of diagram (graphical or symbolic) that represents an algorithm or


process.
➔ Each step in the process is represented by a different symbol and contains a short
description of the process step.
➔ The flow chart symbols are linked together with arrows showing the process flow
direction.
➔ A flowchart describes what operations (and in what sequence) are required to solve a
given problem
➔ Flowcharts are used in analyzing, designing, documenting or managing a process or
program in various fields
Flowchart Symbols & Guidelines:
Flowcharts are usually drawn using some standard symbols; however,
Some special symbols can also be developed when required.
Some standard symbols, which are frequently required for flowcharting many computer
programs are shown.

Terminator: An oval flow chart shape indicates the start or end of the process, usually
containing the word “Start” or “End”.

or

Process: A rectangular flow chart shape indicates a normal/generic process flow step.
For example, “Add 1 to X”, “M = M*F” or similar

Decision: A diamond flow chart symbol is used when a decision needs to be made,
commonly a Yes/No question or True/False test.

Connector: A small, labeled, circular flow chart shape used to indicate a jump in the
process flow. Connectors are generally used in complex or multi-sheet diagrams

Data: A parallelogram that indicates data input or output (I/O) for a process.
Examples: Get X from the user, Display X.

21
Arrow: used to show the flow of control in a process. An arrow coming from one symbol
and ending at another symbol represents that control passes to the symbol the arrow points
to.

Guidelines of Flow Chart:-

1. The flowchart should be neat, clear and easy to follow


2. It should contain both logical start and stop.
3. It should contain the steps that are required for execution in sequence.
4. The flowchart is to be read left to right or top to bottom.
5. A process symbol can have only one flow line coming out of it.

or

6. For a decision symbol, only one flow line can enter it, but multiple lines can leave it to denote
possible answers

Or

7. The terminal symbols can only have one flow line in conjunction with them.

Or

8. It should make use of connector symbol in case of complex flow charts in order to decrease the
number of flow lines.

Limitations of Using Flowcharts:

Although a flowchart is a very useful tool, there are a few limitations in using flowcharts
which are listed below:

❖ Complex logic: Sometimes, the program logic is quite complicated. In that case, flowchart becomes
complex and clumsy.
❖ Alterations and Modifications: If alterations are required the flowchart may require re-drawing
completely.
❖ Reproduction: As the flowchart symbols cannot be typed, reproduction of flowchart becomes a
problem

22
Advantages of Using Flowcharts:

The benefits of flowcharts are as follows:

❖ Communication : Flowcharts are better way of communicating the logic of a


system to all concerned.
❖ Effective analysis : With the help of flowchart, problem can be analyzed in more
effective way.
❖ Proper documentation: Program flowcharts serve as a good program
documentation, which is needed for various purposes.
❖ Efficient Coding : The flowcharts act as a guide or blueprint during the systems
analysis and program development phase.
❖ Proper Debugging : The flowchart helps in debugging process.

❖ Efficient Program Maintenance: The maintenance of operating program becomes easy with the
help of flowchart. It helps the
programmer to put efforts more
efficiently on that part.

Example 1: To find sum of two numbers

Pseudo Code Algorithm:-

Step 1: Start/begin
Step 2: Declare Num1, Num2 and Sum
Step 3: Read Num1 , Num2
Step 4: Sum Num1 + Num2
Step 5: Print or Display Sum
Step 6: Stop/End

23
Example 2: To find Area of Rectangle

Pseudo Code Algorithm:-


Declare Length , Breadth, Area,Peimeter
Step 1: Start/begin
Step 2: Declare Length, Breadth, Area
and Perimeter
Step 3: Read Length, Breadth
Step 4: Area Length * Breadth
Step 5: Perimeter 2*( Length + Breadth)
Step 6: Print or Display Area
Step 7: Print or Display Perimeter
Step 6: Stop/End

Example 3: Greatest of two numbers

Pseudo Code Algorithm:-

Step 1: Start/begin
Step 2: Read A,B
Step 3: if A>B then
Step 4: Print or Display ‘ A’ goto step7
Step 5: else go to step 6
Step 6: Print or Display ‘B’
Step 7: Stop

24
Example 4: Write an algorithm & Flow chart to find the largest among three different numbers entered by user.
Step 1: Start
Step 2: Declare variables a,b and c.
Step 3: Read variables a,b and c.
Step 4: If a>b
If a>c
Display a is the largest number.
Else
Display c is the largest number.
Else
If b>c
Display b is the largest number.
Else
Display c is the greatest number.
Step 5: Stop
.

25
Chapter – 4
Basics of C
4.1 Introduction to C / Overview of C
• C is a structured programming language. It is also known as function orientated
programming language. C programming language was developed in the year
of 1972 by Dennis Ritchie at Bell Laboratories in the USA (AT & T).
• In the year of 1968, research was started by Dennis Ritchie on programming languages
like BCPL, CPL. The main aim of his research was to develop a new language to create an
OS called UNIX. After four years of research, a new programming language was created
with solutions for drawbacks in languages like BCPL & CPL. In the year of 1972, the new
language was introduced with the name “Traditional C”.
• The name 'c' was selected from the sequence of previous language ‘B’ (BCPL) because
most of the features of 'c' were derived from BCPL (B language).
• The first outcome of the c language was the UNIX operating system. The initial UNIX OS
was completely developed using 'c' programming language.
• The founder of the ‘C’ language, Dennis Ritchie is known as “Father of C” and
also “Father of UNIX”.
• The c programming language is very popular because it is reliable, simple and easy to use
and it is the base for almost all the other programming languages.

Steps in the Development of a "C" Program


The “C” Programming execution requires the following steps:
• Create the Program.
• Compile the program
• Linking the program with functions that are needed from the “C” Library.
• Executing the C Program.

On a successful compilation of the source file (.c) generates an object file (.obj).The
Object file (.obj) is converted into a (.exe ) file for the execution of “C” Program .

26
4.1 C Program Basics / Structure of C Program
C is a structured programming language. Every c program and its statements must be in a
particular structure. Every c program has the following general structure.

Comments / Documentation Section


This section is used to provide a small description of the program. The comment lines are
simply ignored by the compiler, that means they are not executed.
In C, there are two types of comments.
1. Single Line Comments: Single line comment begins with // symbol. We can write
any number of single line comments.
2. Multiple Lines Comments: Multiple lines comment begins with /* symbol and ends
with */. We can write any number of multiple lines comments in a program.

Preprocessing Commands
Preprocessing commands are used to include header files and to define constants. We use
the #include statement to include the header file into our program. We use a #define statement
to define a constant.
Global Declaration
The global declaration is used to define the global variables, which are common for all the
functions after its declaration. We also use the global declaration to declare functions .
main()
Every C program must write this statement. This statement (main) specifies the starting point of
the C program execution.

27
Here, int is a data type of a value that is going to return to the Operating System after completing
the main method execution. If we don't want to return any value, we can use it as void.

Open Brace ( { )
The open brace indicates the beginning of the block which belongs to the main method. In C
program, every block begins with a '{' symbol.

Local Declaration
In this section, we declare the variables and functions that are local to the function or block in
which they are declared.

Executable statements
In this section, we write the statements which perform tasks like reading data, displaying the
result, calculations, etc

Closing Brace ( } )
The close brace indicates the end of the block which belongs to the main method. In C program
every block ends with a '}' symbol.

User-defined function()
This is the place where we implement the user-defined functions.

General rules for any C program


1. Every executable statement must end with a semicolon symbol (;).
2. Every C program must contain exactly one main method (Starting point of the program
execution).
3. All the system-defined words (keywords) must be used in lowercase letters.
4. Keywords can not be used as user-defined names(identifiers).
5. For every open brace ({), there must be respective closing brace (}).
6. Every variable must be declared before it is used.

4.2 C Tokens
Every C program is a collection of instructions and every instruction is a collection of some
individual units. Every smallest individual unit of a c program is called token. Every instruction in
a c program is a collection of tokens. Tokens are used to construct c programs and they are said
to the basic building blocks of a c program.
In a c program tokens may contain the following...

28
1. Keywords
2. Identifiers
3. Special Symbols
4. Constants
5. Strings
6. Data values

4.2.1 Keywords

Keywords are the reserved words with predefined meaning which already known to the
compiler.

Properties of Keywords
1. All the keywords in C programming language are defined as lowercase letters so they
must be used only in lowercase letters
2. Every keyword has a specific meaning, users can not change that meaning.
3. Keywords can not be used as user-defined names like variable, functions, arrays,
pointers, etc...
4. Every keyword in C programming language represents something or specifies some
kind of action to be performed by the compiler.

4.2.2 Identifiers
An identifier is a collection of characters which acts as the name of variable, function, array,
pointer, structure, etc...
In other words, an identifier can be defined as the user-defined name to identify an entity
uniquely in the c programming language that name may be of the variable name, function name,
array name, pointer name, structure name or a label.

29
Example
int marks;
char studentName[30];

Here, marks and studentName are identifiers.

Rules for Creating Identifiers


1. An identifier can contain letters (UPPERCASE and
lowercase), numerics & underscore symbol only.
2. An identifier should not start with a numerical value. It can start with a letter or an
underscore.
3. We should not use any special symbols in between the identifier even whitespace.
However, the only underscore symbol is allowed.
4. Keywords should not be used as identifiers.
5. There is no limit for the length of an identifier. However, the compiler considers the
first 31 characters only.
6. An identifier must be unique in its scope.

4.2.3 Data types


Data types are used to specify what kind of value can be stored in a variable. The memory size
and type of the value of a variable are determined by the variable data type.

In the c programming language, data types are classified as follows...

1. Primary data types (Basic data types OR Predefined data types)


2. Derived data types (Secondary data types OR User-defined data types)
3. User defined data types
4. Void data type

30
[Link] Primary Data types
The primary data types in the C programming language are the basic data types. All the primary
data types are already defined in the system. Primary data types are also called as Built-In data
types. The following are the primary data types in c programming language...
1. Integer data type
2. Floating Point data type
3. Double data type
4. Character data type

Integer Data type


• The integer data type is a set of whole numbers. Every integer value does not have the
decimal value. We use the keyword "int" to represent integer data type in c.
• The integer data type is used with different type modifiers like short, long, signed
and unsigned. The following table provides complete details about the integer data
type.

Type Size (Bytes) Range

int 4 Bytes -2147483648 to 2147483647

Signed short int 2 Bytes -32768 to 32767

Unsigned short int 2 Bytes 0 to 65535

long int (signed) 4 Bytes -2147483648 to 2147483647

unsigned long int 4 Bytes 0 to 4294967295

31
Floating Point data types
Floating-point data types are a set of numbers with the decimal value. Every floating-point value
must contain the decimal value. The floating-point data type has two variants...

• float
• double

We use the keyword "float" to represent floating-point data type and "double" to represent
double data type in c. Both float and double are similar but they differ in the number of decimal
places. The float value contains 6 decimal places whereas double value contains 15 or 19 decimal
places.
The following table provides complete details about floating-point data types.

Type Size (Bytes) Range

float 4 Bytes 1.17549 × 10-38 to 3.40282 × 1038

double 8 Bytes 2.22507 × 10-308 to 1.79769 × 10308

long double 12 Bytes

Character data type


The character data type is a set of characters enclosed in single quotations. The following table
provides complete details about the character data type.

Type Size (Bytes) Range

char (signed char) 1 Bytes -128 to 127

Unsigned char 1 Bytes O to 255

void data type


The void data type means nothing or no value. Generally, the void is used to specify a function
which does not return any value. We also use the void data type to specify empty parameters of
a function.

32
4.2.4 Variables
Variable is a name given to a memory location where we can store different values of the same
datatype during the program execution.
A variable name may contain letters, digits and underscore symbol. The following are the rules
to specify a variable name...
1. Variable name should not start with a digit.
2. Keywords should not be used as variable names.
3. A variable name should not contain any special symbols except underscore(_).
4. A variable name can be of any length but compiler considers only the first 31
characters of the variable name.

Declaration Syntax:
datatype variableName;
Example
int num;
The above declaration tells to the compiler that allocates 4 bytes of memory with the
name num and allows only integer values into that memory location.

4.2.5 Constants
A constant is a named memory location which holds only one value throughout the program
execution. A constant can be of any data type like integer, floating-point, character, string
and double, etc.,

Integer constants
An integer constant can be a decimal integer or octal integer or hexadecimal integer. A decimal
integer value is specified as direct integer value whereas octal integer value is prefixed with 'o'
and hexadecimal value is prefixed with 'OX'.

Example
125 -----> Decimal Integer Constant O76 -----> Octal Integer Constant
OX3A -----> Hexa Decimal Integer Constant

Floating Point constants


A floating-point constant must contain both integer and decimal parts. Some times it may also
contain the exponent part. When a floating-point constant is represented in exponent form, the
value must be suffixed with 'e' or 'E'.
Example
The floating-point value 3.14 is represented as 3E-14 in exponent form.
33
Character Constants
A character constant is a symbol enclosed in single quotation. A character constant has a
maximum length of one character.
Example

'A'
'2'
'+'

String Constants
A string constant is a collection of characters, digits, special symbols and escape sequences
that are enclosed in double quotations.

We define string constant in a single line as follows...


"C notes by Santhosh"

4.3 Operators
An operator is a symbol used to perform arithmetic and logical operations in a program. That
means an operator is a special symbol that tells the compiler to perform mathematical or logical
operations. C programming language supports a rich set of operators that are classified as
follows.

1. Arithmetic Operators
2. Relational Operators
3. Logical Operators
4. Increment & Decrement Operators
5. Assignment Operators
6. Bitwise Operators
7. Conditional Operator
8. Special Operators

Arithmetic Operators (+, -, *, /, %)


The arithmetic operators are the symbols that are used to perform basic mathematical
operations like addition, subtraction, multiplication, division and percentage modulo. The
following table provides information about arithmetic operators.

34
Operator Meaning Example

+ Addition 10 + 5 = 15

- Subtraction 10 - 5 = 5

* Multiplication 10 * 5 = 50

/ Division 10 / 5 = 2

% Remainder of the Division 5%2=1

Relational Operators (<, >, <=, >=, ==, !=)


The relational operators are the symbols that are used to compare two values. That means the
relational operators are used to check the relationship between two values. Every relational
operator has two results TRUE or FALSE. In simple words, the relational operators are used to
define conditions in a program. The following table provides information about relational
operators.

Operator Meaning Example

< Returns TRUE if the first value is smaller than second value 10 < 5 is
otherwise returns FALSE FALSE

> Returns TRUE if the first value is larger than second value otherwise 10 > 5 is
returns FALSE TRUE

<= Returns TRUE if the first value is smaller than or equal to second 10 <= 5 is
value otherwise returns FALSE FALSE

>= Returns TRUE if the first value is larger than or equal to second 10 >= 5 is
value otherwise returns FALSE TRUE

== Returns TRUE if both values are equal otherwise returns FALSE 10 == 5 is


FALSE

!= Returns TRUE if both values are not equal otherwise returns FALSE 10 != 5 is
TRUE
Logical Operators (&&, ||, !)

The logical operators are the symbols that are used to combine multiple conditions into one
condition. The following table provides information about logical operators.

35
Operator Meaning Example

&& Logical AND - Returns TRUE if all conditions are TRUE 10 < 5 && 12 > 10
otherwise returns FALSE is FALSE

|| Logical OR - Returns FALSE if all conditions are FALSE 10 < 5 || 12 > 10 is


otherwise returns TRUE TRUE

! Logical NOT - Returns TRUE if condition is FLASE and !(10 < 5 && 12 >
returns FALSE if it is TRUE 10) is TRUE

Assignment Operators (=, +=, -=, *=, /=, %=)


The assignment operators are used to assign right-hand side value (Rvalue) to the left-hand side
variable (Lvalue). The assignment operator is used in different variants along with arithmetic
operators. The following table describes all the assignment operators in the C programming
language.

Operator Meaning Example

= Assign the right-hand side value to left-hand side variable A = 15

+= Add both left and right-hand side values and store the result into A += 10
left-hand side variable ⇒A = A+10

-= Subtract right-hand side value from left-hand side variable value A -= B


and store the result into left-hand side variable ⇒ A = A-B

*= Multiply right-hand side value with left-hand side variable value A *= B


and store the result into left-hand side variable ⇒ A = A*B

/= Divide left-hand side variable value with right-hand side variable A /= B


value and store the result into the left-hand side variable ⇒ A = A/B

%= Divide left-hand side variable value with right-hand side variable A %= B


value and store the remainder into the left-hand side variable ⇒ A = A%B

Conditional Operator (?:)


The conditional operator is also called a ternary operator because it requires three operands.
This operator is used for decision making.

36
In this operator, first we verify a condition, then we perform one operation out of the two
operations based on the condition result. If the condition is TRUE the first option is performed,
if the condition is FALSE the second option is performed.
The conditional operator is used with the following syntax.

Expression1? expression2: expression3;


(OR)

Condition ? TRUE Part : FALSE Part;

Example Program on Conditional Operator

#include <stdio.h>
int main()
{
int age;
printf("Enter your age : ");
scanf("%d",&age);
(age>=18)?(printf("Eligible for voting")):(printf("Not eligible
for voting"));
return 0;
}

Special Operators (sizeof, pointer, comma, dot, etc.)


The following are the special operators in c programming language.

sizeof operator
This operator is used to find the size of the memory (in bytes) allocated for a variable. This
operator is used with the following syntax.

sizeof(variableName);

37
Example Program on sizeof Operator

#include <stdio.h>
int main()
{
printf("Character size :%d Byte", sizeof(char));
printf("\nInteger size :%d Bytes", sizeof(int));
printf("\nFloat size :%d Bytes", sizeof(float));
printf("\n Double size :%d Bytes", sizeof(double));
return 0;
}

Pointer operator (*)


This operator is used to define pointer variables in c programming language.
Comma operator (,)
This operator is used to separate variables while they are declaring, separate the
expressions in function calls, etc.
Dot operator (.)
This operator is used to access members of structure or union.

Bit-Wise Operator (&, |, ^, ~, >>, <<)


The bitwise operators are used to perform bit-level operations in the c programming language.
When we use the bitwise operators, the operations are performed based on the binary values.
The following table describes all the bitwise operators in the C programming language.

One’s Compliment: - The ones complement operator is used to convert the bit from 1 to 0 and
0 to 1. The operator is used to represent ones compliment is called tilde (~) (takes only one’s
value).
e.g.: - A = 10100101 = (165)10
~A = 01011010 = (90)10

Bit-wise AND (&): - This operator is used to perform the AND operation between the bits. It is
representing with single ampersand (&).
Example: - if a=5 b=7

38
c= a & b
𝑎 = 0000 0101 {𝑏𝑖𝑛𝑎𝑟𝑦 𝑓𝑜𝑟𝑚 𝑜𝑓 5}
𝑏 = 0000 0111 {𝑏𝑖𝑛𝑎𝑟𝑦 𝑓𝑜𝑟𝑚 𝑜𝑓 7}
𝑐 = 0000 0101 {𝑏𝑖𝑛𝑎𝑟𝑦 𝑓𝑜𝑟𝑚 𝑜𝑓 5}
c=5

Bit-wise OR (|):
This operator is used to perform the OR operation between two bits. The operator used here is a single
pipe (|).
Syntax: - operand1 | operand2

Example: - if a=5 b=7


c= a | b
𝑎 = 0000 0101 {𝑏𝑖𝑛𝑎𝑟𝑦 𝑓𝑜𝑟𝑚 𝑜𝑓 5}
𝑏 = 0000 0111 {𝑏𝑖𝑛𝑎𝑟𝑦 𝑓𝑜𝑟𝑚 𝑜𝑓 7}
𝑐 = 0000 0111 {𝑏𝑖𝑛𝑎𝑟𝑦 𝑓𝑜𝑟𝑚 𝑜𝑓 7}
c=7
Left-Shift Operator: - (<<)
Left-Shift operators are used for shifting the bits towards the left side.
After shifting the bits, the remaining left over places are added with zeros, it is represented by
“<<”.
Syntax: - operand << value

Right-Shift Operator: - (<<)


Right-Shift operators are used for shifting the bits towards the Right side. After
shifting the bits, the remaining left most bits are filled with zeros, it is represented by “>>”.
Syntax: - operand >> value

Exclusive OR: - (X-OR)


The Exclusive OR operation is also called as X-OR operation. The operator results
into false if both the inputs are same and results into true if both the inputs are different. The truth table
for X-OR is
A b a^b
0 0 0
0 1 1
1 0 1
1 1 0
Example: - if a=5 b=7
c= a^b

𝑎 = 0000 0101 {𝑏𝑖𝑛𝑎𝑟𝑦 𝑓𝑜𝑟𝑚 𝑜𝑓 5}


𝑏 = 0000 0111 {𝑏𝑖𝑛𝑎𝑟𝑦 𝑓𝑜𝑟𝑚 𝑜𝑓 7}
𝑐 = 0000 0010 {𝑏𝑖𝑛𝑎𝑟𝑦 𝑓𝑜𝑟𝑚 𝑜𝑓 2}
c=2
39
4.3 Expressions
An expression is a collection of operators and operands that represents a specific value.

In the above definition, an operator is a symbol that performs tasks like arithmetic operations,
logical operations, and conditional operations, etc.
Operands are the values on which the operators perform the task. Here operand can be a direct
value or variable or address of memory location.

Expression Types in C
In the C programming language, expressions are divided into THREE types. They are as follows...

1. Infix Expression (Operand1 Operator Operand2)

2. Postfix Expression (Operand1 Operand2 Operator)

3. Prefix Expression (Operator Operand1 Operand2)

The above classification is based on the operator position in the expression .

4.4 Operator Precedence and Associativity

What is Operator Precedence?


Operator precedence is used to determine the order of operators evaluated in an expression. In
c programming language every operator has precedence (priority).
When there is more than one operator in an expression the operator with higher precedence is
evaluated first and the operator with the least precedence is evaluated last.

40
What is Operator Associativity?
Operator associativity is used to determine the order of operators with equal precedence
evaluated in an expression.
In the c programming language, when an expression contains multiple operators with equal
precedence, we use associativity to determine the order of evaluation of those operators.
In c programming language the operator precedence and associativity are as shown in the following table.

Precedence Operator Operator Meaning Associativity

() function call
[] array reference
1 Left to Right
-> structure member access
. structure member access

! negation
~ 1's complement
+ Unary plus
- Unary minus
++ increment operator
2 Right to Left
-- decrement operator
& address of operator
* pointer
sizeof returns size of a variable
(type) type conversion

* multiplication
3 / division Left to Right
% remainder

+ addition
4 Left to Right
- subtraction

<< left shift


5 Left to Right
>> right shift

< less than


<= less than or equal to
6 Left to Right
> greater than
>= greater than or equal to

== equal to
7 Left to Right
!= not equal to

41
Precedence Operator Operator Meaning Associativity

8 & bitwise AND Left to Right

9 ^ bitwise EXCLUSIVE OR Left to Right

10 | bitwise OR Left to Right

11 && logical AND Left to Right

12 || logical OR Left to Right

13 ?: conditional operator Left to Right

= assignment
*= assign multiplication
/= assign division
%= assign remainder
+= assign addition
14 -= assign subtraction Right to Left
&= assign bitwise AND
^= assign bitwise XOR
|= assign bitwise OR
<<= assign left shift
>>= assign right shift

15 , separator Left to Right

Example Program on Operator Precedence and Operator Associativity

#include <stdio.h>
int main ()
{
int x;
x = 10*20+110/5;
printf ("The Value of x = %d", x);
return 0;
}

42
4.5 Expression Evaluation
An expression is evaluated based on the precedence and associativity of the operators in that
expression.
To understand expression evaluation in c, let us consider the following simple example
expression...

10 + 4 * 3 / 2
In the above expression, there are three operators +, * and /. Among these three operators,
both multiplication and division have the same higher precedence and addition has
lower precedence.

It is evaluated as follows...
4 * 3 ====> 12
12 / 2 ===> 6
10 + 6 ===> 16
The expression is evaluated to 16.
Example Program on Expression Evaluation
#include <stdio.h>
int main()
{
printf("%d",10+4*3/2);
}

4.6 Type Casting and Conversion in C


In a programming language, the expression contains data values of the same datatype or
different data types. When the expression contains similar datatype values then it is evaluated
without any problem. But if the expression contains two or more different datatype values then
they must be converted to the single datatype of destination datatype.

In a c programming language, the data conversion is performed in two different methods as


follows...

1. Type Conversion
2. Type Casting
43
Type Conversion
The type conversion is the process of converting a data value from one data type to another data
type automatically by the compiler.
Sometimes type conversion is also called implicit type conversion. The implicit type conversion
is automatically performed by the compiler.

Typecasting
Typecasting is also called an explicit type conversion. Compiler converts data from one data type
to another data type implicitly. When compiler converts implicitly, there may be a data loss.
The general syntax of typecasting is as follows.
(TargetDatatype) DataValue

Example
int totalMarks = 450, maxMarks = 600 ;
float average ;

average = (float) totalMarks / maxMarks * 100 ;

Example 1 Program on Implicit Type Conversion


#include<stdio.h>
int main()
{
char alphabet = 'a';
printf("Character Value: %c\n", alphabet);
int number = alphabet;
printf("Integer Value: %d", number);
return 0;
}

44
Example 2 Program on Implicit Type Conversion
#include<stdio.h>
int main()
{
int num=10;
printf("Integer Value: %d\n", num);
float f=num;
printf("Float Value: %f", f);
return 0;
}

Example Program on Explicit Type Conversion


#include<stdio.h>
int main()
{
float f=10.67;
printf("Float Value: %f", f);
int num=(int)f;
printf("\nInteger Value: %d", num);
return 0;
}

45
Unit-I Questions
1. Computer ? Classification of Computers
2. Major Hardware Components of a computer / Anatomy of a computer.
3. Memory Hierarchy and Software and it types.
4. Operating System and Operations of CPU
5. Define Algorithm and explain in detail about different ways of
stating an algorithm
6. Write about “C” tokens and operators in detail
7. Structure of C Program
8. Expression , Operator precedence and Operator associativity
9. Datatypes with examples
10. Type Casting and Type Conversions in C with an example program.
11. Explain Flowchart in detail (Flowchart guidelines and
limitations).
12. Translators
13. Generations and Classifications of Programming Languages.

46

You might also like