cp unit 1 notes b r23 notes
cp unit 1 notes b r23 notes
cp unit 1 notes b r23 notes
UNIT I
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
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
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
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
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
Page 7
INTRODUCTION TO PROGRAMMING UNIT-I I-BTECH I-SEM BR23
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:
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 will physically wear out over Software does not wear out but it can be
time affected by bugs and glitches
Page 9
INTRODUCTION TO PROGRAMMING UNIT-I I-BTECH I-SEM BR23
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.
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.
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
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.
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
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
Programming Languages:
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
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
Page 20
INTRODUCTION TO PROGRAMMING UNIT-I I-BTECH I-SEM BR23
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.
Page 21
INTRODUCTION TO PROGRAMMING UNIT-I I-BTECH I-SEM BR23
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.
Page 22
INTRODUCTION TO PROGRAMMING UNIT-I I-BTECH I-SEM BR23
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.
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
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
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.
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
if (a%2==0)
{
printf("%d is even",a); //print true block output
}
else
printf("%d is odd",a); //print false block output
Page 27
INTRODUCTION TO PROGRAMMING UNIT-I I-BTECH I-SEM BR23
1. scanf():The function scanf() is used for formatted input from standard input and provides
many of the conversion facilities of the function printf().
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.
Page 28
INTRODUCTION TO PROGRAMMING UNIT-I I-BTECH I-SEM BR23
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);
}
Page 29
INTRODUCTION TO PROGRAMMING UNIT-I I-BTECH I-SEM BR23
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).
Page 30
INTRODUCTION TO PROGRAMMING UNIT-I I-BTECH I-SEM BR23
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
Page 31
INTRODUCTION TO PROGRAMMING UNIT-I I-BTECH I-SEM BR23
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.
Page 32
INTRODUCTION TO PROGRAMMING UNIT-I I-BTECH I-SEM BR23
ii) Typedef :
It is used to create new data type. But it is commonly used to change existing data type with
another name.
integer rno;
Page 33
INTRODUCTION TO PROGRAMMING UNIT-I I-BTECH I-SEM BR23
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.
Page 34
INTRODUCTION TO PROGRAMMING UNIT-I I-BTECH I-SEM BR23
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
Output:
All variables are accessed from main 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.
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";
❖ 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.
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
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
Page 39
INTRODUCTION TO PROGRAMMING UNIT-I I-BTECH I-SEM BR23
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
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
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
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
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
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
Output: 9 8 7 6
Page 45
INTRODUCTION TO PROGRAMMING UNIT-I I-BTECH I-SEM BR23
7. Assignment Operators :
10 is assigned to variable
Simple assignment operator = sum = 10
sum
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);
}
Page 47
INTRODUCTION TO PROGRAMMING UNIT-I I-BTECH I-SEM BR23
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:
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.
where, data_type is any valid c data type, and expression may be constant, variable or
expression.
The following rules have to be followed while converting the expression from one type to
another to avoid the loss of information:
Page 48
INTRODUCTION TO PROGRAMMING UNIT-I I-BTECH I-SEM BR23
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
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.
2. Runtime Errors: These Errors are determined at the execution time of the program.
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
() 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
! Logical Not
* Pointer reference
* Multiplication
% Modulus
+ Addition
Left to Right
- Subtraction
Page 52
INTRODUCTION TO PROGRAMMING UNIT-I I-BTECH I-SEM BR23
== Equality
Left to Right
!= Not Equal to
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.
Page 54