0% found this document useful (0 votes)
4 views54 pages

cp unit 1 notes b r23 notes

Download as pdf or txt
Download as pdf or txt
Download as pdf or txt
You are on page 1/ 54

INTRODUCTION TO PROGRAMMING UNIT-I I-BTECH I-SEM BR23

UNIT I

(PART-A) Introduction to Programming


Computer System: History of Computers, Introduction to Components of Computer
System, Compilation and execution, Program Counter.
Basics of Computer Program- Programming Languages and History of C, Structure of
a Computer program, Software Development Process: Characteristics Algorithm,
flowchart, Pseudo Code, Header file, Errors in Compilation time, Primitive Data Types,
Formatted I/O’s, Format Modifier, Variables Rules, Keywords, Constants, Strings, and
Operators, Type Conversions, Priority Table
Problem Solving Strategies: Top-down and Bottom–up approach, Time and space
complexities.

History of Computers and Computer Generations

1. Discuss about Computer History and Computer Generations?


History of Computers:
A computer is an electronic device that manipulates information or data. It can store, retrieve,
and process data. Nowadays, a computer can be used to type documents, send an email, play
games, and browse the Web. It can also be used to edit or create spreadsheets, presentations,
and even video
Charles Babbage designed an Analytical Engine which was a general computer It helps us
understand the growth and progress of technology through the times. It is also an important topic
for competitive and banking exams.
Abacus:
The history of computer begins with the birth of abacus which is believed to be the first
computer. It is said that Chinese invented Abacus around 4,000 years ago. It was a wooden
rack which has metal rods with beads mounted on them.

Napier's Bones:
It was a manually-operated calculating device which was invented by John Napier (1550- 1617)
of Murchison. In this calculating tool, he used 9 different ivory strips or bones marked with
numbers to multiply and divide. So, the tool became known as "Napier's Bones. It was also the
first machine to use the decimal point.

Page 1
INTRODUCTION TO PROGRAMMING UNIT-I I-BTECH I-SEM BR23

Pascaline:
Pascaline is also known as Arithmetic Machine or Adding Machine. It was invented between
1642 and 1644 by a French mathematician-philosopher Biaise Pascal. It is believed that it was
the first mechanical and automatic calculator

Stepped Reckoner or Leibnitz wheel:


It was developed by a German mathematician-philosopher Gottfried Wilhelm Leibnitz in 1673.
He improved Pascal's invention to develop this machine. It was a digital mechanical calculator
which was called the stepped reckoner as instead of gears it was made of fluted drums.

Difference Engine:
In the early 1820s, it was designed by Charles Babbage who is known as "Father of Modern
Computer". It was a mechanical computer which could perform simple calculations. It was a
steam driven calculating machine designed to solve tables of numbers like logarithm tables.

Analytical Engine:
This calculating machine was also developed by Charles Babbage in 1830. It was a mechanical
computer that used punch-cards as input. It was capable of solving any mathematical problem
and storing information as a permanent memory.

Tabulating Machine:
It was invented in 1890, by Herman Hollerith, an American statistician. It was a mechanical
tabulator based on punch cards. It could tabulate statistics and record or sort data or
information. This machine was used in the 1890 U.S. Census. Hollerith also started the
Hollerith?s Tabulating Machine Company which later became International Business Machine
(IBM) in 1924.

Differential Analyzer
It was the first electronic computer introduced in the United States in 1930. It was an analog
device invented by Vannevar Bush. This machine has vacuum tubes to switch electrical signals
to perform calculations. It could do 25 calculations in few minutes.

Page 2
INTRODUCTION TO PROGRAMMING UNIT-I I-BTECH I-SEM BR23

Computer Generations: Computers have evolved significantly over the years,


and the history of computers is often divided into generations based on the technology used.
Here are the five generations of computers:
First Generation (1940s-1950s):
1946-1959 is the period of first generation computer.
J.P.Eckert and J.W.Mauchy invented the first successful electronic computer called
ENIAC, ENIAC stands for “Electronic Numeric Integrated And Calculator”.
The first computers used vacuum tubes for processing and magnetic drums for storage.
They were large, expensive, and unreliable.
Examples are: ENIAC, EDVAC, UNIVAC, IBM-701, IBM-650
Advantages:
1. It made use vacuum tubes which ar only electronic component available during those
days.
2. These computers could calculate in milliseconds.
Disadvantages:
1.These were very big in size, weight was about 30 tones.
2.These computers were based on vacuum tubes.
3. These computers were very costly.
4. Not reliable and constant maintenance is required.
5.Very less work efficiency.
6.Limited programming capabilities and punch cards were used to take inputs.
7.Large amount of energy consumption.

Second Generation (1950s-1960s): The second generation of computers replaced vacuum


tubes with transistors, making them smaller, faster, and more reliable. Magnetic core memory
was also introduced, which was faster and more reliable than magnetic drums.
1959-1965 is the period of second-generation computer.
Second generation computers were based on Transistor instead of vacuum tubes.
Few Examples are: Honeywell 400,IBM 7094,CDC 1604,CDC 3600,UNIVAC 1108
Advantages:
1.Less energy and not produce as much heat as the first generation.
2.Assembly language and punch cards were used for input.
3.Low cost than first generation computers.
4.Better speed, calculate data in microseconds.
Disadvantages:
1.A cooling system was required.
2.Constant maintenance was required.
3.Only used for specific purposes.

Third Generation (1960s-1970s): The third generation of computers used integrated circuits,
which allowed for even smaller and faster computers.They also introduced magnetic disk
storage and operating systems.
1965-1971 is the period of third generation computer.
These computers were based on Integrated circuits.
IC was invented by Robert Noyce and Jack Kilby In 1958-1959.
IC was a single component containing number of transistors.
Few Examples are: PDP-8,PDP-11,ICL 2900,IBM 360,IBM 370
Page 3
INTRODUCTION TO PROGRAMMING UNIT-I I-BTECH I-SEM BR23

Advantages:
1.These computers were cheaper as compared to second-generation computers.
2.They were fast and reliable.
3.Use of IC in the computer provides the small size of the computer.
4.This generation of computers has big storage capacity.
Disadvantages:
1. IC chips are difficult to maintain.
2. The highly sophisticated technology required for the manufacturing of IC chips.
3.Air conditioning is required.

Fourth Generation (1970s-1980s): The fourth generation of computers saw the introduction
of microprocessors, which made personal computers possible. They also introduced graphical
user interfaces and networking.
1971-1980 is the period of fourth generation computer.
This technology is based on Microprocessor.
A microprocessor is used in a computer for any logical and arithmetic function to be
performed in any program.
Graphics User Interface (GUI) technology was exploited to offer more comfort to users.
Few Examples are: IBM 4341,DEC 10,STAR 1000,PUP 11
Advantages:
1. Fastest in computation and size get reduced as compared to the previous generation of
computer.
2. Heat generated is negligible.
3. Small in size as compared to previous generation computers.
4.Less maintenance is required.
5.All types of high-level language can be used in this type of computers.
Disadvantages:
1. The Microprocessor design and fabrication are very complex.
2. Air conditioning is required in many cases due to the presence of ICs.
3.Advance technology is required to make the ICs.

Fifth Generation (1980s-Present): The fifth generation of computers is still ongoing, and
is focused on artificial intelligence and parallel processing. This generation also saw the
development of mobile computing and the internet.
The period of the fifth generation in 1980 onwards.
This generation is based on artificial intelligence.
The aim of the fifth generation is to make a device which could respond to natural
language input and are capable of learning and self-organization.
This generation is based on ULSI(Ultra Large Scale Integration) technology resulting in
the production of microprocessor chips having ten million electronic component.
Few Examples are: Desktop,Laptop,NoteBook,UltraBook,Chromebook
Advantages:
1. It is more reliable and works faster.
2. It is available in different sizes and unique features.
3. It provides computers with more user-friendly interfaces with multimedia features.
Disadvantages:
1. They need very low-level languages.
2. They may make the human brains dull and doomed.
Page 4
INTRODUCTION TO PROGRAMMING UNIT-I I-BTECH I-SEM BR23

Basic Components of Computer System


2. Explain about the Block Diagram of Computer System

Characteristics of a Computer:
1. Speed: Computers can perform millions of calculations per second. The computation
speed is extremely fast.
2. Accuracy: Because computers operate on pre-programmed software, there is no space
for human error.
3. Diligence: They can perform complex and long calculations at the same time and with
the same accuracy.
4. Versatile: Computers are designed to be versatile. They can carry out multiple
operations at the same time.
5. Storage: Computers can store a large amount of data/ instructions in its memory, which
can be retrieved at any point of time.
Components of a Computer: There are basically three components of a computer:
1. Input Unit
2. Central Processing Unit(CPU)
3. Output Unit
1. Input Unit The input unit consists of input devices that are attached to the computer. These
devices take input and convert it into binary language that computer understands. Some of the
common input devices are keyboard, mouse, joystick, scanner etc.
• The Input Unit is formed by attaching one or more input devices to a computer.
• A user input data and instructions through input devices such as a keyboard, mouse etc
2.Central Processing Unit(CPU): Once the information is entered into the computer by the
input device, the processor processes it.
The Central Processing Unit (CPU) is called "the brain of computer" as it controls operation of
all parts of computer. It consists of :Arithmetic Logic Unit (ALU), and Control Unit.

Page 5
INTRODUCTION TO PROGRAMMING UNIT-I I-BTECH I-SEM BR23

Arithmetic Logic Unit (ALU)


Data entered into computer is sent to RAM, from where it is then sent to ALU,
where rest of data processing takes place. All types of processing, such as comparisons,
decision-making and processing of non-numeric information takes place here and once again
data is moved to RAM.
• Arithmetic Logical Unit is the main component of the CPU
• It is the fundamental building block of the CPU.
• Arithmetic and Logical Unit is a digital circuit that is used to perform arithmetic and logical
operations.
Control Unit
As name indicates, this part of CPU extracts instructions, performs execution,
maintains and directs operations of entire system
• . The Control Unit is a component of the central processing unit of a computer that
directs the operation of the processor.
• It instructs the computer’s memory, arithmetic and logic unit, and input and output
devices on how to respond to the processor’s instructions.
• In order to execute the instructions, the components of a computer receive signals
from the control unit.
• It is also called the central nervous system or brain of the computer.
Functions of Control Unit
Control unit performs following functions −
• It controls all activities of computer
• Supervises flow of data within CPU
• Directs flow of data within CPU
• Transfers data to Arithmetic and Logic Unit
• Transfers results to memory
• Fetches results from memory to output devices

Memory Unit
This is unit in which data and instructions given to computer as well as results given
by computer are stored. Unit of memory is "Byte".
1 Byte = 8 Bits
• Memory Unit is the primary storage of the computer.
• It stores both data and instructions.
• Data and instructions are stored permanently in this unit so that they are available
whenever required.

3. Output Unit:
The output unit consists of output devices that are attached to the computer. It converts the
binary data coming from the CPU to human understandable form. The common output devices
are monitor, printer, plotter, etc.
• The output unit displays or prints the processed data in a user-friendly format.
• The output unit is formed by attaching the output devices of a computer.
• The output unit accepts the information from the CPU and displays it in a user-
readable form.

Page 6
INTRODUCTION TO PROGRAMMING UNIT-I I-BTECH I-SEM BR23

Operating Systems, Hardware and Software


3. What are the Operating Systems, Hardware and Software?
Operating System:
• Operating systems were first developed in the late 1950s to manage tape storage
• The General Motors Research Lab implemented the first OS in the early 1950s for
their IBM 701
• In the late 1960s, the first version of the Unix OS was developed
• The first OS built by Microsoft was DOS. It was built in 1981 by purchasing the 86-
DOS software from a Seattle company
• The present-day popular OS Windows first came to existence in 1985 when a GUI
was created and paired with MS-DOS.
Types of Operating System (OS):
Following are the popular types of OS (Operating System):
• Batch Operating System
. Multi-Programming Operating System
• Multitasking/Time Sharing OS
• Multiprocessing OS
• Real Time OS
• Distributed OS
• Network OS
• Mobile OS
1. Batch Operating System: Some computer processes are very lengthy and time-consuming.
To speed the same process, a job with a similar type of needs are batched together and run as
a group.
Advantages of Batch Operating System
• Multiple users can share the batch systems.
• The idle time for the batch system is very less.
• It is easy to manage large work repeatedly in batch systems.
Disadvantages of Batch Operating System
• The computer operators should be well known with batch systems.
• Batch systems are hard to debug.
• It is sometimes costly.
2. Multi-Programming Operating System: It can be simply illustrated as more than one
program is present in the main memory and any one of them can be kept in execution. This
is basically used for better execution of resources.
Advantages of Multi-Programming Operating System
• Multi Programming increases the Throughput of the System.
• It helps in reducing the response time.
Disadvantages of Multi-Programming Operating System
• There is not any facility for user interaction of system resources with the system.
3.Multi-Tasking/Time-sharing Operating systems:Time-sharing operating system enables
people located at a different terminal(shell) to use a single computer system at the same time.
The processor time (CPU) which is shared among multiple users is termed as time sharing.

Page 7
INTRODUCTION TO PROGRAMMING UNIT-I I-BTECH I-SEM BR23

4. Multi-Processing Operating System: It is a type of Operating System in which more than


one CPU is used for the execution of resources. It betters the throughput of the System.
Advantages of Multi-Procesing Operating System
• It increases the throughput of the system.
• As it has several processors, so, if one processor fails, we can proceed with another
processor.
Disadvantages of Multi-Processing Operating System
• Due to the multiple CPU, it can be more complex and somehow difficult to understand.
5. Real time OS: A real time operating system time interval to process and respond to inputs is
very small. Examples: Military Software Systems, Space Software Systems are the Real time
OS example.
Advantages of RTOS
• Maximum Consumption: Maximum utilization of devices and systems, thus more
output from all the resources.
• Focus on Application: Focus on running applications and less importance on
applications that are in the queue.
• Error Free: These types of systems are error-free.
• Memory Allocation: Memory allocation is best managed in these types of systems.
Disadvantages of RTOS
• Limited Tasks: Very few tasks run at the same time and their concentration is very
less on a few applications to avoid errors.
• Use heavy system resources: Sometimes the system resources are not so good and
they are expensive as well.
• Complex Algorithms: The algorithms are very complex and difficult for the designer
to write on.
6. Distributed Operating System: It is use many processors located in different machines to
provide very fast computation to its users.
Advantages of Distributed Operating System
• Electronic mail increases the data exchange speed.
• Load on host computer reduces.
• Delay in data processing reduces.
Disadvantages of Distributed Operating System
• Failure of the main network will stop the entire communication.
• To establish distributed systems the language is used not well-defined yet.
7. Network Operating System: It runs on a server. It provides the capability to serve to
manage data, user, groups, security, application, and other networking functions.
Advantages of Network Operating System
• Highly stable centralized servers.
• Security concerns are handled through servers.
• New technologies and hardware up-gradation are easily integrated into the system.
• Server access is possible remotely from different locations and types of systems.
Disadvantages of Network Operating System
• Servers are costly.
• User has to depend on a central location for most operations.
• Maintenance and updates are required regularly.

Page 8
INTRODUCTION TO PROGRAMMING UNIT-I I-BTECH I-SEM BR23

8. Time-Sharing Operating Systems: Each task is given some time to execute so that all the
tasks work smoothly. Each user gets the time of the CPU as they use a single system. These
systems are also known as Multitasking Systems. The task can be from a single user or
different users also. The time that each task gets to execute is called quantum.
Advantages of Time-Sharing OS
• Each task gets an equal opportunity.
• Fewer chances of duplication of software.
• CPU idle time can be reduced.
Disadvantages of Time-Sharing OS
• Reliability problem.
• One must have to take care of the security and integrity of user programs and data.
• Data communication problem.
9. Mobile OS:Mobile operating systems are those OS which is especially that are designed to
power smartphones, tablets, and wearables devices.
5.compiler and inaterpreter
Difference between hardware and software
Hardware Software

Hardware is further divided into four main Software is further divided into two main
categories: categories:

• Input Devices • Application Software


• Output Devices • System Software
• Secondary Storage Devices
• Internal Components

Developed using electronic and other Developed writing using instructions using a
materials programming language

When damaged, it can be replaced with a When damaged it can be installed once more
new component using a backup copy

Hardware is physical in nature and hence The software cannot be physically touched
one can touch and see hardware but still can be used and seen

Hardware cannot be infected by Viruses The software can be infected by Viruses

Hardware will physically wear out over Software does not wear out but it can be
time affected by bugs and glitches

An example of Hardware is hard drives, An example of software is Windows 10,


monitors, CPU, scanners, printers etc. Adobe Photoshop, Google Chrome etc.

Page 9
INTRODUCTION TO PROGRAMMING UNIT-I I-BTECH I-SEM BR23

Types of Computer Languages


4.Discuss about the different Types of Computer Languages

1. Low-Level Languages:
A low-level programming language is close in relation to a computer’s instruction set and
directly interacts with its hardware components to convert the orders into action.
a) Machine Language:
Machine Language:: Machine language is a code or object code composed of binary digits
(0s and 1s), which a computer system can easily interpret. It is a native language that the central
processing unit (CPU) directly understands and processes. However, it can be difficult to
understand machine language due to binary commands, thereby leading to different opinions
and results. It cannot understand programs and scripts in C, C++, and Java. Hence, acompiler
is needed to convert these computer scripts into machine language.
Example of machine language for the text “Hello World” using Binary Code:
01001000 0110101 01101100 01101100 01101111 00100000 01010111 01101111 01110010
01101100 01100100
Each group of eight ones and zeros is called a “byte.” In this case, each byte represents a
specific letter or character in the text.
Here’s a breakdown of what each byte represents in the machine language example for the
text “Hello World”:
• 01001000 -> ‘H’
• 0110101 -> ‘e’
• 01101100 -> ‘l’
• 01101100 -> ‘l’
• 01101111 -> ‘o’
• 00100000 -> ‘ ‘ (space)
• 01010111 -> ‘W’
• 01101111 -> ‘o’
• 01110010 -> ‘r’
• 01101100 -> ‘l’
• 01100100 -> ‘d’

Page 10
INTRODUCTION TO PROGRAMMING UNIT-I I-BTECH I-SEM BR23

So, when a computer reads this sequence of bytes in machine language, it understands that it
should display the text “Hello World” on the screen.
b) Assembly Language:
Assembly language:: It is simply a low-level programming language to write instructions for
microprocessors and various programmable devices. It is often referred to as a second-
generation language of computer, while machine language is the first-generation language.
Assembly language is common for writing scripts for operating systems and desktop
applications. It’s a low-level language of computer because it’s closer to the way computers
actually work.
Assembly language is easy to understand in comparison to machine language. The compiler
takes less time to translate the code, while the efficiency of the code’s execution is greater.

2. High-Level Languages:
The earlier types of computer language had portability issues, making it difficult to transfer
code from one machine to another. To address this, high-level languages were introduced.
Programmers started developing high-level languages to respond to the challenges of lower-
level language programs. These types of computer languages are designed to be user-friendly,
allowing programmers to write code quickly and easily.

Types of High-Level Languages


a) Procedural Language
A procedural language is a third-generation language easily created with simple procedures.
These procedures are instructions in a sequence with a unique name..
Here are some examples of popular procedural languages:
• C Language: C is widely useful for developers for developing system software, like
operating systems and device drivers. It is known for its efficiency in managing
hardware resources.
• Fortran: Fortran is commonly useful as a programming language for scientific
computing and numerical analysis. It has found extensive applications in fields such as
physics, engineering, and astronomy, and it remains relevant today.
• Pascal: Pascal is a procedural type of computer language designed to be easy to learn
and use. It is utilized for creating applications in various domains, including education,
engineering, and business.
• BASIC: BASIC (Beginner’s All-purpose Symbolic Instruction Code) was designed
with the goal of creating a procedural language that is beginner-friendly. It is commonly
useful for developing basic applications and educational programs.
• COBOL: COBOL (Common Business Oriented Language) is a procedural language
initially developed for business applications. It is still helpful today for developing
banking, insurance, and government applications.

b) Functional Language:
Functional language is a type of high-level language that revolves around mathematical
functions as their fundamental concept. Functional languages are particularly concise, clear,
and easily understandable. The Common applications are artificial intelligence and data
analysis. Here are some examples of popular functional languages:

Page 11
INTRODUCTION TO PROGRAMMING UNIT-I I-BTECH I-SEM BR23

• Haskell: Haskell is a purely functional language famous for its strong safety features
and its ability to handle complex mathematical operations. It finds applications in
various fields, including artificial intelligence, data analysis, and finance.
• Lisp: Lisp is one of the oldest functional languages still in use today. It is famous for
its flexibility and its capability to handle complex data structures. Lisp is employed in
the development of applications across domains such as artificial intelligence, robotics,
and game development.
• Erlang: Erlang is a functional language specifically for building concurrent and
distributed systems. It is extensively useful in the telecommunications industry for
creating messaging systems and other real-time applications.
• F#: F# is a functional language based on the .NET framework. It is notable in the
development of applications for various domains, including web development, game
development, and artificial intelligence.
• Clojure: Clojure, a functional programming language with roots in Lisp, offers
exceptional expressiveness and finds application in diverse fields such as web
development, data analysis, and machine learning.

c) Object-Oriented Programming Language:


Object-oriented programming languages have become the predominant approach indeveloping
new software. The development process in these languages revolves around creating and
interacting with objects, which consist of pieces of code (modules) and data structures.
Here are some examples of popular object-oriented languages:
• Java: Java is a widely useful object-oriented language for developing various
applications, including web applications, mobile applications, and games. It aims to
provide platform independence, allowing programs to run on different systems. Java
handles memory management automatically and is recognized for its security features
and the ability to run on multiple platforms.
• Python: Python is a widespread object-oriented language for data analysis, machine
learning, and artificial intelligence. It is popular for its user-friendly interface and
capacity to process large amounts of data efficiently.
• C++: C++ is an object-oriented language suitable for developing applications that
require high performance and low-level control, such as operating systems and game
engines. It is famous for its speed and efficiency.
• Ruby: Ruby is an object-oriented language commonly helpful for web development
and scripting. It is creative for its simplicity and straightforward design.
• Swift: Swift is an object-oriented language primarily for developing applications for
Apple devices, including iPhones and iPads. It prioritizes safety and is well-equipped
to handle complex applications.

d) Scripting Language:
Scripting languages are high-level languages to be user-friendly and easy to learn for
automating repetitive tasks and creating dynamic web pages. Developers prefer interpreted
scripting languages because they do not require compilation before execution, enabling quick
prototyping and testing.
Here are some of the common scripting languages:

Page 12
INTRODUCTION TO PROGRAMMING UNIT-I I-BTECH I-SEM BR23

• JavaScript: JavaScript is a common scripting language for creating dynamic and


interactive web pages. It is alongside HTML and CSS to build complex web
applications. JavaScript is also utilized in server-side development through platforms
like Node.js. It is well-known for its versatility and capability to run on various devices.
• Python: Python is a scripting language for various applications, such as web
development, data analysis, and artificial intelligence.. Python has wide usage in
scientific computing and machine learning domains.
• Perl: Perl is frequently in use as a scripting language for text processing, web
development, and system administration. It has powerful regular expressions and the
ability to handle complex data structures.
• Bash: Bash is a scripting language that is for shell scripting in Linux and Unix-based
operating systems. It serves as the default command-line shell and is a powerful
command-line interface, thereby enabling users to perform various tasks through simple
commands.

3. Specialized Languages:
Specialized languages are programming languages that are for specific uses or industries. They
have special features and rules that make them really good at solving certain kinds of problems.
a) Markup Language:
Markup languages are computer languages to format text for display on the web or in
documents. They employ tags and other markers to describe how text should be formatted or
displayed. The objective of markup languages is to ensure both machine and human readability.
Here are some common examples of Markup languages:
• HTML: HTML (Hypertext Markup Language) is a primary markup language for
designing web pages. It utilizes tags to structure and present information on a webpage,
including headings, paragraphs, links, images, and other essential elements. HTML is
widely and universally functioning with the support of web browsers.
• XML: XML (Extensible Markup Language) stores and exchanges data between
different systems. It utilizes tags to define data structure and content, enabling the
representation of complex data structures. Enterprise applications, data sharing, and
web services commonly use XML format.
• Markdown: Markdown is just a lightweight markup language that allows for easy text
formatting for the web. It uses plain text and simple tags to define headings, lists, links,
and other elements. It is widely for writing documentation, blog posts, and web content
due to its simplicity and readability.
b) Query Language:
Query languages are simply computer languages that retrieve and manipulate data from
databases. These types of computer language allow users to issue commands or statements in
order to edit or retrieve data based on specific criteria. Query languages find applications in
various fields, including business intelligence, data analytics, and web development.
• SQL: Structured Query Language (SQL) is commonly for managing relational
databases. It provides functionality to create, modify, and delete databases, tables, and
other objects, alongside query data stored in these databases. SQL has usage in
enterprise applications, web development, and data analytics.

Page 13
INTRODUCTION TO PROGRAMMING UNIT-I I-BTECH I-SEM BR23

• SPARQL: SPARQL (SPARQL Protocol and RDF Query Language) is a language for
querying data stored in RDF (Resource Description Framework) format. RDF is a
flexible data model that represents metadata, and SPARQL allows the manipulation
and retrieval of data in RDF format. SPARQL is quite useful in applications dealing
with large amounts of data, like data analytics and scientific research.
c) Domain-Specific Language:
Developers design Domain-Specific Languages (DSLs) for specific domains or problems to
simplify programming tasks by providing a language tailored to the needs of a particular
application. Multiple applications utilize domain-specific languages (DSLs), including
scientific computing, financial modeling, and game development.
• MATLAB: MATLAB is a domain-specific language for scientific computing and data
analysis. It provides a robust environment for numerical computation, visualization,
and programming. Scientists in various fields, including engineering and physics,
commonly use MATLAB.
• R Language: The R Language is primarily a domain-specific language in the field of
statistical computing and graphics. It is a widespread tool for data analysis andscientific
research. R Language is open-source and has a large and active community of users and
developers.

Parameters Low-level language High-level language

Definition Closely tied to the computer’s instruction set User-friendly and focuses on the proble
and directly interacts with hardware solving aspect of programming.
components.

Examples Machine language and Assembly language. Python, Java, C++, Ruby, and JavaScript.

Readability Difficult to read and write due to machine- Easily readable and writable by humans.
level instructions.

Portability Specific to a particular computer architecture, Portable and can run on any computer
not portable without rewriting.
with appropriate software.

Maintenance Difficult to debug and maintain due to Easier to debug and maintain due to a
closeness to hardware and requirement of deep
understanding of architecture. higher level of abstraction and readability.

Speed Faster due to direct access to hardware. Slower because translation into machine-le
code is necessary.

Page 14
INTRODUCTION TO PROGRAMMING UNIT-I I-BTECH I-SEM BR23

Compiler and Interpreter ,Compilation, Execution Process and


Program Counter

5. Discuss about the Compiler and Interpreter, Compilation,


Execution Process and Program Counter?
Compilers:
A compiler is a translator that produces an output of low-level language (like an assembly or
machine language) by taking an input of high-level language. It is basically a computer
program used to transform codes written in a programming language into machine code
(human-readable code to a binary 0 and 1 bits language for a computer processor to
understand). Compilers check all types of errors, limits, and ranges..
Interpreter:
It is a program that functions for the translation of a programming language into
comprehensible one. It is a computer program used for converting high-level program
statements into machine codes. It includes pre-compiled code, source code, and scripts.
• An interpreter translates only one statement at a time of the program.
• They create an exe of the programming language before the program runs.

Difference between Compiler and Interpreter


Parameter Compiler Interpreter

Steps of • Creation of the program. • Creation of the program.


Programming • The Compiler analyses all the • It doesn’t require the linking offiles
language statements and throws an or generation of machine code.
error when it finds something • It executes the source statements
incorrect. line by line during the execution.
• If there’s zero error, the compiler
converts the source code tomachine
one.
• It links various code files into a
runnable program (exe).
• It runs the program.

Advantage The code execution time is comparatively They are fairly easy to use and execute,
less because the program code already gets even for a beginner.
translated into machine code.

Disadvantage One can’t change a program without Only computers with the corresponding
getting back to the source code. Interpreter can run the interpreted
programs.

Machine Code It stores the machine language on the disk It doesn’t save the machine language at
in the form of machine code. all.

Page 15
INTRODUCTION TO PROGRAMMING UNIT-I I-BTECH I-SEM BR23

Running Time The compiled codes run comparatively The interpreted codes run comparatively
faster. slower.

Model It works on the basis of the language- It works on the basis of the Interpretation
translation linking-loading model. method.

Generation of It generates an output program in the exe It doesn’t generate an output program.
Program format. A user can run it independently Meaning, it evaluates the source program
from the originally intended program. every time during individual execution.

Execution One can separate the program execution Execution of the program is one of the
from the compilation. Thus, you can steps of the Interpretation process. So, you
perform it only after completing the can perform it line by line.
compilation of the entire output.

Memory Target programs execute independently. Interpreter originally exists in the memory
Requirement They don’t require the Compiler in the at the time of interpretation.
memory.

Dynamic Typing Compilers are very difficult to implement The Interpreted language supports
because they can’t predict anything that Dynamic Typing.
happens during the turn time.

Use It works best for the Production It works the best for the programming and
Environment. development environment.

Execution of A Compiler displays every error and An Interpreter reads every statement, then
Error warning while compiling. So, you can’t run displays the errors, if any. A user must
this program unless you fix the errors. resolve these errors in order to interpret the
next line.

Input A Compiler takes a program as a whole. An Interpreter takes single lines of a code.

Output The Compilers generate intermediate The Interpreters never generate any
machine codes. intermediate machine codes.

Errors This translator displays all the errors after It displays the errors of every single line
compiling- together at the same time. one by one.

Programming Java, Scala, C#, C, C++ use Compilers. Perl, Ruby, PHP use Interpreters.
Languages
TYPES OF COMPILERS
1. CROSS-COMPILER:A cross-compiler is one that runs on a computer whose CPU or
operating system differs from the one on which the code it produces will run.

Page 16
INTRODUCTION TO PROGRAMMING UNIT-I I-BTECH I-SEM BR23

2. NATIVE COMPILER:A native compiler produces an output that would run on the same
type of computer and operating system as the compiler itself.
3. BOOTSTRAP COMPILER:Bootstrap compiler is a compiler written in the language that
it intends to compile.
4. DECOMPILER:A decompiler translates code from a low-level language to a higher level
one.
5. SOURCE-TO-SOURCE COMPILER (TRANSPILER):A source-to-source compiler is
a program that translates between high-level languages. This type of compiler is also known as
a transcompiler or transpiler.
Some examples of a transpiler include:
6.A LANGUAGE REWRITER:This is usually a program translating form of expressions
without a change of language.

Compilation Process:: Compilation ensures that the source code adheres to the Syntax.
If any code does not follow Syntax, a compilation error will be generated.

Execution process: Execution is the process of running a.exe file for Windows or a.
extension file for a different operating system. A linker then links the object code with pre-
compiled library functions, thus creating an executable program. This executable program is
then loaded into the memory for execution.

Program counter: Program Counter: It contains the address of the next instructions to
be executed by the CPU.
A program counter is a register in a computer processor that contains the address (location) of
the instruction being executed at the current time. As each instruction gets fetched, the
program counter increases its stored value by 1.
The program counter (PC) is a register that manages the memory address of the instruction to
be executed next.
The address specified by the PC will be + n (+1 for a 1-word instruction and +2 for a 2-word
instruction) each time one instruction is executed.
However, in the case of an interrupt instruction, etc., the jump destination address is stored.

Call an execution instruction.The CPU reads the address where the instruction to be executed
next is stored from the PC and executes it in sequence.

Page 17
INTRODUCTION TO PROGRAMMING UNIT-I I-BTECH I-SEM BR23

(PART-B) Programming Languages


1.What are the type of Programming Languages

Programming Languages:

Major types of programming languages


• Procedural programming languages. A procedural language follows a sequence of statements
or commands in order to achieve a desired output. ...
• Functional programming languages. ...
• Object-oriented programming languages. ...
• Scripting languages. ...
• Logic programming languages.
1. Procedural programming languages
A procedural language follows a sequence of statements or commands in order to achieve a
desired output. Each series of steps is called a procedure, and a program written in one of these
languages will have one or more procedures within it. Common examples of procedural
languages include:
• C and C++
• Java
• Pascal
• BASIC

2. Functional programming languages


Rather than focusing on the execution of statements, functional languages focus on the output
of mathematical functions and evaluations. Each function–a reusable module of code–performs
a specific task and returns a result. The result will vary depending on what data you input into
the function. Some popular functional programming languages include:
• Scala
• Erlang
• Haskell
• Elixir
• F#

3. Object-oriented programming languages


This type of language treats a program as a group of objects composed of data and program
elements, known as attributes and methods. Objects can be reused within a program or in other
programs. This makes it a popular language type for complex programs, as code is easier to
reuse and scale. Some common object-oriented programming (OOP) languages include:
• Java
• Python
• PHP
• C++
• Ruby

Page 18
INTRODUCTION TO PROGRAMMING UNIT-I I-BTECH I-SEM BR23

4. Scripting languages
Programmers use scripting languages to automate repetitive tasks, manage dynamic web
content, or support processes in larger applications. Some common scripting languages include:
• PHP
• Ruby
• Python
• bash
• Perl
• Node.js

5. Logic programming languages


Instead of telling a computer what to do, a logic programming language expresses a series of
facts and rules to instruct the computer on how to make decisions. Some examples of logic
languages include:
• Prolog
• Absys
• Datalog
• Alma-0

Front-end vs. back-end languages


Front-end languages are primarily concerned with the ‘user’ aspect of the software. The front
end deals with all of the text, colors, buttons, images, and navigation that the user will face
when navigating your website or application. Anyone with a background in graphic design or
art may be more inspired to begin learning one of the front-end languages.
Some examples of front-end programming languages include:
• HTML
• CSS
• JavaScript
• React

History of C:

The c programming language was Introduced by Dennis Ritchie at bell laboratories at USA
in early 1970’s.It’s clearly introduced in 1972. It C language precede to developed with
ALGOL (1960), BCPL(1967) and B so alphabetical order name is taken as C.

Page 19
INTRODUCTION TO PROGRAMMING UNIT-I I-BTECH I-SEM BR23

Algorithms, Flowchart

2.Define an algorithm. What are the properties of an algorithm? What are


the types of algorithms and flowchart?
Algorithm: A step by step process of a particular programming task. An algorithm
(pronounced AL-go-rith-um) is a procedure or formula for solving a problem.
A finite set of precise instructions for performing a computation or for solving a problem

Properties of an Algorithm: It is written in simple English. - Each step of an


algorithm is unique and should be self explanatory.
Input:- An algorithm must have at least one input.
Output:- An algorithm must have at least one output.
Finite:- An algorithm has finite number of steps. the process terminates, finite numbe of steps
Definite:- - each step is precisely stated. Should have finite number of steps-
Efficiency:- each step can be carried out by a computer .The initial statements should be of
input and output statements are effectively

Control Structure of Algorithm:


1.Sequence Algorithm 2.Selective Algorithm 3. Loop/Iterative Algorithm

1.Sequence Algorithm: In a sequence, there is a linear progression of statements.


Write an algorithm to add two numbers entered by user.
Step 1: Start
Step 2: Read values num1 and num2.
Step 3: Add num1 and num2 and assign the result to sum.
sum←num1+num2
Step 4: print sum value
Step 5: Stop
2.Selective Algorithm:
Program to find the given two numbers which one is greater number
Step 1: Start.
Step 2: Take two inputs (a and b) from the user.
Step 3: If a is greater than b then go to step 4 otherwise go to step 5
Step 4: Print a greater than b
Step 5: Print b greater than a
Step 6: Stop.
3.Iterative Algorithm:
Program to find the factorial of a number
Step 1: Start.
Step 2: Initialize variables.
Step 3: Check FOR condition.
Step 4: If the condition is true, then go to step 5 otherwise go to step 7.
Step 5: f = f * i.
Step 6: Go to step 3.
Step 7: Print value of factorial.
Step 8: Stop.

Page 20
INTRODUCTION TO PROGRAMMING UNIT-I I-BTECH I-SEM BR23

Flowchart: Graphical representation of the Algorithm is called Flowchart. Flowcharts


are usually drawn using some standard symbols; however, some special symbols can also be
developed when required. Some standard symbols,
1. Start and end symbols:
Start or end of the program
Start and end symbols, represented as lozenges, ovals or rounded rectangles, usually
containing the word "Start" or "End", or another phrase signaling the start or end of a process,
2. Processing steps:
Computational steps or processing function of a program
Processing steps, represented as rectangles. Ex: "Add 1 to X"; "replace identified part";
3. Input/Output:
Input or output operation
Input/Output, represented as a parallelogram. Examples: Get X from the user; display X.
4. Conditional (or decision):
Decision making and branching
Conditional (or decision), represented as a diamond (rhombus). These typically contain a
Yes/No question or True/False test.. A number of other symbols that have less universal
currency, such as: A Document represented as a rectangle with a wavy base;

5. Arrows:
 →   Flow line
Advantages Of Using Flowcharts:
1. Effective analysis: With help flowchart, problem can be analyzed in more effective way.
2. Proper documentation: Program flowcharts serve as a good program documentation,
which is needed for various purposes.
3. Efficient Coding: The flowcharts act as a guide or blueprint during the systems analysis
and program development phase.
4. Proper Debugging: The flowchart helps in debugging process.
Disadvantages of Flowchart:
• It is difficult to draw flowcharts for large and complex programs.
• There is no standard to determine the amount of detail.
• Difficult to reproduce the flowcharts.
• It is very difficult to modify the Flowchart.
• Making a flowchart is costly.

Limitations Of Using Flowcharts:


1. Complex logic: Sometimes, the program logic is quite complicated. In that case,
flowchart becomes complex and clumsy.
2. Alterations and Modifications: If alterations are required the flowchart may require re-
drawing completely.
3. Reproduction: symbols cannot be typed, reproduction of flowchart becomes a problem.
4. The essentials of what is done can easily be lost in the technical details of how it is done.

Page 21
INTRODUCTION TO PROGRAMMING UNIT-I I-BTECH I-SEM BR23

Program Development Steps

3. Explain about Program Development Steps or Software Life Cycle Process


Program Development Steps:
The following steps are used in sequence for developing an efficient program:
1. Program Analysis (Specifying the problem statement)
2. Program Designing
i) Algorithm
ii) Flowchart
iii) Pseudo Code
3. Program Development
i) Coding
ii) Debugging
iii) Testing and Validating
4. Documentation and Maintenance.

1. Program Analysis (Specifying the Problem):


The Problem which has to be implemented into a program must be
thoroughly understood before the program is written. Problem must be analyzed to determine
the input and output requirements of the program. A problem is created with these
specifications.
ie. Understand the program, Select the set of instructions and multiple instructions

2. Program Designing :
With the problem statement obtained in the previous step, various methods
available for obtaining the required solution are analyzed and the best suitable method is
designed into algorithm.
ie. Algorithm, Flowchart and Pseudo code

i) Algorithm: A step by step process of a particular programming task(to get the solution fora
well defined problem). An algorithm (pronounced AL-go-rith-um) is a procedure or formula
for solving a problem.

Properties of an algorithm: - It is written in simple English. - Each step of an algorithm is


unique and should be self explanatory.
Input:- An algorithm must have at least one input.
Output:- An algorithm must have at least one output.
Finite:- An algorithm has finite number of steps. process terminates, number steps are finite
Definite:- - each step is precisely stated. Should have finite number of steps- Every statement
should be definitive.
Efficiency:- each step can be carried out by a computer .The initial statements should be of
input and output statements are effectively

ii) Flowchart: Graphical representation of the Algorithm is called Flowchart. 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

Page 22
INTRODUCTION TO PROGRAMMING UNIT-I I-BTECH I-SEM BR23

1. Start and end symbols:


Start or end of the program
2. Processing steps:
Computational steps or processing function of a program
3. Input/Output:

Input or output operation

4. Conditional (or decision):


Decision making and branching
Arrows:
 →   Flow line

iii) Pseudo Code: Pseudo code is an artificial and informal language that helps
programmers develop algorithms. Pseudo code is a "text-based" detail (algorithmic) design
tool. The rules of Pseudo code are reasonably straightforward. All statements showing
"dependency" are to be indented..
1. SEQUENCE represents linear tasks sequentially performed one after the other.
2. WHILE a loop with a condition at its beginning.
3. REPEAT-UNTIL a loop with a condition at the bottom.
4. FOR another way of looping.
5. IF-THEN-ELSE a conditional statement changing the flow of the algorithm.
6. CASE the generalization form of IF-THEN-ELSE.
BEGIN
READ A,B
CAL C=A+B
WRITE C
END

3. Programme Developments:
i) Coding: The actual program is written in the required programming language with the help
of information depicted in flow charts and algorithms.
ii) Debugging: There is a possibility of occurrence of errors in programs. These errors must be
removed to ensure proper working of programs. Hence error check is made. It is known as
“Debugging”.
Types of errors that may occur in the program are:
Syntactic Errors: These errors occur due to the usage of wrong syntax for the statements.
Syntax means rules of writing the program.
Example: x=z*/b;
There is syntax error in this statement. The rules of binary operators state that there cannot be
more than one operator between two operands.
Runtime Errors: These Errors are determined at the execution time of the program.
Example: Divide by zero
Range out of bounds

Page 23
INTRODUCTION TO PROGRAMMING UNIT-I I-BTECH I-SEM BR23

Logical Errors: These Errors occur due to incorrect usage of the instruction in the program.
These errors are neither displayed during compilation or execution nor cause any obstruction
to the program execution. They only cause incorrect outputs.

iii) Testing and Validating:


Testing and Validation is performed to check whether the program is producing correct
results or not for different values of input.

4. Documentation and Maintenance:


Documentation is the process of collecting, organizing and maintaining, in written the
complete information of the program for future references. Maintenance is the process of
upgrading the program according to the changing requirements.

Execution of C Program Development Steps:

1. Creating a Program : Create a source code using editor and save the file with .C Extension
ie..,An editor like notepad or WordPad is used to create a C program. This file contains a source
code which consists of executable code. The file should be saved as '*.c' extension only.
2. Compiling the Program :Compilation is the process of high level instructions into
machine level instructions. We use the shortcut key ALT+F9. Compiler converts
executable code to binary code i.e. object code. In this process complier checks the
errors. If there are any errors rectify and correct them and recompile the file. If there
is no errors source code converted to object code and store file save with.obj
3. Linking a Program to library : Obj file can executed using shortcut key CNTRL+F9an
executable file is created with .exe extension. The processor can understand exe file and it
perform the specified task.The object code of a program is linked with libraries that are
needed for execution of a program. The linker is used to link the program with libraries. It
creates a file with '*.exe' extension
C. Linking Programs: C programs are made up of many functions. Example:
printf ( ) , pow ( )… etc.
4. Execution of Program : Run Executable file: The final executable file is then run
by dos command prompt or by any other software.(ie .exe files are created)
After running the program the result is placed on user screen. Open user screen and check
the result using shortcut key ALT+F5.

Page 24
INTRODUCTION TO PROGRAMMING UNIT-I I-BTECH I-SEM BR23

Basic structure of C program

4. Describe about Basic structure of C program


Basic structure of C program: Structure of C program is defined by set of rules called
protocol, to be followed by programmer while writing C program.
1. Documentation section
2. Linkage Section or Header File Section
3. Definition Section
4. Global declaration section and Function prototype declaration section
5. Main function
6. Local declaration section.
7. Execution section.
8. User defined function definition section or Sub Program Section

S.N Sections Description

We can give comments about the program, creation or modified date, author name etc
in this section. The characters or words or anything which are given between starting
with /* and ending with */, won’t be considered by C compiler for compilation process.
These will be ignored by C compiler during compilation. In C++ used symbol is //
1. Single Line comment represented as //
Documentation Syntax: // message in C99 Compiler-TCC, DevC++
1 Ex:// addition two numbers
section
2. Multiline comment represented as /* ......................................................... */
Ex: /.*name: BNR
Branch: CSE */
Syntax: /* message */ in ANSI C Compiler-TC

Header files that are required to execute a C program are included


Syntax: #include<headerfile.h> Ex: #include<stdio.h> or
1. #include<filename>
2. #include “filename”
Here # is a Preprocessor Directive and ‘h’ is a header file

Linkage /Header 1 stdio.h -.> IStandered input/Output functions (scanf(),printf())


2
Section
2 conio.h ->Console Input/Output functions(clrscr(),getch())

3 stdlib.h ->General utility functions

4 string.h ->String functions(strlen(),strrev(),strcpy(),strcat())

5 math.h ->Mathematics functions( pow(),,sqrt(),abs(),exp())

Page 25
INTRODUCTION TO PROGRAMMING UNIT-I I-BTECH I-SEM BR23

In this section, variables are defined and values are set to these variables. It is a
Definition Optional Section. It is used fixed values
3
Section Syntax: #define identifier constant value
Ex: #define pi 3.14
Global variables are defined in this section. When a variable is to be used throughout
the program, can be defined in this section. These variables also called a Public
Global Variables
4 declaration
section int a;// Global variable declaration (public).This variable access any where any place
main()
{
}
Function prototype gives many information about a function like return type,
parameter names used inside and outside the function.

Syntax: Return type Function name(parameter list);


Function
prototype Exp:
declaration
section void sample(); // Global function declaration. This access any where any place

void main()
{
Sample()
}
Every C program is started from main function and this function contains two major
sections called declaration section and executable section. It is task of the every
program.
5 Main function
void main()
{

}
Local variables are defined in this section. When a variable is to be used to with inthe
main program, can be defined in this section. These variables also called a Private
Variables
Local declaration
6
section void main()
{
int a // it is Local variable declaration. This is only access with in main body

Page 26
INTRODUCTION TO PROGRAMMING UNIT-I I-BTECH I-SEM BR23

Function prototype gives many information about a function like return type,
parameter names used inside the function.
Function Exp:
prototype void main()
declaration {
section void sample(); // Local function declaration. This is only access with in main boby

sample();

}
7 Execution section It used defined the main logic coding of the program

It is used to simplify the code separately. It is a combination of statement block. It is


easily understand the user.T hats why it is user define function.
Sub Program
8 return FunctionName(Argumentlist)
Section {
Function body
‘rerun value
}

SAMPLE PROGRAM USING BASIC STRUCTURE FORMAT

/* To print is Even or Odd number */ // Documentation Section or Comment Line


#include<stdio.h>
#include<conio.h> // These two lines are Linage/ Header File
Section

void main() // This is Main Section


{
int a; // This is Local Variable Declaration Section
clrscr();
printf("Enter a number :"); // Begin Execute Section
scanf("%d",&a);

if (a%2==0)
{
printf("%d is even",a); //print true block output
}
else
printf("%d is odd",a); //print false block output

getch(); // End Execute Section


} // Begin to End lines or Statements are Execution Part Section

Page 27
INTRODUCTION TO PROGRAMMING UNIT-I I-BTECH I-SEM BR23

Input/Output (I/O Function) Statements


5.Disscuss about Input/Output (I/O Function) Statements
I/O (Function) Statements: The Input and Output Statements are Two Types. They
1.Formated I/O Function 2.Unformated I/O Function
1. Formatted Input/Output Functions :In formatted I/O binary data is converted to ASCII
before being stored, manipulated or output.. The scanf() and printf() functions are used for
formatted data input and output.. These functions are:
1. scanf()
2. printf();

1. scanf():The function scanf() is used for formatted input from standard input and provides
many of the conversion facilities of the function printf().

Syntax: scanf (“control string/format specifies”, &num1, &num2,…,&numn);


or
scanf (“control string/format specifies”, &variable list);

The function scnaf() reads and converts characters from the standards input depending
on the format specification string and stores the input in memory locations represented by the
other arguments (num1, num2,….numn).
For Example: char Name;
int Rollno;
scanf(“ %c %d”,&Name, &Rollno);
Write a function to accept and display the element number and the weight of a proton.
#include<stdio.h>
main()
{
int e_num;
float e_wt;
printf (“Enter the Element No. and Weight of a Proton\n”);
scanf (“%d %f”,&e_num, &e_wt);
printf (“The Element No.is:”,e_num);
printf (“The Weight of a Proton is: %f\n”, e_wt);
}

2.printf():The function printf() is used for formatted output to standard output based on a
format specification. The format specification string, along with the data to be output, are the
parameters to the printf() function.

Syntax: printf (“control string/format specifies”, num1, num2,…,numn);


or
printf (“control string/format specifies”, variable list);
Example: printf (“%c”, data1);

Page 28
INTRODUCTION TO PROGRAMMING UNIT-I I-BTECH I-SEM BR23

Unformatted Input/Output Functions :

1. getchar() and putchar():

1. getchar(): getchar() function will read a single character from the standard input. The return
value of getchar() is the first character in the standard input. The input is read until the Enter
key is pressed, but only the first character in the input will be returned.
Syntax for getchar() in C: character variable name=getchar();
getchar() accepts one character type data from the keyboard and store the character in to the
memory

2. putchar(): putchar() function will print a single character on standard output from the
memory
Syntax for putchar() in C : putchar(character variable name)
putchar() displays one character at a time to the Monitor
getchar() and putchar() functions are part of the standard C library header stdio.h
main()
{
char ch;
ch = getchar();
putchar(ch);
}

2. getch() getche() getc():


The functions getch() and getche() are used to read a character from the keyboard, similar
to getchar().A character entered will itself terminates reading. But getchar() read the character
and store in to the memory

1. Syntax for getch () in C : getch();


getch() accepts only single character from keyboard. But the character don’t store the memory

2. Syntax for getche() in C : getche();


Like getch(), getche() also accepts only single character, In case of getch(), the character
entered is not displayed or echoed on the screen, whereas in getche(), the character entered is
echoed or displayed on the screen. Syntax for both the macros
getch(); /*Typed character will not be displayed on the screen*/
getche(); /*Typed character will be displayed on the screen*/

3. getc() and putc():


1. getc(): read the character and store the memory
Syntax of getc(): getc(character name); // it is read the single character in memory

Page 29
INTRODUCTION TO PROGRAMMING UNIT-I I-BTECH I-SEM BR23

2. putc():write the character from store the memory


Syntax for putc ()in C : putc(character name) // It displays only one character at a time.

4.gets() and puts():These functions are used to read a set of characters (string) from the
keyboard and display a set of characters (string) on the screen.

1. gets() :These functions are used to read a set of characters (string) from the keyboard
Syntax for gets() in C : gets(String_name);
gets() accepts any line of string including spaces from the standard Input device (keyboard).
gets() stops reading character from keyboard only when the enter key is pressed.

2. puts():This function used for display a set of characters (string) on the screen.
The unformatted output statements in C are putch(), putchar() and puts().
Syntax for puts() in C : puts(String_name);
puts() displays a single / paragraph of text to the standard output device.
#include<conio.h>
void main()
{
char a[20];
gets(a);
puts(a);
getch();
}
5.getw() and putw():These functions are used to read the integer value from the
keyboard and display a integer number on the screen.
1. getw():These functions are used to read the integer value from the keyboard and display
a integer number on the screen.
Syntax for getw() in C : getw(variable name);
getw() accepts any integer value from the standard Input device (keyboard).

2. putw():These functions are used to display a integer number on the screen.


Syntax for putw() in C : putw(Variable name);
putw() displays a integer value to the standard output device.
#include<stdio.h>
void main()
{
int a;
getw(a);
putw(a);
}

Page 30
INTRODUCTION TO PROGRAMMING UNIT-I I-BTECH I-SEM BR23

Primitive Data Types


6..What are C Data Types in ANSI C and C-99 Slandered
A data type defines a set of values that a variable can store along with a set of
operations that can be performed on that variable.
1. Basic Data Type or Primary (or fundamental) data type
2. User – define data type
3. Derived data type 4.Empty /void data type

primary data types::-integer, character, floating point and double – precision floating point.
user define data types,:- namely struct, union, typedef and enum.
derived – data types,: such as arrays and pointers.
empty data set is also considered as data type -. void which either explicitly declares the
return type of a function where the function doesn’t return any value .ie void
ANSI C Standard Primitive Data types in C table format:
Keyword Format Specifier Size Data Range

char %c 1 Byte -128 to +127

unsigned char <-- -- > 1Bytes 0 to 255

int %d or %i 2 Bytes -32768 to +32767

Long int %ld 4 Bytes (2,147,483,647 to -2,147,483,648

float %f 4 Bytes -3.4e308 to +3.4e308

double %lf 8 Bytes -1.7e38 to +1.7e38

C99 Standard Primitive Data types in C table format:

Keyword Format Specifier Size Data Range

short %d or %i 2 Bytes -32768 to +32767

int %d 4 Bytes (2,147,483,647 to -2,147,483,648

Long int %ld 8 Bytes 4,294,967,295 to -4,294,967,296

bool %u 1 byte True or False

Page 31
INTRODUCTION TO PROGRAMMING UNIT-I I-BTECH I-SEM BR23

1. Basic data types in C:


i) Integer data type:
• Integer data type allows a variable to store numeric values.
• “int” keyword is used to refer integer data type.
• The storage size of int data type is 2 or 4 or 8 byte.
• It varies depend upon the processor in the CPU that we use. If we are using 16 bit
processor, 2 byte (16 bit) of memory will be allocated for int data type.
Ex:
int a=9; // int— It occupies two or four bytes of memory depends on complier/register
short int b=19; // Short---It occupies two bytes of memory
long int x=6; // long---It occupies four bytes of memory

ii) Character data type:


• Character data type allows a variable to store only one character.
• Storage size of character data type is 1. We can store only one character using
character data type..“char” keyword is used to refer character data type.
• For example, ‘A’ can be stored using char datatype. You can’t store more than one
character using char data type.

iii) Floating point data type: Floating point data type consists of 2 types. They are,
1. float 2. double
1. float:
➢ Floating data type can define using keyword float
➢ It takes four bytes of memory.
➢ It returns 6 precession values after decimal.
Ex: float pi=3.14;

2.double:
➢ Double point data type takes decimal values.
➢ Double data type can define using keyword double.
➢ It takes eight bytes of memory.
➢ It returns 15 precession values after decimal.
➢ Double data type is also same as float data type which allows up-to 10 digits after
decimal.

Ex: double pi=3.1428571428;

2. User defined Data Type:


i) Enumeration data type in C
• Enumeration data type consists of named integer constants as a list.
• It start with 0 (zero) by default and value is incremented by 1 for the sequential
identifiers in the list.
• enum syntax in C:

Page 32
INTRODUCTION TO PROGRAMMING UNIT-I I-BTECH I-SEM BR23

Syntax: enum identifier {const1, const2, .... , const n};

enum cse {software, web, seo};

enum month { Jan, Feb, Mar }; or


/* Jan, Feb and Mar variables will be assigned to 0, 1 and 2 respectively by default */
enum month { Jan = 1, Feb, Mar };
/* Feb and Mar variables will be assigned to 2 and 3 respectively by default */
enum month { Jan = 20, Feb, Mar };
#define Jan 20;
#define Feb 21;
#define Mar 22;

ii) Typedef :

It is used to create new data type. But it is commonly used to change existing data type with
another name.

typedef [data_type] new_data_type;

typedef int integer;

integer rno;

3. Derived data type in C:

• Array, pointer are called derived data type in C language.

4. Empty data type or Void data type in C:

• Void is an empty data type that has no value.


• This can be used in functions and pointers.
• Also used to null indicator is ‘\0’ ;

Page 33
INTRODUCTION TO PROGRAMMING UNIT-I I-BTECH I-SEM BR23

Identifiers, Keywords, Constant and Operators types(C- Tokens)

7. What are variable rules, keyword, Constant and Operators types?

C – Tokens :

• C tokens are the basic buildings blocks in C language which are constructed together
to write a C program.
• Each and every smallest individual units in a C program are known as C tokens.

• C tokens are of six types. They are,

1. Keywords (eg: int, while),


2. Identifiers (Variables ) (eg: main, total),
3. Constants (eg: 10, 20),
4. Strings (eg: “total”, “hello”),
5. Special symbols (eg: (), {}),
6. Operators (eg: +, /,-,*)

C tokens example program:


main()
{
int x, y, total;
x = 10, y = 20;
total = x + y;
printf (“Total = %d \n”, total);
}
where
• main – identifier
• {,}, (,) – delimiter
• int – keyword
• x, y, total – identifier
• main, {, }, (, ), int, x, y, total – tokens

1. Identifiers or Variables in C language:


• Each program elements in a C program are given a name called identifiers.
• Names given to identify Variables, functions and arrays are examples for identifiers.

Rules for constructing identifier or Variables in C:

1. Variable name must begin with letter or underscore.


2. Variables are case sensitive
3. They can be constructed with digits, letters.
4. No special symbols are allowed other than underscore.
5. sum, height, _value are some examples for variable name

Page 34
INTRODUCTION TO PROGRAMMING UNIT-I I-BTECH I-SEM BR23

Declaring & initializing C variable:

• Variables should be declared in the C program before to use.


• Memory space is not allocated for a variable while declaration. It happens only on
variable definition.
• Variable initialization means assigning a value to the variable.

S.No Type Syntax Example

1 Variable data_type variable_name; int x, y, z; char flat, ch;


declaration

2 Variable data_type variable_name = value; int x = 50, y = 30;


initialization
char flag = ‘x’, ch=’l’;

There are two types of variables in C program They are,


1. Local variable
2. Global variable

1. Example program for local variable in C:


• The scope of local variables will be within the function only.
• These variables are declared within the function and can’t be accessed outside the
function.

void test();
main()
{
int m = 22, n = 44; // m, n are local variables of main function
printf(“\nvalues : m = %d and n = %d”, m, n);
test();
}
void test()
{
int a = 50, b = 80; // a, b are local variables of test function
printf(“\nvalues : a = %d and b = %d”, a, b);
}

Output:
values : m = 22 and n = 44

values : a = 50 and b = 80

Page 35
INTRODUCTION TO PROGRAMMING UNIT-I I-BTECH I-SEM BR23

2. Example program for global variable in C:


• The scope of global variables will be throughout the program. These variables can be
accessed from anywhere in the program.
• This variable is defined outside the main function. So that, this variable is visible to
main function and all other sub functions.
#include<stdio.h>
void test();int m = 22, n = 44;
int a = 50, b = 80;
main()
{ printf(“All variables are accessed from main function”);
printf(“\nvalues: m=%d:n=%d:a=%d:b=%d”, m,n,a,b);
test();
}
void test()
{ printf(“\n\nAll variables are accessed from” \ ” test function”);
printf(“\nvalues: m=%d:n=%d:a=%d:b=%d”, m,n,a,b);
}

Output:
All variables are accessed from main function
values : m = 22 : n = 44 : a = 50 : b = 80

All variables are accessed from test function


values : m = 22 : n = 44 : a = 50 : b = 80

2. Keywords in C language:
• Keywords are pre-defined words in a C compiler.
• Each keyword is meant to perform a specific function in a C program.
• Since keywords are referred names for compiler, they can’t be used as variable name.
C language supports 32 keywords which are given below.

auto double int struct const float short unsigned

break else long switch continue for signed void

case enum register typedef default goto sizeof volatile

char extern return union do if static while

Page 36
INTRODUCTION TO PROGRAMMING UNIT-I I-BTECH I-SEM BR23

3. C – Constant:
• C Constants are also like normal variables. But, only difference is, their values can
not be modified by the program once they are defined.
• Constants refer to fixed values. They are also called as literals
• Constants may be belonging to any of the data type.
• Syntax: const data_type variable_name; (or) const data_type *variable_name;

Types of C constant:
1. Integer constants
2. Real or Floating point constants
3.Octal & Hexadecimal constants
4.Character constants
5. String constants
6. Backslash character constants

1. Integer Constants in C:
• An integer constant must have at least one digit.
• It must not have a decimal point.
• It can either be positive or negative.
• No commas or blanks are allowed within an integer constant.
• If no sign precedes an integer constant, it is assumed to be positive.
• The allowable range for integer constants is -32768 to 32767.
int a=9
2. Real constants in C:
• A real constant must have at least one digit
• It must have a decimal point
• It could be either positive or negative
• If no sign precedes an integer constant, it is assumed to be positive.
• No commas or blanks are allowed within a real constant.
float b=19.5
3. Character and string constants in C:
• A character constant is a single alphabet, a single digit or a single special symbol
enclosed within single quotes.
• The maximum length of a character constant is 1 character.
char v=’R’
4. String constants
❖ A String in C is nothing but a collection of characters in a linear sequence.
'C' alwaystreats a string a single data even though it contains whitespaces.
❖ A single character is defined using single quote representation. A string is
❖ There are two ways to declare a
❖ String constants are enclosed within double quotes.
char ch[]="bnr";

char ch[10]={‘b', ‘n', ‘r’, '\0'};


As we know, array index starts from 0, so it will be represented as in the figure givenbelow.
Page 37
INTRODUCTION TO PROGRAMMING UNIT-I I-BTECH I-SEM BR23

❖ There are two main differences between char array and literal.
❖ We need to add the null character '\0' at the end of the array by our self
whereas, it is appended internally by the compiler in the case of the character
array.
❖ The string literal cannot be reassigned to another set of characters whereas, we
canreassign the characters of the array.

4. Backslash Character Constants or Escape Sequences or White Spaces in C:


There are some characters which have special meaning in C language. They should be
preceded by backslash symbol to make use of special function of them.

Backslash_character Meaning

\b Backspace

\f Form feed

\n New line

\r Carriage return

\t Horizontal tab

\” Double quote

\’ Single quote

\\ Backslash

\v Vertical tab

\a Alert or bell

\? Question mark

Octal constant (N is an octal


\N
constant)

Hexadecimal constant (N – hex.dcml


\XN
cnst)

Page 38
INTRODUCTION TO PROGRAMMING UNIT-I I-BTECH I-SEM BR23

Operators :
Binary Operator: An operator is called as two operand between using operator.
1. Arithmetic operators
2. Relational operators
3. Logical operators
4. Bit wise operators
Unary Operator: An Operand before or after using the Operator is called as Unary Operator
1. Increment/decrement operators
2. Assignment operators
Ternary Operator: An operator and operand in without using conditional statements are
called Ternary or Conditional Operator
1.Conditional operators (ternary operators) .Actually the type of operators are
Types of C operators
Arithmetic operators
Relational operators
Logical operators
Bit wise operators
Conditional operators (ternary operators)
Increment/decrement operators
Assignment operators
Special operators
S.no Types of Operators Description

These are used to perform mathematical calculations like


1 Arithmetic_operators addition, subtraction, multiplication, division and
modulus

These are used to assign the values for the variables in C


2 Assignment_operators
programs.

These operators are used to compare the value of two


3 Relational operators
variables.

These operators are used to perform logical operations on


4 Logical operators
the given two variables.

These operators are used to perform bit operations on


5 Bit wise operators
given two variables.

Conditional (ternary) Conditional operators return one value if condition is true


6
operators and returns another value is condition is false.

Page 39
INTRODUCTION TO PROGRAMMING UNIT-I I-BTECH I-SEM BR23

Increment/decrement These operators are used to either increase or decrease the


7
operators value of the variable by one.

8 Special operators &, *, sizeof( ) and ternary operators.

1. Arithmetic Operators: it is used to perform mathematical calculations,(arithmetic’s)


S.no Arithmetic Operators Operation Example

1 + Addition A+B

2 - Subtraction A-B

3 * multiplication A*B

4 / Division A/B

5 % Modulus A%B

#include <stdio.h>
main()
{
int a=40,b=20, add,sub,mul,div,mod;
add = a+b;
sub = a-b;
mul = a*b;
div = a/b;
mod = a%b;
printf(“Addition of a, b is : %d\n”, add);
printf(“Subtraction of a, b is : %d\n”, sub);
printf(“Multiplication of a, b is : %d\n”, mul);
printf(“Division of a, b is : %d\n”, div);
printf(“Modulus of a, b is : %d\n”, mod);
}
Output:
Addition of a, b is : 60
Subtraction of a, b is : 20
Multiplication of a, b is : 800
Division of a, b is : 2
Modulus of a, b is : 0

Page 40
INTRODUCTION TO PROGRAMMING UNIT-I I-BTECH I-SEM BR23

2. Relational Operators: Relational operators are used to find the relation between two
variables. i.e. to compare the values of two variables in a C program.
S.no Operators Example Description

1 > x>y x is greater than y

2 < x<y x is less than y

3 >= x >= y x is greater than or equal to y

4 <= x <= y x is less than or equal to y

5 == x == y x is equal to y

6 != x != y x is not equal to y

#include <stdio.h>
main()
{
int m=40,n=20;
if (m == n)
printf(“m and n are equal”);
else
printf(“m and n are not equal”);
}
Output: m and n are not equal

3. Logical Operators:These operators are used to perform logical operations on the given
expressions.There are 3 logical operators in C language. They are, logical AND (&&), logical
OR (||) and logical NOT (!).
S.no Operators Name Example Description

1 && logical AND (x>5)&&(y<5) It returns true when both conditions are true

It returns true when at-least one of the condition


2 || logical OR (x>=10)||(y>=10)
is true

It reverses the state of the operand “((x>5) &&


(y<5))”
3 ! logical NOT !((x>5)&&(y<5))
If “((x>5) && (y<5))” is true, logical NOT
operator makes it false

Page 41
INTRODUCTION TO PROGRAMMING UNIT-I I-BTECH I-SEM BR23

#include <stdio.h>
main()
{
int m=40,n=20;
int o=20,p=30;
if (m>n && m !=0)
printf(“&& Operator : Both conditions are true\n”);
if (o>p || p!=20)
printf(“|| Operator : Only one condition is true\n”);
if (!(m>n && m !=0))
printf(“! Operator : Both conditions are true\n”);
else
printf(“! Operator : Both conditions are true. ” \“But, status is inverted as false\n”);
}Output:
&& Operator : Both conditions are true
|| Operator : Only one condition is true
! Operator : Both conditions are true. But, status is inverted as false

4. Bitwise Operators: These operators are used to perform bit operations. Decimal values are
converted into binary values which are the sequence of bits and bit wise operators work on
these bits.Bit wise operators in C language are & (bitwise AND), | (bitwise OR), ~ (bitwise
OR), ^ (XOR), << (left shift) and >> (right shift).
Truth table for bit wise operation Bit wise operators
x y x|y x & y x ^ y Operator_symbol Operator_name

0 0 0 0 0 & Bitwise_AND

0 1 1 0 1 | Bitwise OR

1 0 1 0 1 ~ Bitwise_NOT

1 1 1 1 0 ^ XOR

<< Left Shift

>> Right Shift

main()
{
int m = 40,n = 80,AND_opr,OR_opr,XOR_opr,NOT_opr ;
AND_opr = (m&n);
OR_opr = (m|n);
NOT_opr = (~m);

Page 42
INTRODUCTION TO PROGRAMMING UNIT-I I-BTECH I-SEM BR23

XOR_opr = (m^n);
printf(“AND_opr value = %d\n”,AND_opr );
printf(“OR_opr value = %d\n”,OR_opr );
printf(“NOT_opr value = %d\n”,NOT_opr );
printf(“XOR_opr value = %d\n”,XOR_opr );
printf(“left_shift value = %d\n”, m << 1);
printf(“right_shift value = %d\n”, m >> 1);
}
AND_opr value = 0
OR_opr value = 120
NOT_opr value = -41
XOR_opr value = 120
left_shift value = 80
right_shift value = 20

5. Conditional or Ternary Operators : Conditional operators return one value if condition


is true and returns another value is condition is false.

• This operator is also called as ternary operator. ? :

Syntax : Exp1 ? exp2 : exp3


Here exp1 evaluated first if it is true exp2 evaluated otherwise exp3 evaluated.
Example : (A > 100) ? 0 : 1;
.In above example, if A is greater than 100, 0 is returned else 1 is returned. This is equal to if
else conditional statements.

Example program for conditional/ternary operators in C:


#include <stdio.h>
main()
{
int x=1, y ;
y = ( x ==1 ? 2 : 0 ) ;
printf(“x value is %d\n”, x);
printf(“y value is %d”, y);
}

6. Increment/Decrement Operators: Syntax:


Incrementoperator::++var_name;(or)var_name++;
Decrement operator: --var_name; (or) var_name – -;

Incrementoperator: ++i,i++
Decrement operator : - – i , i – -
❖ Increment and decrement operators are also called unary operators.

Page 43
INTRODUCTION TO PROGRAMMING UNIT-I I-BTECH I-SEM BR23

❖It is also called modify operators.


❖Increment means increase value by one.
❖Decrement means decrease value by one.
❖Increment operators is two types pre increment and post increment.
❖Decrement operator is two types pre decrement and post decrement.
❖Both are used to either increase or decrease a value by one…
❖In pre increment and post increment there will be a difference when we
will assign aincrement to other variable.
Pre increment Post increment
x=10 x=10
++x; //pre increment x++; //post increment
x=x+1; x=x+1;
x=10+1; x=10+1;
x=11. x=11.
x=10 x=10
y=++x; y=x++;
here x=x+1;. here x=x+1;.
x=10+1; x=11; y=11; x=10+1; x=11; y=10;
In pre increment y value will update with new x In post increment y value will not update with
value. new x value
Example program for increment operators in
• In this program, value of “i” is incremented one by one from 1 up to 9 using “i++”
operator and output is displayed as “1 2 3 4 5 6 7 8 9”.
//Example for increment operators
#include <stdio.h>
main()
{ int i=1;
while(i<10)
{
printf("%d ",i);
i++;
}
}
Example program for decrement operators in C: In this program, value of “I” is
decremented one by one from 20 up to 11 using “i–” operator and output is displayed as “20
19 18 17 16 15 14 13 12 11”.
//Example for decrement operators
#include <stdio.h>
main()
{
int i=20;
while(i>10)
{

Page 44
INTRODUCTION TO PROGRAMMING UNIT-I I-BTECH I-SEM BR23

printf("%d ",i);
i--;
}
}
Output: 20 19 18 17 16 15 14 13 12 11

Difference between pre/post increment & decrement operators in C:


• Below table will explain the difference between pre/post increment and decrement
operators in C.
S.no Operator type Operator Description

++i Value of i is incremented before assigning it to


1 Pre increment
variable i.

i++ Value of i is incremented after assigning it to variable


2 Post-increment
i.

– –i Value of i is decremented before assigning it to


3 Pre decrement
variable i.

i– – Value of i is decremented after assigning it to variable


4 Post_decrement
i.

Example program for pre – increment operators in C:


main()
{
int i=0;
while(++i < 5 )
{
printf("%d ",i);
}
}
Output: 1 2 3 4
Example program for pre - decrement operators in C:
#include <stdio.h>
main()
{
int i=10;
while(--i > 5 )
printf("%d ",i);
}

Output: 9 8 7 6

Page 45
INTRODUCTION TO PROGRAMMING UNIT-I I-BTECH I-SEM BR23

Example program for post - decrement operators in C:


#include <stdio.h>
main()
{
int i=10;
while(i-- > 5 )
printf("%d ",i);
}
Output:: 9 8 7 6 5

7. Assignment Operators :

Operators Example Explanation

10 is assigned to variable
Simple assignment operator = sum = 10
sum

This is same as sum = sum +


+= sum += 10
10

This is same as sum = sum –


-= sum -= 10
10

This is same as sum = sum *


*= sum *= 10
10

Compound assignment /+ sum /= 10 This is same as sum = sum /


operators 10

sum %= This is same as sum = sum


%=
10 % 10

This is same as sum = sum


&= sum&=10
& 10

This is same as sum = sum ^


^= sum ^= 10
10

Example program for C assignment operators:


# include <stdio.h>
main()
{

Page 46
INTRODUCTION TO PROGRAMMING UNIT-I I-BTECH I-SEM BR23

int Total=0,i;
for(i=0;i<10;i++)
Total+=i; // This is same as Total = Toatal+i
printf(“Total = %d”, Total);
}

8. Special Operators: Using sizeof() function in Data Types C:


sizeof() function is used to find the memory space allocated for each C data types.
S.no Operators Description

This is used to get the address of the variable.


1 &
Example : &a will give address of a.

This is used as pointer to a variable.


2 *
Example : * a where, * is pointer to the variable a.

This gives the size of the variable.


3 sizeof ()
Example : size of (char) will give us 1.

Example program for sizeof() operator in C:


• sizeof() operator is used to find the memory space allocated for each C data types.
#include <stdio.h>
#include <limits.h>
main()
{
int a; char b; float c; double d;
printf(“Storage size for int data type:%d \n”,sizeof(a));
printf(“Storage size for char data type:%d \n”,sizeof(b));
printf(“Storage size for float data type:%d \n”,sizeof(c));
printf(“Storage size for double data type:%d\n”,sizeof(d));
}Output:
Storage size for int data type:4
Storage size for char data type:1
Storage size for float data type:4
Storage size for double data type:8

Page 47
INTRODUCTION TO PROGRAMMING UNIT-I I-BTECH I-SEM BR23

Type casting (type conversion)


8 Explain about data modifiers (type conversion)

Type Conversion(Type Casting or Data Modifiers):

Type conversion in c can be classified into the following two types:

1. Implicit Type Conversion

2.Explicit Type Conversion

1. Implicit Type Conversion:

The compiler converts all operands into the data type of the largest operand.

The sequence of rules that are applied while evaluating expressions are given below:

All short and char are automatically converted to int, then,

1. If either of the operand is of type long double, then others will be converted to long
double and result will be long double.
2. Else, if either of the operand is double, then others are converted to double.
3. Else, if either of the operand is float, then others are converted to float.
4. Else, if either of the operand is unsigned long int, then others will be converted to
unsigned long int.

2. Explicit Type Conversion:

The explicit type conversion is also known as type casting.

Type casting in c is done in the following form:

(data_type)expression or (type cast)expression;

where, data_type is any valid c data type, and expression may be constant, variable or
expression.

For example x=(int)a+b*d;

The following rules have to be followed while converting the expression from one type to
another to avoid the loss of information:

1. All integer types to be converted to float.


2. All float types to be converted to double.
3. All character types to be converted to integer.

Page 48
INTRODUCTION TO PROGRAMMING UNIT-I I-BTECH I-SEM BR23

Format Modifiers(Specifies) and Compilation Errors


9.What are the format modifiers and Compilation errors ?

Format specifies:
The % specifiers that you can use in ANSI C are as follows:
SPECIFIER USED FOR
%c a single character
%s a string
%hi short (signed)
%hu short (unsigned)
%Lf long double
%n prints nothing
%d a decimal integer (assumes base 10)
%i a decimal integer (detects the base automatically)
%o an octal (base 8) integer
%x a hexadecimal (base 16) integer
%p an address (or pointer)
%f a floating point number for floats
%u int unsigned decimal
%e a floating point number in scientific notation
%E a floating point number in scientific notation
%% the % symbol

Errors in Compilation:
There is a possibility of occurrence of errors in programs. These errors must be
removed to ensure proper working of programs. Hence error check is made. It is known as
“Debugging”.
Types of errors that may occur in the program are:
1. Syntactic Errors: These errors occur due to the usage of wrong syntax for the statements.
Syntax means rules of writing the program.
Example: x=z*/b;

Page 49
INTRODUCTION TO PROGRAMMING UNIT-I I-BTECH I-SEM BR23

There is syntax error in this statement. The rules of binary operators state that there cannot be
more than one operator between two operands.
. Some of the most frequently occurring syntax errors include:
• Missing or extra parentheses
• Missing or extra braces
• Mismatched quotes
• Missing or misplaced semicolons
• Incorrectly nested loops or blocks
• Invalid variable or function names
• Incorrect use of operators
Syntax Error in C Example
Suppose you are writing a C program to calculate the area of a rectangle. An example of a
syntax error in this program might be:
int main()
{
int length = 5;
int width = 10
int area = length * width;
printf("The area of the rectangle is %d\n", area);
return 0;
}
Here, the syntax error is the missing semicolon after the declaration and assignment of the
'width' variable. The compiler will raise an error, and the program will not compile until the
mistake is corrected.
Expression Syntax Error in C
Expression syntax errors can also occur when using arithmetic, logical, or relational operators
incorrectly. An example of an expression syntax error in C:
int main()
{
int a = 2;
int b = 4;
int result = a ++ * ++ b;
printf("The result is %d\n", result);
return 0;
}
Here, the error is caused by the incorrect use of the increment operator (++). The correct
expression should be:
int result = a++ * ++b;
Correcting the error will allow the program to compile and execute successfully.
Create Syntax Errors notes faster than ever before
StudySmarter FREE web and mobile app

Declaration Syntax Error in C


Declaration syntax errors occur when a variable or function is improperly declared. An
example of a declaration syntax error in C:
int main()
{
Page 50
INTRODUCTION TO PROGRAMMING UNIT-I I-BTECH I-SEM BR23

int a;
int 1b;
a = 5;
1b = 10;
printf("The value of a is %d and the value of 1b is %d\n", a, 1b);
return 0;
}
The syntax error in this example is the naming of the '1b' variable, as variable names must not
start with a number. Changing the variable name to a valid identifier will correct the error:
int b;
a = 5;
b = 10;
printf("The value of a is %d and the value of b is %d\n", a, b);
Once the error is corrected, the program will compile and execute without issues.

Identifying Common Syntax Errors in C


When programming in C, it is essential to be aware of common syntax errors to avoid potential
issues in your code. This section will provide insights into frequent syntax errors and their
identification process, making it easier for you to loca Debugging is the process of locating and
resolving errors in your code. To make the debugging process more efficient, follow these tips:

1. Examine compiler or interpreter error messages: These messages often provide


detailed information about the location and nature of the syntax errors.
2. Use descriptive variable and function names: This makes it easier to understand the
purpose of each code element and helps you identify potential errors in their usage.
3. Indent and comment your code: Proper indentation and comments will enable you
to grasp the structure and logic of your code quickly, thus making it easier to identify
any syntax errors.
4. Break complex expressions into smaller parts: This helps in understanding the logic
better, making it easier to locate and fix errors.
5. Use a debugger tool: Debugger tools step through your code, helping you locate
mistakes efficiently and fix them in real-time.
6. Test your code frequently: By testing small sections of your code as they are
completed, you will be able to resolve syntax errors earlier in the developmentprocess

2. Runtime Errors: These Errors are determined at the execution time of the program.

Example: Divide by zero


Range out of bounds
Square root of a negative number

3. Logical Errors: These Errors occur due to incorrect usage of the instruction in the
program. These errors are neither displayed during compilation or execution nor cause any
obstruction to the program execution. They only cause incorrect outputs.

Page 51
INTRODUCTION TO PROGRAMMING UNIT-I I-BTECH I-SEM BR23

Precedence Priority Table


10..Drow the Operator Precedence Priority Table.
Operators Precedence and Associatively :

Associatively Operator Description

() Function

[] Array
Left to Right
--> Pointer to member

. Structure

- Unary Minus

+ Unary Plus

++ / -- Increment/Decrement

~ One's Complement

& Address of
Right to left
(type) Type casting

Sizeof() Size (in bytes)

! Logical Not

* Pointer reference

* Multiplication

Left to Right / Division

% Modulus

+ Addition
Left to Right
- Subtraction

Left to Right << Left Shift

Page 52
INTRODUCTION TO PROGRAMMING UNIT-I I-BTECH I-SEM BR23

>> Right Shift

< Less than

<= Less than or equal to


Left to Right
> Greater than

>= Greater than or equal to

== Equality
Left to Right
!= Not Equal to

Left to Right & Bitwise AND

Left to Right ^ Bitwise XOR

Left to Right | Bitwise OR

Left to Right && Logical AND

Left to Right || Logical OR

Left to Right ? : Conditional Operator

Right to Left = *= += Assignment

Left to Right , Comma

Case Study: Top-down and Bottom–up approach ,Time vs space


complexities
1) Top-down approach:
❖ In this approach, a large project divides into small programs, and these
programs areknown as modules.
❖ C programming language supports this approach for developing projects. It is
always good idea that decomposing solution into modules in a hierarchal
manner.
❖ The basic task of a top-down approach is to divide the problem into tasks
and thendivide tasks into smaller sub-tasks and so on.
Advantages of top-down approach:
1. In this approach, first, we develop and test most important module.

Page 53
INTRODUCTION TO PROGRAMMING UNIT-I I-BTECH I-SEM BR23

2. This approach is easy to see the progress of the project by developer or customer.
3. Using this approach, we can utilize computer resources in a proper manner
according tothe project.
4. Testing and debugging is easier and efficient.
5. This approach is good for detecting and correcting time delay

2) Bottom-up approach:
❖ C++ used the bottom-up approach for project development. It is an
alternativeapproach to the top-down approach.
❖ In this approach, bottom level modules developed first (Lower level
moduledeveloped, tested and debugged).
❖ Then the next module developed, tested and debugged. This process is
continueduntil all modules have been completed.

Time and space complexities:


Time complexity:
Time complexity of an algorithm quantifies the amount of time taken by an algorithm
to run a program.
❖ Worst Case Analysis: In the worst-case analysis, we calculate the upper limit of the
execution time of an algorithm .Notation of worst-case time complexity by using the
Big-O.
❖ Average Case Analysis: In the average case analysis, we calculate the average limit
ofthe execution time of an algorithm .Notation of average case is Big-Omega.
❖ Best Case Analysis: In the best case analysis, we calculate the lower bound of
theexecution time of an algorithm. Notation of Best case is Big-Theta.
Space complexity:
Space complexity of an algorithm quantifies the amount of space or memory taken by
analgorithm to run a Program.
❖ Instruction Space: It is the amount of memory used to store compiled version of
instructions.
❖ Data space: It is the amount of memory used to store variables and constants.
❖ Environmental space: It is the amount of memory used to environmental
resourcesneeded to current program.

Page 54

You might also like