0% found this document useful (0 votes)
14 views67 pages

Unit 1

This document provides an overview of programming and problem-solving, including the history of computers, basic computer organization, and programming languages. It covers the evolution of computing devices from the abacus to modern computers, the structure of a computer, and the differences between compilers and interpreters. Additionally, it discusses the classification of programming languages and their characteristics, emphasizing the importance of algorithms and problem-solving techniques.

Uploaded by

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

Unit 1

This document provides an overview of programming and problem-solving, including the history of computers, basic computer organization, and programming languages. It covers the evolution of computing devices from the abacus to modern computers, the structure of a computer, and the differences between compilers and interpreters. Additionally, it discusses the classification of programming languages and their characteristics, emphasizing the importance of algorithms and problem-solving techniques.

Uploaded by

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

UNIT 1

Introduction to Programming and Problem Solving

History of Computers, Basic organization of a computer: ALU, input-output units, memory, program counter,
Introduction to Programming Languages, Basics of a Computer Program-Algorithms, flowcharts (using Dia Tool), pseudo
code. Introduction to compilation and Execution, Primitive Data Types, Variables and Constants, Basic Input and Output,
Operations, Type conversion and Casting.

Problem solving techniques: Algorithmic approach, characteristics of algorithm, Problem solving strategies: Top-down
approach, Bottom-up approach, Time and space complexities of algorithms.

History of Computers (or) Evolution of Computers:

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. let us consider the development of a computer through various stages.

1.Abacus:
✓ It was a wooden rack which has metal rods with beads mounted on them.
✓ The beads were moved by the abacus operator according to some rules to perform arithmetic calculations.
✓ Abacus is still used in some countries like China, Russia and Japan.

2.Napier’s Logs and Bone’s :


✓ Napier’s Bones was a manually operated calculating device and invented by John Napier.
✓ This device used 9 different ivory strips (bones) marked with numbers to multiply and divide for calculation.
✓ First machine to use the decimal point system for calculation.

3.Pascal’s Adding machine :


✓ Pascaline is also known as Arithmetic Machine or Adding Machine.
✓ First mechanical and automatic calculator by a French mathematician- philosopher Biaise Pascal.
✓ It was a wooden box with a series of gears and wheels. When a wheel is rotated one revolution, it rotates the
neighboring wheel. A series of windows is given on the top of the wheels to read the totals.
4. Stepped Reckoner or Leibnitz wheel Calculator
✓ 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.
✓ It was able to perform multiplication & division.

5. Babbage’s Difference Engine :


✓ Charles Babbage developed a machine called difference engine In early 1820s.
✓ These machines calculate logarithmic tables to a high degree of precision.

6. Babbage’s Analytical Engine :


✓ Charles Babbage designs an analytical engine which begins a real model of modern days computer in 1830.
✓ He included the concept of central process storage area, memory and input/output.
✓ Because of inventions of difference engine and analytical engine, Charles Babbage has been considering as “Father
of modern Computers”.
✓ 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.
7.Tabulating (or) Hollerith’s Machine :
✓ Herman Hollerith developed electro mechanical punched card in 1890, that is used for input, output and storing of
instructions.
✓ 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.

8. Mark-1 :
✓ *Howard Aiken contracted an electro mechanical computer named mark-1 In the year 1944.
✓ *It could multiply two 10-digit number in 5-seconds.
✓ *It was also the first programmable digital computer marking a new era in the computer world.

9.ENIAC :
✓ Electronic Numerical Integrator and Calculator were built by Prof. Eckerit and Mauchly.
✓ It used about 19000 vacuum tubes and can perform about 300 multiplications per second.

10.EDSAC:
✓ Electronic Delay Storage Automatic Computer was developed by Maurice willies.
✓ It has ability to input, output, staring the data.
✓ It also able to perform and control arithmetic calculations.
11.EDVAC:
✓ Electronic Discrete Variable Automatic Computer was developed by Prof. Eckerit and Mauchly.
✓ In this both the data and instruction can be stored in binary form instead of decimal number system.
12.UNIVAC:
✓ Universal Automatic Computer developed by Remington.
✓ It was cable of performing to access both numeric and alphabetic information.b
13.UNIVAC-1:
✓ It is the first computer which is used for commercial purpose in 1954.
Generations of Computers:
Gen Technology Year speed Languages Examples Dis ADV
No specific Analytical
Very slowest Very Large,
Mechanical languages instead Engine,
0th 1642-1940 computing Bulky and
gears of that patterns Difference
devices noisy
used Engine
Slowest Large, Bulky
st Vacuum Machine level
1 1940-1956 computing EDSAC ,EDVAC and difficult to
Tubes language
devices program
High cost and
Faster than first Assembly level IBM-1401, IBM- limited to
2nd Transistor 1956-1963
generation language 1620 special
purpose tasks
Integrated Limited
Faster than High level IBM-360,
3rd circuits 1964-1975 storage
second generation languages HoneyWell-6000
(ICs) capacity
Faster than third High level IBM PC series , Difficult to
4th VLSI 1975-1989
generation languages Apple Series manufacture
HLL , Integrated Laptop , PDA Lack of human
1989 – till Fastest of all
5th ULSI Development (Personal Digital like
date times
Environment (IDE assistance) Intelligence

Block Diagram of a Computer (or) Basic organization of a computer:


The word computer has been derived from the word “Compute” which means to calculate. It is an electronic device
which inputs the data, stores the data, processes the data and gives the result accurately at a very high speed according to
the instructions provided. (or)
A computer is an electronic machine that can be programmed to carry out sequences of arithmetic or logical
operations automatically that accepts raw data as input and processes it with a set of instructions (a program) to produce the
result as output.

Input Unit:
Computers need to receive data and instructions in order to solve any problem.
✓ The input unit consists of one or more input devices like keyboard, mouse, joystick etc.
✓ Regardless of the type of the input device used in a computer system, all input devices perform the following
functions.
➢ Accept the data
➢ Convert data to computer understandable form.
➢ Supply converted data for further processing.
CPU:
✓ The actual processing of the data is carried out in the Central Processing Unit (CPU), which is the brain
✓ of computer. The CPU stores the data and instructions in the primary memory of the computer, called the Random
Access Memory (RAM) and processes them from this location.

✓ CPU stands for “Central Processing Unit.”


✓ CPU is like a computer Brain. It performs the following operations.
➢ It performs all calculations.
➢ It takes all decisions.
➢ It controls all units of computer.
✓ Control unit, Memory unit and Arithmetic logic unit of the computers are together known as central processing
unit.
The Control Unit (CU) and the Arithmetic Logic Unit (ALU) are the two subcomponents of the CPU. The ALU
carries out the arithmetic and logical operations while the CU retrieves the information from the storage unit and
interprets this information. The CPU also consists of circuitry devices called cache and registers.
Control Unit:
✓ The control unit controls all other units in the computer.
✓ The control unit instructs the input unit where to store data after receiving it from the user.
✓ It also controls the flow of data and instructions from the memory unit to “ALU”.
✓ It controls the flow of results from ALU to output unit.
Arithmetic Logic Unit:
✓ All calculations are performed in ALU.
✓ It does comparisons and takes decisions.
✓ It can perform Basic Arithmetic operations like addition, subtraction as well as logical operations like less than
greater than.
✓ After performing calculations, the result is stored in memory unit.
Program Counter:
✓ 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.
Memory Unit:
✓ Memory Unit of the computer holds data and instructions that we enter through the input unit.
✓ It is also used to preserve intermediate and final results before they are sent to the output unit.
✓ It is used to preserve the data for later usage.
✓ The various storage devices used for storage can be classified in to a categories namely,
➢ Primary Memory
➢ Secondary Memory
✓ Primary memory stores and provides information very fast but it loses the contents when we switch off the
computer.
✓ Secondary memory stores the data permanently. The program that we want to run on the computer is first
transferred to the primary memory from secondary.
Output Unit:
✓ The output unit of a computer provides information and results of an operation to the outside world.
✓ The output unit also converts Binary data to a form that uses can understand.
✓ The commonly used to output devices are Monitors, Printers, and Plotters.

Introduction to Programming Languages:


A programming language is a set of symbols, grammars and rules with the help of which one is able to translate
algorithms to programs that will be executed by the computer. The programmer communicates with a machine using
programming languages.
Program & Programming
✓ A program is a set of logically related instructions that is arranged in a sequence that directs the computer in
solving a problem.
✓ The process of writing a program is called programming.
✓ Software is a collection of computer programs and related data that provides the instructions for telling a computer
what to do and how to do it.
✓ Computer software broadly classified into two categories: a) System software and b) Application software
a) System Software:
✓ System software is a collection of programs that interfaces with the hardware.
✓ Categories of system software:

(or)

b) Application Software:
✓ Application software is written to enable the computer to solve a specific data processing task.
✓ Categories of application software:

COMPILER:
✓ For executing a program written in a high-level language, it must be first translated into a form the machine can
understand. This is done by a software called the compiler.
✓ The compiling process consists of two steps:
a) The analysis of the source program
b) Check for syntax error
Compiler action:

Advantages of Compiler
✓ A compiler translates a program in a single run.
✓ It consumes less time.
✓ CPU utilization is more.
✓ Both syntactic and semantic errors can be checked concurrently.
✓ It is easily supported by many high-level languages like C, C++, JAVA, etc.

INTERPRETER:
✓ During the process of translation There is another type of software that also does translation. This is called an
interpreter.
Advantages of Interpreter
✓ An interpreter translates the program line by line.
✓ The interpreter is smaller in size.
✓ It is flexible.
✓ Error localization is easier.
✓ The interpreter facilitates the implementation of computer programming language constructs.
Differences between compiler and interpreter:

Parameter Compiler Interpreter

Program Compilers scan the entire program in The program is interpreted/translated one line at a
scanning one go. time.

As and when scanning is performed, all


One line of code is scanned, and errors
Error detection the errors are shown in the end
encountered are shown.
together, not line by line.

Compilers convert the source code to Interpreters do not convert the source code into
Object code
object code. object code.

It is not preferred due to its slow speed. Usually,


The execution time of compiler is less,
Execution time interpreter is slow, and hence takes more time to
hence it is preferred.
execute the object code.

Need of source Compiler doesn’t require the source


It requires the source code for execution later.
code code for execution later.

Programming Programming languages that use Programming languages that uses interpreter
languages compilers include C, C++, C#, etc.. include Python, Ruby, Perl, MATLAB, etc.

Compiler can check syntactic and


Types of errors
semantic errors in the program Interpreter checks the syntactic errors only.
detected
simultaneously.

Size Compiler are larger in size. Interpreters are smaller in size.

Flexibility Compilers are not flexible. Interpreters are relatively flexible.

Efficiency Compilers are more efficient. Interpreters are less efficient.

Third, Forth & Fifth Generation Languages:


✓ The 3GLs are procedural in nature i.e., these languages specify “how to do”. Hence 3GLs require the knowledge of
complete steps to solve a problem.
✓ In case of 4GLs, they are non-procedural i.e., they specify “what to do”. Hence in 4GLs we need to specify only
what we required and rest gets done on its own
Advantages:
✓ Smaller code
✓ Reduced development time and maintenance cost
✓ Easy to programmers
✓ Doesn’t require a high knowledge on program GUI Based Languages
✓ With the invention of GUI based interfaces, many programming languages are developed that help programmer to
develop GUI applications.
Some of the GUI based languages are,
➢ Visual Basic (VB)
➢ C#
➢ VB.Net
Classification of Programming Languages:
WHAT IS COMPUTER LANGUAGE?
Generally, we use languages like English, Hindi, etc., to make communication between two persons. That means when we
want to make communication between two persons, we need a language through which persons can express their feelings.
Similarly, when we want to make communication between user and computer or between two or more computers, we need
a language through which user can give information to the computer and vice versa. When a user wants to give any
instruction to the computer the user needs a specific language and that language is known as a computer language.
The user interacts with the computer using programs and that programs are created using computer programming languages
like C, C++, Java, etc.,

Computer languages are the languages through which the user can communicate with the computer by writing
program instructions.
Every computer programming language contains a set of predefined words and a set of rules (syntax) that are used
to create instructions of a program.
Computer Languages Classification
Over the years, computer languages have been evolved from Low-Level to High-Level Languages. In the earliest days of
computers, only Binary Language was used to write programs.

LOW-LEVEL LANGUAGE (MACHINE LANGUAGE)


Low-Level language is the only language which can be understood by the computer. Binary Language is an example of a
low-level language. Low-level language is also known as Machine Language. The binary language contains only two
symbols 1 & 0. All the instructions of binary language are written in the form of binary numbers 1's & 0's. A computer can
directly understand the binary language. Machine language is also known as the Machine Code.
As the CPU directly understands the binary language instructions, it does not require any translator. CPU directly starts
executing the binary language instructions and takes very less time to execute the instructions as it does not require any
translation. Low-level language is considered as the First Generation Language (1GL).
Advantages
• A computer can easily understand the low-level language.
• Low-level language instructions are executed directly without any translation.
• Low-level language instructions require very less time for their execution.
Disadvantages
• Low-level language instructions are very difficult to use and understand.
• Low-level language instructions are machine-dependent, that means a program written for a particular machine does
not execute on another machine.
• In low-level language, there is more chance for errors and it is very difficult to find errors, debug and modify.

MIDDLE-LEVEL LANGUAGE (ASSEMBLY LANGUAGE)


Middle-level language is a computer language in which the instructions are created using symbols such as letters, digits and
special characters. Assembly language is an example of middle-level language. In assembly language, we use predefined
words called mnemonics. Binary code instructions in low-level language are replaced with mnemonics and operands in
middle-level language. But the computer cannot understand mnemonics, so we use a translator called Assembler to
translate mnemonics into binary language. Assembler is a translator which takes assembly code as input and produces
machine code as output. That means, the computer cannot understand middle-level language, so it needs to be translated
into a low-level language to make it understandable by the computer. Assembler is used to translate middle-level language
into low-level language.
Advantages
• Writing instructions in a middle-level language is easier than writing instructions in a low-level language.
• Middle-level language is more readable compared to low-level language.
• Easy to understand, find errors and modify.
Disadvantages
• Middle-level language is specific to a particular machine architecture, that means it is machine-dependent.
• Middle-level language needs to be translated into low-level language.
• Middle-level language executes slower compared to low-level language.
High-Level Language
A high-level language is a computer language which can be understood by the users. The high-level language is very
similar to human languages and has a set of grammar rules that are used to make instructions more easily. Every high-level
language has a set of predefined words known as Keywords and a set of rules known as Syntax to create instructions. The
high-level language is easier to understand for the users but the computer cannot understand it. High-level language needs
to be converted into the low-level language to make it understandable by the computer. We use Compiler or interpreter to
convert high-level language to low-level language.
Languages like COBOL, FORTRAN, BASIC, C, C++, JAVA, etc., are examples of high-level languages.
All these programming languages use human-understandable language like English to write program instructions. These
instructions are converted to low-level language by the compiler so that it can be understood by the computer.
Advantages
• Writing instructions in a high-level language is easier.
• A high-level language is more readable and understandable.
• The programs created using high-level language runs on different machines with little change or no change.
• Easy to understand, create programs, find errors and modify.
Disadvantages
• High-level language needs to be translated into low-level language.
• High-level language executes slower compared to middle and low-level languages.

UNDERSTANDING COMPUTER LANGUAGES


The following figure provides a few key points related to computer languages.

From the above figure, we can observe the following key points...
• The programming languages like C, C++, Java, etc., are written in High-level language which is more comfortable
for the developers.
• A high-level language is closer to the users.
• Low-level language is closer to the computer. Computer hardware can understand only the low-level language
(Machine Language).
• The program written in the high-level language needs to be converted to low-level language to make
communication between the user and the computer.
• Middle-level language is not closer to both user and computer. We can consider it as a combination of both high-
level language and low-level language.
EXECUTION PROCESS OF A C PROGRAM

IMPORTANT POINTS
• C program file (Source file) must save with .c extension.
• The compiler converts complete program at a time from high-level language to low-level language.
• Input to the compiler is .c file and output from the compiler is .exe file, but it also generates .obj file in this process.
• The compiler converts the file only if there are no errors in the source code.
• CPU places the result in User Screen window.
PROGRAM DEVELOPMENT LIFE CYCLE
When we want to develop a program using any programming language, we follow a sequence of steps. These steps are
called phases in program development. The program development life cycle is a set of steps or phases that are used to
develop a program in any programming language.
• Problem Definition
• Problem Analysis
• Algorithm Development
• Coding & Documentation
• Testing & Debugging
• Maintenance

1. PROBLEM DEFINITION
In this phase, we define the problem statement and we decide the boundaries of the problem. In this phase we need to
understand the problem statement, what is our requirement, what should be the output of the problem solution. These are
defined in this first phase of the program development life cycle.
2. PROBLEM ANALYSIS
In phase 2, we determine the requirements like variables, functions, etc. to solve the problem. That means we gather the
required resources to solve the problem defined in the problem definition phase. We also determine the bounds of the
solution.
3. ALGORITHM DEVELOPMENT
During this phase, we develop a step-by-step procedure to solve the problem using the specification given in the previous
phase. This phase is very important for program development. That means we write the solution in step-by-step statements.
4. CODING & DOCUMENTATION
This phase uses a programming language to write or implement the actual programming instructions for the steps defined in
the previous phase. In this phase, we construct the actual program. That means we write the program to solve the given
problem using programming languages like C, C++, Java, etc.,
5. TESTING & DEBUGGING
During this phase, we check whether the code written in the previous step is solving the specified problem or not. That
means we test the program whether it is solving the problem for various input data values or not. We also test whether it is
providing the desired output or not.
6. MAINTENANCE
During this phase, the program is actively used by the users. If any enhancements found in this phase, all the phases are to
be repeated to make the enhancements. That means in this phase, the solution (program) is used by the end-user. If the user
encounters any problem or wants any enhancement, then we need to repeat all the phases from the starting, so that the
encountered problem is solved or enhancement is added.
C Background
C is a structured programming language. It is also known as function orientated programming language. C programming
language was developed in the year of 1972 by Dennis Ritchie at Bell Laboratories in the USA (AT & T).

In the year of 1968, research was started by Dennis Ritchie on programming languages like BCPL, CPL. The main aim of
his research was to develop a new language to create an OS called UNIX. After four years of research, a new programming
language was created with solutions for drawbacks in languages like BCPL & CPL. In the year of 1972, the new language
was introduced with the name “Traditional C”.
• The name 'c' was selected from the sequence of previous language ‘B’ (BCPL) because most of the features of 'c'
were derived from BCPL (B language).
• The first outcome of the c language was the UNIX operating system. The initial UNIX OS was completely
developed using 'c' programming language.
• The founder of the ‘C’ language, Dennis Ritchie is known as “Father of C” and also “Father of UNIX”.
• The c programming language is very popular because it is reliable, simple and easy to use and it is the base for
almost all the other programming languages.
• The following are the language before ‘c’ & various versions of ‘c’.

1. CPL (Common Programming Language)


The CPL was invented by Martin Richards at the University of Cambridge in the early of 1960s.
2. BCPL (Basic Combined Programming Language)
The BCPL was invented by Martin Richards at the University of Cambridge in the year of 1966. It was a popular
programming language at that time. BCPL allows the user, direct access to the computer memory. BCPL is the extension of
CPL.
3. B Language
B language is derived from BCPL. It was introduced in the year of 1969 by Ken Thompson and Dennis Ritchie at Bell
Laboratory, USA. The B language is similar to BCPL.
4. C Language
C language is derived from the B language. It was introduced in the year of 1972 by Dennis Ritchie at Bell Laboratory,
USA. The C language was mainly developed to create an operating system called UNIX. The name C is given based on the
previous language B and BCPL. Ninety percent of the UNIX operating system code is written in C language. During the
1970s, the C language became a very popular
programming language. Many universities and organizations began creating their version of C language for their respective
projects. So, C language has got many variants at that time. Later it was standardized.
5. ANSI C (C89)
In the year of 1983, the ANSI (American National Standards Institute) formed a committee to frame standard specifications
for the C language. In the year of 1989, this committee introduced a standard version of C with the name "ANSI C" with
standard library files. The ANSI C is also called as C89 in short form.
6. C90
In the year of 1990, the ANSI C was got ISO (International Organization for Standardization) standardization with the
inclusion of a few new features like new library files, new processor commands. And it was also added with keywords
const, volatile and signed, etc... ISO standardized ANSI C as ISO/IEC 9899:1990. This version is called as C90 in short
form.
7. C99
In the year of 1995, many new features were added to the C90 to create a new version of it. This new version of C was got
ISO standardization in the year of 1999 with the name ISO/IEC 9899:1999. In the short form, it is called as C99. Later C99
became the official standard version of C.
General rules for any C program
• Every executable statement must end with a semicolon symbol (;).
• Every C program must contain exactly one main method (Starting point of the program execution).
• All the system-defined words (keywords) must be used in lowercase letters.
• Keywords cannot be used as user-defined names(identifiers).
• For every open brace ({), there must be respective closing brace (}).
• Every variable must be declared before it is used.
Basics of a Computer Program:
Computer Programming is a set of instructions, that helps the developer to perform certain tasks that return the desired
output for the given valid inputs.
Example: Given below is a Mathematical Expression,
✓ Z = X + Y, where X, Y, and Z are the variables in a programming language.
✓ If X = 550 and Y = 450, value of X and Y are the input values that are called literals.
✓ To calculate the value of X+Y, which results in Z, i.e. the expected output.
A computer is a machine that processes information and this information can be any data that is provided by the user
through devices such as keyboards, mice, scanners, digital cameras, joysticks, and microphones, These devices are
called Input Devices and the information provided is called input.
The computer requires storage to store this information and the storage is called Memory. Computer Storage or
Memory is of Two Types. (i) Primary Memory or RAM (Random Access Memory): This is the internal storage that is
used in the computers and is located on the motherboard. RAM can be accessed or modified quickly in any order or
randomly. The information that is stored in RAM is lost when the computer is turned off called as Volatile. (ii) Secondary
Memory or ROM (Read-Only Memory): Information (data) stored in ROM is read-only, and is stored permanently
called as Non-Volatile. The ROM stored instruction is required to start a computer.
Processing: Operations done on this information (input data) is called Processing. The Processing of input is done in the
Central Processing Unit which is popularly known as CPU.
Output Devices: These are the computer hardware devices that help in converting information into human-readable form.
Some of the output devices include Visual Display Units (VDU) such as a Monitor, Printer, Graphics Output devices,
Plotters, Speakers, etc.
➢ Developers should have essential knowledge on the following concepts to become skilled in Computer
Programming,
✓ Algorithm: It is a set of steps or instruction statements to be followed to accomplish specific tasks.
✓ Source code: Source code is the actual text used to construct the program using C language.
void main()
{
// Steps to be performed
}
✓ Compiler: Compiler is a software program that helps in converting the source code into binary code.
✓ Data Type: Data of different types, integer, floating-point, character.
✓ Variable: Variable is a space holder to store value in memory used in program. Example, int age = 25.
✓ Conditionals: a certain condition should execute only if true or false to exit.
✓ Array: Array is the variable that stores elements of a similar data type. Example: int a[10]
✓ Loop: Loop is used to execute the series of code until the condition is true. Example, for, while, do-while.
✓ Function: Functions or methods are used to accomplish a task in programming, a function can take parameters and
process them to get the desired output. Functions are used to reuse them whenever required at any place repeatedly.
Algorithms:
Definition:
An algorithm is defined as a finite set of steps that provide a chain of actions for solving a problem. (or) An
algorithm is a sequence of instructions that are carried out in a predetermined sequence in order to solve a problem. (or)
A step-by-step procedure used to solve a problem is called Algorithm. (or) An algorithm (pronounced AL-go-rith-um) is
a procedure or formula for solving a problem, based on conducting a sequence of specified actions.

Procedure for writing an algorithm:


An Algorithm is a well-organized and textual computational module that receives one or more input
values and provides one or more output values.
✓ These well-defined steps are arranged in a sequence that processes given input into output.
✓ The steps of the algorithm are written using English like statements which are easy to understand.
✓ This will enable the reader to translate each step into a program.
✓ Every step is known as instruction.
✓ An algorithm is set to be accurate only when it provides the exact required output.
✓ If the procedure is lengthy then sub divided into small parts as it makes easy to solve the problem.
Analyzing an Algorithm:
When one writes an algorithm, it is essential to know how to analyses the algorithm.
✓ Analyzing the algorithm refers to calculating the resources such as computer memory, processing time,
logic gates and so on …..
✓ Time is most important resource because the program developed should be faster in processing.
✓ The analysis can also be made by reading the algorithm for logical accuracy, tracing the algorithm and
checking with the data.
Categories of Algorithm:
The steps in an algorithm can be divided into three categories, namely
➢ Sequence
➢ Selection and
➢ Iteration
Sequence
✓ The steps described in an algorithm are performed successively one by one without skipping any step.
✓ The sequence of steps defined in an algorithm should be simple and easy to understand.

Example: // adding two timings


Step 1: start
Step 2: read h1, m1, h2, m2
Step 3: m=m1+m2
Step 4: h= h1 + h2 + m/60
Step 5: m=m mod 60
Step 6: write h and m
Step 7: stop
Selection
✓ We understand that the algorithms written in sequence fashion are not reliable. There must be a procedure
to handle operation failure occurring during execution.
✓ The selection of statements can be shown as follows,
if(condition)
Statement-1;
else
Statement-2;
✓ The above syntax specifies that if the condition is true, statement-1 will be executed otherwise
statement-2 will be executed.
✓ In case the operation is unsuccessful. Then sequence of algorithm should be changed / corrected in such a
way that the system will re-execute until the operation is successful.
Example: // Person eligibility for vote
Step 1: start
Step 2: read age
Step 3: if age > = 18 then step_4 else step_5
Step 4: write “person is eligible for vote”
Step 5: write “person is not eligible for vote”
Step 6: stop
Iteration
✓ In a program, sometimes it is very necessary to perform the same action for a number of times.
✓ If the same statement is written repetitively, it will increase the program code.
✓ To avoid this problem, iteration mechanism is applied.
✓ The statement written in an iteration block is executed for a given number of times based on certain
condition.
Example: // sum of individual digits in the given number
Step 1: start
Step 2: read n
Step 3: repeat step 4 until n>0
Step 4: (a) r=n mod 10
(b) s=s+r
(c) n=n/10
Step 5: write s
Step 6: stop
Some more examples:
Algorithm to add two numbers: Algorithm to find largest among three numbers:
Step 1: START Step 1: Start
Step 2: Declare integers a, b & c Step 3: Define values of Step 2: Declare variables a,b and c. Step 3: Read variables
a&b a,b and c.
Step 4: add values of a & b Step 4: If a > b
Step 5: store output of step 4 to c Step 6: print c If a > c
Step 7: STOP Display a is the largest. else
Display c is the largest.
Algorithm to find odd or even number: else
Step 1: Start If b > c
Step 2: [Take Input] Read: Number Step 3: Check: Display b is the largest.
If Number%2 == 0 Then else
Print : N is an Even Number. Display c is the largest.
Else Step 5: Stop
Print : N is an Odd Number.
Step 4: Exit

Flowcharts

A flowchart is an alternative technique for solving a problem. Instead of descriptive steps, we use pictorial
representation for every step.

Definition:
Flowchart is a diagrammatic or pictorial representation of various steps involved in the Algorithm.

A complete flowchart enables us to organize the problem into a plan of actions i.e. it specifies what comes first,
second, third, . . . .
✓ Flowchart also represents the flow of data.
✓ It is an easy way to solve the complex problems because it makes the reader to flow the process
quickly from the flowchart incited of going through text.
✓ A flowchart is a set of symbols that indicates various operations in a program.
✓ For every process there is a corresponding symbol in the flowchart.
✓ Once the algorithm is written, its pictorial representation can be done using flowchart symbol.
Some of the commonly used flowchart symbols are listed below
Note: (Name of the Symbols)
Oval, Diamond, Circle, Square (or) Rectangle, Parallelogram, hexagon shaped symbol, arrows (Data Flow lines),
Subroutine Symbol (rectangle with a line at each end of the shape).
Flowchart Example:
•Problem 1: Draw a flowchart to find the sum of two numbers.

•Problem 2: Draw a flowchart to calculate the average of three two numbers.

•Problem 3: Draw a flowchart to find the greatest of two numbers.


•Problem 4: Draw a flowchart to swap two numbers.

Pseudo Code
A Pseudocode is defined as a step-by-step description of an algorithm. Pseudocode does not use any
programming language in its representation instead it uses the simple English language text as it is intended for
human understanding rather than machine reading.
Pseudocode is the intermediate state between an idea and its implementation (code) in a high-level
language.
Algorithm and Pseudocode are the two related terms in computer programming. The basic difference
between algorithm and pseudocode is that an algorithm is a step-by-step procedure developed to solve a
problem, while a pseudocode is a technique of developing an algorithm.
What is the need for Pseudocode
Pseudocode is an important part of designing an algorithm, it helps the programmer in planning the
solution to the problem as well as the reader in understanding the approach to the problem. Pseudocode is an
intermediate state between algorithm and program that plays supports the transition of the algorithm into the
program.

Pseudocode is an intermediate state between algorithm and program


Five important rules for writing pseudocode are:
➢ Write one statement per line.
➢ Initial keywords should be represented in capital case (READ, WRITE, IF, WHILE, UNTIL).
➢ Indentation of pseudocode should be similar to the actual program to show hierarchy.
➢ Ending the multiline structure is necessary.
➢ Keep statements in simple language (English).
Difference between Algorithm and Pseudocode:

Algorithm Pseudocode
An Algorithm is used to provide a solution to A Pseudocode is a step-by-step description of
a problem in form of a well-defined step-based an algorithm in code-like structure using English
form. text.
An algorithm only uses simple English words It uses reserved keywords like if-else, for, while,
etc.
These are a sequence of steps of a solution to a These are fake codes as the word pseudo means
problem fake, using code like structure and plain English
text
There are no rules to writing algorithms There are certain rules for writing pseudocode
Algorithms can be considered pseudocode Pseudocode cannot be considered an algorithm
It is difficult to understand and interpret It is easy to understand and interpret
Example 1:
To implement a simple program that calculates the average of three numbers using pseudo code in C:
Pseudo code:
1. Start
2. Input three numbers
3. Calculate the sum of the three numbers
4. Divide the sum by 3 to get the average
5. Display the average
6. End
7.

Example 2:
To find the Factorial value of the given number using pseudo code in C:
Algorithm to find Factorial of n: Pseudocode to Factorial of n: C program to find Factorial of n:
Step 1: start Start program #include<stdio.h>
Step 2: initialize fact = 1 Declare fact and n void main()
Step 3: input the user value n Enter number for n {
Step 4: for i=1 to i <= n repeat for i=1 to i <=n int n, fact=1,i;
the process Perform fact = fact printf("enter value for n: ");
Step 5: fact = fact * i * i Display fact scanf("%d", &n);
Step 6: i++ [increment i by one] End program for(i=1; i<=n; i++)
Step 7: print fact value { fact=fact*i; }
Step 8: stop printf("\n factorial is: %d", fact);
}

P BHANU PRAKASH 9676288008 [email protected] 21


Example 3:
To find the Sum of Natural Numbers up to the given number using pseudo code in C:
Algorithm to find the Sum of pseudo-code to find the Sum of C program to find the Sum of
Natural Numbers up to n: Natural Numbers up to n: Natural Numbers up to n:

Step 1: start Start program #include<stdio.h>


Step 2: declare and initialize Declare variables n, sum=0 and i void main()
n, sum = 0 and i Enter the number for n {
Step 3: Input number n For i=1 to i<=n int n, sum=0, i;
Step 4: for i=1 to i<=n Perform operation sum = sum + printf("enter no of terms: ");
Step 5: sum = sum + i i Increment i value by one scanf("%d", &n);
Step 6: i++ [increment i by one] Print sum for(i=1; i<=n; i++)
Step 7: print sum End program { sum = sum+i; }
Step 8: stop printf("sum of series=%d",sum);
}

INTRODUCTION TO COMPILATION AND EXECUTION:

(i) Compilation of the High Level Language:

Compilation process in C is also known as the process of converting Human Understandable


Code (C Program) into a Machine Understandable Code (Binary Code). Compilation process in C
involves four steps: pre-processing, compiling, assembling, and linking.
➢ The preprocessor tool helps in comments removal, macros expansion, file inclusion, and
conditional compilation. These commands are executed in the first step of the compilation
process.
➢ Compiler software helps boost the program's performance and translates the intermediate file to
an assembly file.
➢ Assembler helps convert the assembly file into an object file containing machine-level code.
➢ Linker is used for linking the library file with the object file. It is the final step in
compilation to generate an executable file.

The compiling process consists of two steps:


i) The analysis of the source program and
ii) ii) The synthesis of the object program in the machine language of the
specified machine.
➢ The analysis phase uses the precise description of the source programming language.
➢ A source language is described using a) lexical rules, b) syntax rules, and () semantic rules.

P BHANU PRAKASH 9676288008 [email protected] 22


EXECUTION PROCESS OF A C PROGRAM

(ii)Execution Steps of a Program:


The following are the execution steps of a program:
➢ Translation of the program resulting in the object program.
➢ Linking of the translated program with other object programs needed for execution, thereby resulting in a binary
program.
➢ Relocation of the program to execute from the specific memory area allocated to it.
➢ Loading of the program in the memory for the purpose of execution.
Linker:
➢ Linking resolves symbolic references between object programs.
➢ It makes object programs known to each other.
➢ Linking makes the addresses of programs known to each other so that transfer of control from one subprogram to
another or a main program takes place during execution.
➢ In FORTRAN / COBOL, all program units are translated separately.
Relocation:
➢ Relocation is more than simply moving a program from one area to another in the main memory.
➢ Relocation means adjustment of all address-dependent locations, such as address constant,
➢ correspond to the allocated space, which means simple modification of the object program so that it can be
loaded at an address different from the location originally specified.
Loader:
Loading means physically placing the machine instructions and data into main memory, also known as primary
storage area.
➢ Assignment of load-time storage area to the program
➢ Loading of program into assigned area
➢ Relocation of program to execute properly from its load time storage area
➢ Linking of programs with one another
Program Execution:
➢ When a program is compiled and linked, each instruction and each item of data is assigned an address.
➢ At execution time, the CPU finds instructions and data from these addresses.

P BHANU PRAKASH 9676288008 [email protected] 23


➢ The program counter, is a CPU register that holds the address of the next instruction to be executed in a
program.
➢ The CPU has random access capability to any and all words of the memory, no matter what their addresses

General rules for any C program


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

STRUCTURE OF C PROGRAM

P BHANU PRAKASH 9676288008 [email protected] 24


Line 1: Comments - They are ignored by the compiler
This section is used to provide a small description of the program. The comment lines are simply ignored
by the compiler, that means they are not executed. In C, there are two types of comments.

• Single Line Comments: Single line comment begins with // symbol. We can write any number of
single line comments.
• Multiple Lines Comments: Multiple lines comment begins with /* symbol and ends with */. We can
write any number of multiple lines comments in a program.
In a C program, the comment lines are optional. Based on the requirement, we write comments. All the
comment lines in a C program just provide the guidelines to understand the program and its code.
Line 2: Preprocessing Commands
Preprocessing commands are used to include header files and to define constants. We use the #include
statement to include the header file into our program. We use a #define statement to define a constant. The
preprocessing statements are used according to the requirements. If we don't need any header file, then no
need to write #include statement. If we don't need any constant, then no need to write a #define statement.
Line 3: Global Declaration
The global declaration is used to define the global variables, which are common for all the functions after
its declaration. We also use the global declaration to declare functions. This global declaration is used
based on the requirement.
Line 4: int main()
Every C program must write this statement. This statement (main) specifies the starting point of the C
program execution. Here, main is a user-defined method which tells the compiler that this is the starting
point of the program execution. Here, int is a data type of a value that is going to return to the Operating
System after completing the main method execution. If we don't want to return any value, we can use it as
void.
Line 5: Open Brace ( { )
The open brace indicates the beginning of the block which belongs to the main method. In C program,
every block begins with a '{' symbol.
Line 6: Local Declaration
In this section, we declare the variables and functions that are local to the function or block in which they
are declared. The variables which are declared in this section are valid only within the function or block in
which they are declared.
Line 7: Executable statements
In this section, we write the statements which perform tasks like reading data, displaying the result,
calculations, etc., All the statements in this section are written according to the requirements.
Line 9: Closing Brace (})
The close brace indicates the end of the block which belongs to the main method. In C program every block
end with a '}' symbol.
Line 10, 11, 12, ...: User-defined function ()
This is the place where we implement the user-defined functions. The user-defined function
implementation can also be performed before the main method. In this case, the user-defined function need
not be declared. Directly it can be implemented, but it must be before the main method. In a program, we
can define as many user-defined functions as we want. Every user-defined function needs a function call to
execute its statements.

P BHANU PRAKASH 9676288008 [email protected] 25


CHARACTER SET
As every language contains a set of characters used to construct words, statements, etc., C language also
has a set of characters which include alphabets, digits, and special symbols. C language supports a total of
256 characters.

Every C program contains statements. These statements are constructed using words and these words are
constructed using characters from C character set.
• Alphabets
• Digits
• Special Symbols
Alphabets
C language supports all the alphabets from the English language. Lower- and upper-case letters together
support 52 alphabets.
• lower case letters - a to z
• UPPER CASE LETTERS - A to Z
Digits
C language supports 10 digits which are used to construct numerical values in C language.
• Digits - 0, 1, 2, 3, 4, 5, 6, 7, 8, 9
Special Symbols
• C language supports a rich set of special symbols that include symbols to perform mathematical
operations, to check conditions, white spaces, backspaces, and other special symbols.
• Special Symbols - ~ @ # $ % ^ & * ( ) _ - + = { } [ ] ; : ' " / ? . > , < \ | tab newline space NULL bell
backspace vertical tab etc.,
Commonly used characters in C with their ASCII values

P BHANU PRAKASH 9676288008 [email protected] 26


C Program to Print All the Characters of C Character Set
#include <stdio.h>
int main()
{
// Declare Variables
int i = 0;
printf("Character \t ASCII Value\n\n");
//Print ASCII Values
for (i = 65; i <=122; i++) {
printf("%c \t\t %d\n", i, i);
}
return 0;
}
C TOKENS
Every C program is a collection of instructions and every instruction is a collection of some individual
units. Every smallest individual unit of a c program is called token. Every instruction in a c program is a
collection of tokens. Tokens are used to construct c programs and they are said to the basic building blocks
of a c program.
• Keywords
• Identifiers
• Operators
• Special Symbols
• Constants
• Strings
• Data values

In a C program, a collection of all the keywords, identifiers, operators, special symbols,


constants, strings, and data values are called tokens.

C KEYWORDS
As every language has words to construct statements, C programming also has words with a specific
meaning which are used to construct c program instructions. In the C programming language, keywords are
special words with predefined meaning. Keywords are also known as reserved words in C programming
language.
In the C programming language, there are 32 keywords. All the 32 keywords have their meaning which is
already known to the compiler.
Properties of Keywords
➢ All the keywords in C programming language are defined as lowercase letters so they must be used
only in lowercase letters
➢ Every keyword has a specific meaning, users can not change that meaning.
➢ Keywords cannot be used as user-defined names like variable, functions, arrays, pointers, etc...

P BHANU PRAKASH 9676288008 [email protected] 27


➢ Every keyword in C programming language represents something or specifies some kind of action
to be performed by the compiler.

auto Break case char const continue default do

double Else enum extern float for goto if

int Long register return short signed sizeof static

struct Switch typedef union unsigned void volatile while

P BHANU PRAKASH 9676288008 [email protected] 28


C IDENTIFIERS
In C programming language, programmers can specify their name to a variable, array, pointer, function,
etc... An identifier is a collection of characters which acts as the name of variable, function, array, pointer,
structure, etc... In other words, an identifier can be defined as the user-defined name to identify an entity
uniquely in the c programming language that name may be of the variable name, function name, array
name, pointer name, structure name or a label.
The identifier is a user-defined name of an entity to identify it uniquely during the program execution
Example
int marks;
char studentName[30];

Here, marks and studentName are identifiers

Rules for Creating Identifiers


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

Rules for Creating Identifiers for better programming


➢ The identifier must be meaningful to describe the entity.
➢ Since starting with an underscore may create conflict with system names, so we avoid starting an
identifier with an underscore.
➢ We start every identifier with a lowercase letter. If an identifier contains more than one word then
the first word starts with a lowercase letter and second word onwards first letter is used as an
UPPERCASE letter. We can also use an underscore to separate multiple words in an identifier.

C DATA TYPES
Def: -The Data type is a set of value with predefined characteristics. Data types are used to declare
variable, constants, arrays, pointers, and functions.

➢ Data used in c program is classified into different types based on its properties. In the C
programming language, a data type can be defined as a set of values with similar characteristics. All
the values in a data type have the same properties.

➢ Data types in the c programming language are used to specify what kind of value can be stored in a
variable. The memory size and type of the value of a variable are determined by the variable data
type. In a c program, each variable or constant or array must have a data type and this data type

P BHANU PRAKASH 9676288008 [email protected] 29


specifies how much memory is to be allocated and what type of values are to be stored in that
variable or constant or array.
In the c programming language, data types are classified as follows...

➢ Primary data types (Basic data types OR Predefined data types)


➢ Derived data types (Secondary data types OR User-defined data types)
➢ Enumeration data types
➢ Void data type

PRIMARY DATA TYPES


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

P BHANU PRAKASH 9676288008 [email protected] 30


INTEGER DATA TYPE
The integer data type is a set of whole numbers. Every integer value does not have the decimal
value. We use the keyword "int" to represent integer data type in c. We use the keyword int to declare the
variables and to specify the return type of a function. The integer data type is used with different type
modifiers like short, long, signed and unsigned.

FLOATING POINT DATA TYPES


Floating-point data types are a set of numbers with the decimal value. Every floating-point value
must contain the decimal value. The floating-point data type has two variants...
• float
• double
We use the keyword "float" to represent floating-point data type and "double" to represent double
data type in c. Both float and double are similar but they differ in the number of decimal places. The float
value contains 6 decimal places whereas double value contains 15 or 19 decimal places.

P BHANU PRAKASH 9676288008 [email protected] 31


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

Example Program
#include <stdio.h>
void main()
{
// Determine and Print the size of int
printf("Size of int: %u bytes\n", sizeof(int));

// Determine and Print the size of float


printf("Size of float: %u bytes\n", sizeof(float));

// Determine and Print the size of double


printf("Size of double: %u bytes\n", sizeof(double));

// Determine and Print the size of char


printf("Size of char: %u bytes\n", sizeof(char));
}

P BHANU PRAKASH 9676288008 [email protected] 32


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

ENUMERATED DATA TYPE


An enumerated data type is a user-defined data type that consists of integer constants and each
integer constant is given a name. The keyword "enum" is used to define the enumerated data type.

DERIVED DATA TYPES


Derived data types are user-defined data types. The derived data types are also called as user-
defined data types or secondary data types. In the c programming language, the derived data types are
created using the following concepts...
• Arrays
• Structures
• Unions
• Enumeration

C VARIABLES
Def: - Variable is a name given to a memory location where we can store different values of the same data
type during the program execution.
Variables in a c programming language are the named memory locations where the user can store
different values of the same data type during the program execution. That means a variable is a name given
to a memory location in which we can store different values of the same data type. In other words, a
variable can be defined as a storage container to hold values of the same data type during the program
execution.
Every variable in c programming language must be declared in the declaration section before it is
used. Every variable must have a data type that determines the range and type of values be stored and the
size of the memory to be allocated.
A variable name may contain letters, digits and underscore symbol.
1. Variable name should not start with a digit.
2. Keywords should not be used as variable names.
3. A variable name should not contain any special symbols except underscore (_).
4. A variable name can be of any length but compiler considers only the first 31 characters of the
variable name.
DECLARATION OF VARIABLE
Declaration of a variable tells the compiler to allocate the required amount of memory with the
specified variable name and allows only specified data type values into that memory location. In C
programming language, the declaration can be performed either before the function as global variables or
inside any block or function. But it must be at the beginning of block or function.

P BHANU PRAKASH 9676288008 [email protected] 33


Declaration Syntax:
data type variable _Name;
Example
int number;

The above declaration tells to the compiler that allocates 2 bytes of memory with the name number and
allows only integer values into that memory location.

C CONSTANTS

Def: - A constant is a named memory location which holds only one value throughout the program
execution.
In C programming language, a constant is similar to the variable but the constant hold only one
value during the program execution. That means, once a value is assigned to the constant, that value can't
be changed during the program execution. Once the value is assigned to the constant, it is fixed throughout
the program.
In C programming language, a constant can be of any data type like integer, floating-point,
character, string and double, etc.,
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
INTEGER CONSTANTS
An integer constant can be a decimal integer or octal integer or hexadecimal integer. A decimal
integer value is specified as direct integer value whereas octal integer value is prefixed with 'o' and
hexadecimal value is prefixed with 'OX'.
An integer constant can also be unsigned type of integer constant or long type of integer constant.
Unsigned integer constant value is suffixed with 'u' and long integer constant value is suffixed with 'l'
whereas unsigned long integer constant value is suffixed with 'ul'.
EXAMPLE
125 -----> Decimal Integer Constant
O76 -----> Octal Integer Constant
OX3A -----> Hexa Decimal Integer Constant

P BHANU PRAKASH 9676288008 [email protected] 34


50u -----> Unsigned Integer Constant
30l -----> Long Integer Constant
100ul -----> Unsigned Long Integer Constant
FLOATING POINT CONSTANTS
A floating-point constant must contain both integer and decimal parts. Some times it may also
contain the exponent part. When a floating-point constant is represented in exponent form, the value must
be suffixed with 'e' or 'E'.
EXAMPLE
The floating-point value 3.14 is represented as 3E-14 in exponent form.
CHARACTER CONSTANTS
A character constant is a symbol enclosed in single quotation. A character constant has a maximum
length of one character.
EXAMPLE
'A'
'2'
'+'
In the C programming language, there are some predefined character constants called escape sequences.
Every escape sequence has its own special functionality and every escape sequence is prefixed with '\'
symbol. These escape sequences are used in output function called 'printf()'.
STRING CONSTANTS
A string constant is a collection of characters, digits, special symbols and escape sequences that are
enclosed in double quotations.

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


"This is YNOT learnings"
We can define string constant using multiple lines as follows...
" This\
is\
YNOT learnings "
We can also define string constant by separating it with white space as follows...
"This" "is" " YNOT learnings "

All the above three defines the same string constant.

CREATING CONSTANTS IN C
In a c programming language, constants can be created using two concepts...
• Using the 'const' keyword
• Using '#define' preprocessor

P BHANU PRAKASH 9676288008 [email protected] 35


USING THE 'CONST' KEYWORD
We create a constant of any data type using 'const' keyword. To create a constant, we prefix the
variable declaration with 'const' keyword.
The general syntax for creating constant using 'const' keyword is as follows...
const datatype constantName;
OR
const datatype constantName = value;
Example
const int x = 10;
Here, 'x' is a integer constant with fixed value 10.
Example Program
#include<stdio.h>
#include<conio.h>
void main()
{
int i = 9 ;
const int x = 10 ;
i = 15 ;
x = 100 ; // creates an error
printf("i = %d\nx = %d", i, x ) ;
}
Output: - The above program gives an error because we are trying to change the constant variable value (x
= 100).
USING '#DEFINE' PREPROCESSOR
We can also create constants using '#define' preprocessor directive. When we create constant using
this preprocessor directive it must be defined at the beginning of the program (because all the preprocessor
directives must be written before the global declaration).
#define CONSTANTNAME value
Example
#define PI 3.14
Here, PI is a constant with value 3.14
Example Program
#include<stdio.h>
#include<conio.h>
#defien PI 3.14
void main()
{
int r, area ;
printf("Please enter the radius of circle : ") ;
scanf("%d", &r) ;
area = PI * (r * r) ;
printf("Area of the circle = %d", area) ;
}

P BHANU PRAKASH 9676288008 [email protected] 36


#include <stdio.h> #include <stdio.h>
void main() #define height 100

{ #define number 3.14


#define letter 'A'
const int height = 100; /*int constant*/
#define letter_sequence "ABC"
const float number = 3.14; /*Real constant*/
#define backslash_char '\?'
const char letter = 'A'; /*char constant*/
void main()
const char letter_sequence[10] = "ABC"; /*string
{
constant*/
printf("value of height : %d \n", height );
const char backslash_char = '\?'; /*special char cnst*/ printf("value of number : %f \n", number );
printf("value of height :%d \n", height ); printf("value of letter : %c \n", letter );
printf("value of number : %f \n", number ); printf("value of letter_sequence : %s
printf("value of letter : %c \n", letter ); \n",letter_sequence);
printf("value of letter_sequence : %s \n", letter_sequence); printf("value of backslash_char : %c

printf("value of backslash_char : %c \n", backslash_char); \n",backslash_char);


}
}

BACKSLASH CHARACTER CONSTANTS 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.
➢ Given below is the list of special characters and their purpose.
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
\N Octal constant (N is an octal constant)
\XN Hexadecimal constant (N – hex.dcml cnst)

P BHANU PRAKASH 9676288008 [email protected] 37


INPUT & OUTPUT

Input means to provide the program with some data to be used in it and Output means to display data on
the screen or write the data to a printer or a file.
The C programming language provides standard library functions to read any given input and display
output on the console.
➢ Standard Input (stdin)
➢ Standard Output (stdout)
Standard input or stdin is used for taking input and Standard output or stdout is used for giving output. The
functions used for standard input and output are present in the stdio.h header file. Hence, to use those
functions, we need to include the stdio.h header file in our program.
#include <stdio.h>
C language offers us several built-in functions for performing input/output operations.
1. printf() function - Show Output
2. scanf() function - Take Input
3. getchar() and putchar() function
4. gets() and puts() function
1. THE PRINTF() FUNCTION
The printf() function is the most used function in the C language. This function is defined in the
stdio.h header file and is used to show output on the console (standard output).

int printf(const char *format, ...);

printf() Code Examples

1. Print a sentence
#include <stdio.h>
int main()
{
// using printf()
printf("Welcome to c language");
return 0;
}
Output:
Welcome to Study c language
2. Print an Integer value
We can use the printf() function to print integer value coming from a variable using the %d format
specifier.
For example,
#include <stdio.h>

P BHANU PRAKASH 9676288008 [email protected] 38


int main() {
int x = 10;
// using printf()
printf("Value of x is: %d", x);
return 0;
}
Output:
Value of x is: 10
THE SCANF () FUNCTION
When we want to take input from the user, we use the scanf() function and store the input value into a
variable.
int scanf(const char *format, ...);

It reads data from stdin and stores it according to the parameter format into the locations pointed by the
additional arguments. On success, the function returns the number of items of the argument list successfully
filled.

The scanf() function can be used to take any data type input from user, all we have to take care is that the
variable in which we store the value should have the same data type.

Here is the syntax for scanf():


scanf("%x", &variable);
where, %x is the format specifier.

Using the format specifier, we tell the compiler what type of data is in a variable and & is the address
operator which tells the compiler the address of the variable so that the compiler can assign the variable
with the value entered by the user.
scanf() Code Examples
1. Input Integer value
If we have to take an integer value input from the user, we have to define an integer variable and then use
the scanf() function.
EXAMPLE
#include <stdio.h>
int main()
{
// using scanf()
int a;
printf("Please enter a number: ");
scanf("%d", &a);
printf("You entered: %d", a);
return 0;
}
OUTPUT
Please enter a number: 7
You entered: 7

P BHANU PRAKASH 9676288008 [email protected] 39


Take Multiple Inputs from User
EXAMPLE
#include <stdio.h>
int main() {
// using scanf() for multiple inputs
char gender;
int age;
printf("Enter your age and then gender(M, F or O): ");
scanf("%d %c", &age, &gender);
printf("You entered: %d and %c", age, gender);
return 0;
}
OUTPUT
Enter your age and then gender(M, F or O): 32 M
You entered: 32 and M

FORMAT SPECIFIERS
To print values of different data types using the printf() statement and while taking input using the
scanf() function, it is mandatory to use format specifiers.
It is a way to tell the compiler what type of data is in a variable. Some examples are %c, %d, %f, etc.

Data type Format Specifier


int %d, %i
char %c
float %f
double %lf
short int %hd
unsigned int %u
long int %li
long long int %lli
unsigned long int %lu
unsigned long long int %llu
signed char %c
unsigned char %c
long double %Lf

ESCAPE SEQUENCE
To display the output in different lines or as we wish, we use some special characters called escape
sequences. Escape sequences are special characters with special functionality used in printf() function to
format the output according to the user requirement. In the C programming language,

P BHANU PRAKASH 9676288008 [email protected] 40


Escape sequence Meaning
\n Moves the cursor to New Line
\t Inserts Horizontal Tab (5 characters space)
\v Inserts Vertical Tab (5 lines space)
\a Beep sound
\b Backspace (removes the previous character from its current position)
\\ Inserts Backward slash symbol
\? Inserts Question mark symbol
\' Inserts Single quotation mark symbol
\" Inserts Double quotation mark symbol

C STORAGE CLASSES
Storage class specifiers in C language tells to the compiler where to store a variable (Storage area of
variable), how to store the variable, Scope of variable, Default value of a variable (if it is not initialized it),
what is the initial value of the variable and life time of the variable.

Storage classes of C will provide following information to compiler.

➢ Storage area of variable


➢ Scope of variable that is in which block the variable is visible.
➢ Life time of a variable that is how long the variable will be there in active mode.
➢ Default value of a variable if it is not initialized it.

Type of Storage Class


Storage classes in mainly divided into four types,
1. auto
2. extern
3. static
4. register

Properties of All storage class

Type
Storage place Scope Life Default Value
(Keyword)

auto RAM Memory Body Within the Function Garbage value

static RAM Memory Function Program 0 (zero)

Till the end of the


extern RAM Memory Program 0 (zero)
main program.

register Register memory Body Within the Function Garbage value

P BHANU PRAKASH 9676288008 [email protected] 41


auto Storage Class
The auto storage class is the default storage class for all local variables. The scope auto variable is
within the function. It is equivalent to local variable.
Syntax
{
int roll;
auto int roll;
}
In above example define two variables with same storage class auto and their scope is within the function.

Example of auto storage class


#include<stdio.h>
#include<conio.h>
void increment ();
void main ()
{
increment ();
increment ();
increment ();
increment ();
getch();
}
void increment ()
{
auto int i = 0 ;
printf ( "%d", i ) ;
i++;
}
Output:
0000
Example Program 1 Example Program 2 Example Program 3
#include<stdio.h> #include<stdio.h> #include<stdio.h>
#include<conio.h> #include<conio.h> #include<conio.h>
int main () { int main () { int main () {
int i; int a=10; {
auto char c; { int a=20;
float f; int a=20; printf("%d",a);
printf("i = %d\tc = printf("%d",a); }
%c\tf = %f",i,c,f); } printf(" %d",a); //a is
return 0; printf(" %d",a); not visible here
} return 0; return 0;
} }

static Storage Class


The static storage class instructs the compiler to keep a local variable in existence during the life-
time of the program instead of creating and destroying it each time it comes into and goes out of scope.

P BHANU PRAKASH 9676288008 [email protected] 42


Example of static storage class
#include<stdio.h>
#include<conio.h>
void increment ();
void main ()
{
increment ();
increment ();
increment ();
increment ();
getch();
}
void increment ()
{
static int i = 0;
printf ("%d", i ) ;
i++;
}
OUTPUT:
0123
Example Program 1 Example Program 2
#include<stdio.h> #include<stdio.h>
#include<conio.h> #include<conio.h>
static int a; static int i=10;
int main () { int main () {
printf("%d",a); i=25; //Assignment statement
return 0; printf("%d”, i);
} return 0;
}
extern Storage Class
The extern storage class is used to give a reference of a global variable that is visible to ALL the
program files. It is equivalent to global variable.
Example of extern storage class
#include<stdio.h>
#include<conio.h>
int x = 20 ;
void main( )
{
extern int y;
printf("The value of x is %d \n",x);
printf("The value of y is %d",y);
getch();
}
int y=30;

P BHANU PRAKASH 9676288008 [email protected] 43


OUTPUT
The value of x is 20
The value of y is 30
Example Program 1 Example Program 2
#include<stdio.h> #include<stdio.h>
#include<conio.h> #include<conio.h>
int i; //By default it is extern variable extern int i; //extern variable
int main () { int main () {
printf("%d”, i); printf("%d",i);
return 0; return 0;
} }

Register variable
Register variables are also local variables, but stored in register memory. Whereas, auto variables
are stored in main CPU memory.
Advantages: The register variables are faster than remaining variables, because register variable are stored
in register memory not in main memory..
Limitation: But, only limited variables can be used as register since register size is very low. (16 bits, 32
bits or 64 bits).

In TC-3.0 we can't access the address of register variables.


Pointer are ptr related concepts are can't applied to register variable.
Example Example Program 1
void main() #include<stdio.h>
{
#include<conio.h>
register int a=10;
++a; int main () {
printf("\n value of a: %d",a);
register int a,b;
printf("Enter a value:");
scanf("%d",&a); scanf("%d%d",&a,&b);
--a;
printf("%d %d",a,b);
printf("\n value of a: %d",a);
}
getch();
}
OUTPUT
Input data is 50.
Error, must take address of a memory
location.

Explanation
In scanf() function if address is provided for the register variable then it will give error, if addition is
not provided it normally work.
Register storage class specifier just recommended to the compiler to hold the variable in CPU register if the
memory is available or else stored in stack area of data segment.

P BHANU PRAKASH 9676288008 [email protected] 44


Storage Memory Default
Class Keyword Location Value Scope Life Time

Automatic auto Computer Garbage Local to the block in Till the control remains within
Memory Value which the variable the block in which variable is
(RAM) has defined defined

External extern Computer Zero Global to the As long as the program’s


Memory program (i.e., execution does not come to
(RAM) Throughout the end
program)

Static static Computer Zero Local to the block in The value of the persists
Memory which the variable between different function
(RAM) has defined calls (i.e., Initialization is done
only once)

Register register CPU Garbage Local to the block in Till the control remains within
Register Value which the variable the block in which variable is
has defined defined

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

P BHANU PRAKASH 9676288008 [email protected] 45


1. Arithmetic Operators
2. Relational Operators
3. Logical Operators
4. Increment & Decrement Operators
5. Assignment Operators
6. Bitwise Operators
7. Conditional Operator
8. Special Operators
ARITHMETIC OPERATORS (+, -, *, /, %)
The arithmetic operators are the symbols that are used to perform basic mathematical operations
like addition, subtraction, multiplication, division and percentage modulo.
Operator Meaning Example
+ Addition 10 + 5 = 15
- Subtraction 10 - 5 = 5
* Multiplication 10 * 5 = 50
/ Division 10 / 5 = 2
% Remainder of the Division 5%2=1

EXAMPLE PROGRAM FOR C ARITHMETIC OPERATORS:


#include <stdio.h> OUTPUT:
int main() Addition of a, b is : 60
{ Subtraction of a, b is : 20
int a=40,b=20, add,sub,mul,div,mod; Multiplication of a, b is : 800
add = a+b; Division of a, b is : 2
sub = a-b; Modulus of a, b is : 0
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);
}

P BHANU PRAKASH 9676288008 [email protected] 46


RELATIONAL OPERATORS (<, >, <=, >=, ==, !=)
The relational operators are the symbols that are used to compare two values. That means the
relational operators are used to check the relationship between two values. Every relational operator has
two results TRUE or FALSE. In simple words, the relational operators are used to define conditions in a
program.
Operator Meaning Example

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

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

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

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

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

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

EXAMPLE PROGRAM FOR RELATIONAL OPERATORS

EXAMPLE 1: EXAMPLE 2:

#include <stdio.h> #include <stdio.h>


int main()
int main()
{
int m=40,n=20; {
if (m == n)
int a = 9;
{
printf("m and n are equal"); int b = 4;
}
printf(" a > b: %d \n", a > b);
else
{ printf("a >= b: %d \n", a >= b);
printf("m and n are not equal");
printf("a <= b: %d \n", a <= b);
}
} printf("a < b: %d \n", a < b);
OUTPUT:
printf("a == b: %d \n", a == b);
m and n are not equal
printf("a != b: %d \n", a != b);
}

P BHANU PRAKASH 9676288008 [email protected] 47


LOGICAL OPERATORS (&&, ||, !)
The logical operators are the symbols that are used to combine multiple conditions into one
condition. These operators are used to perform logical operations on the given expressions.

Operator Meaning Example

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

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


otherwise returns TRUE TRUE

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

⇒ Logical AND - Returns TRUE only if all conditions are TRUE, if any of the conditions is FALSE then
complete condition becomes FALSE.
⇒ Logical OR - Returns FALSE only if all conditions are FALSE, if any of the conditions is TRUE then
complete condition becomes TRUE.

EXAMPLE PROGRAM FOR LOGICAL OPERATORS


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

P BHANU PRAKASH 9676288008 [email protected] 48


INCREMENT & DECREMENT OPERATORS (++ & --)
The increment and decrement operators are called unary operators because both need only one
operand. The increment operators add one to the existing value of the operand and the decrement operator
subtracts one from the existing value of the operand.
Increment operators are used to increase the value of the variable by one and decrement operators
are used to decrease the value of the variable by one in C programs.
Syntax:
Increment operator: ++var_name; (or) var_name++;
Decrement operator: – -var_name; (or) var_name – -;
Example:
Increment operator: ++ i ; i ++ ;
Decrement operator: – – i ; i – – ;
Operator Meaning Example

++ Increment - Adds one to existing value int a = 5;


a++; ⇒ a = 6

-- Decrement - Subtracts one from existing value int a = 5;


a--; ⇒ a = 4

The increment and decrement operators are used infront of the operand (++a) or after the operand
(a++). If it is used infront of the operand, we call it as pre-increment or pre-decrement and if it is used after
the operand, we call it as post-increment or post-decrement.
Pre-Increment or Pre-Decrement
In the case of pre-increment, the value of the variable is increased by one before the expression
evaluation. In the case of pre-decrement, the value of the variable is decreased by one before the expression
evaluation. That means, when we use pre-increment or pre-decrement, first the value of the variable is
incremented or decremented by one, then the modified value is used in the expression evaluation.
Example Program
#include<stdio.h> OUTPUT:
#include<conio.h> i=6 j=6
void main()
{
int i = 5,j;
j = ++i; // Pre-Increment
printf("i = %d, j =
%d",i,j);
}

P BHANU PRAKASH 9676288008 [email protected] 49


Post-Increment or Post-Decrement
In the case of post-increment, the value of the variable is increased by one after the expression
evaluation. In the case of post-decrement, the value of the variable is decreased by one after the expression
evaluation. That means, when we use post-increment or post-decrement, first the expression is evaluated
with existing value, then the value of the variable is incremented or decremented by one.
Example Program
#include<stdio.h> OUTPUT:
#include<conio.h> i=6 j=5
void main(){
int i = 5,j;
j = i++; // Post-Increment
printf("i = %d, j = %d",i,j);
}

ASSIGNMENT OPERATORS (=, +=, -=, *=, /=, %=)


The assignment operators are used to assign right-hand side value (Rvalue) to the left-hand side
variable (Lvalue). The assignment operator is used in different variants along with arithmetic operators.
Operator Meaning Example

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

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

-= Subtract right-hand side value from left-hand side variable value and store A -= B
the result ⇒ A = A-B
into left-hand side variable

*= Multiply right-hand side value with left-hand side variable value and store A *= B
the result ⇒ A = A*B
into left-hand side variable

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

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

EXAMPLE PROGRAM FOR C ASSIGNMENT OPERATORS:


In this program, values from 0 – 9 are summed up and total “45” is displayed as output.
Assignment operators such as “=” and “+=” are used in this program to assign the values and to sum up the
values.

P BHANU PRAKASH 9676288008 [email protected] 50


# include <stdio.h> OUTPUT: Total = 45
int main()
{
int Total=0,i;
for(i=0;i<10;i++)
{
Total+=i; // This is same as Total = Toatal+i
}
printf("Total = %d", Total);
}

BITWISE OPERATORS (&, |, ^, ~, >>, <<)


The bitwise operators are used to perform bit-level operations in the c programming language.
When we use the bitwise operators, the operations are performed based on the binary values.
Let us consider two variables A and B as A = 25 (11001) and B = 20 (10100).

Operator Meaning Example

& the result of Bitwise AND is 1 if all the bits are 1 otherwise it is A & B
0 ⇒ 16 (10000)

| the result of Bitwise OR is 0 if all the bits are 0 otherwise it is 1 A | B


⇒ 29 (11101)

^ the result of Bitwise XOR is 0 if all the bits are same otherwise A^B
it is 1 ⇒ 13 (01101)

~ the result of Bitwise once complement is negation of the bit ~A


(Flipping) ⇒ 6 (00110)

<< the Bitwise left shift operator shifts all the bits to the left by the A << 2
specified number of positions ⇒ 100 (1100100)

>> the Bitwise right shift operator shifts all the bits to the right by A >> 2
the specified number of positions ⇒ 6 (00110)

Bit wise operators in C language are & (bitwise AND), | (bitwise OR), ~ (bitwise NOT), ^ (XOR), << (left
shift) and >> (right shift).

TRUTH TABLE FOR BIT WISE OPERATION

P BHANU PRAKASH 9676288008 [email protected] 51


1. & – Bitwise AND
2. | – Bitwise OR
3. ~ – Bitwise NOT
4. ^ – XOR
5. << – Left Shift
6. >> – Right Shift
Consider x=40 and y=80. Binary forms of these values are given below.
x = 00101000
y= 01010000
All bit wise operations for x and y are given below.

1. x&y = 00000000 (binary) = 0 (decimal)


2. x|y = 01111000 (binary) = 120 (decimal)
3. ~x = 11111111111111111111111111 11111111111111111111111111111111010111 = -41
(decimal)
4. x^y = 01111000 (binary) = 120 (decimal)
5. x << 1 = 01010000 (binary) = 80 (decimal)
6. x >> 1 = 00010100 (binary) = 20 (decimal)

NOTE:
➢ Bit wise NOT : Value of 40 in binary is 00000000000000000000000000000000
00000000000000000010100000000000. So, all 0’s are converted into 1’s in bit wise NOT
operation.
➢ Bit wise left shift and right shift : In left shift operation “x << 1 “, 1 means that the bits will be left
shifted by one place. If we use it as “x << 2 “, then, it means that the bits will be left shifted by 2
places.
EXAMPLE OUTPUT:
#include <stdio.h>
AND_opr value = 0
int main()
OR_opr value = 120
{
NOT_opr value = -41
int m = 40,n =
XOR_opr value = 120
80,AND_opr,OR_opr,XOR_opr,NOT_opr ;
left_shift value = 80
AND_opr = (m&n);
right_shift value = 20
OR_opr = (m|n);
NOT_opr = (~m);
XOR_opr = (m^n);
printf("AND_opr value = %d\n",AND_opr );
printf("OR_opr value = %d\n",OR_opr );

P BHANU PRAKASH 9676288008 [email protected] 52


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);
}
CONDITIONAL OPERATOR (?:)
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 : Condition ? TRUE Part : FALSE Part;
Example : A = (10<15)?100:200; ⇒ A value is 100

Syntax : (Condition? true_value: false_value);


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


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

SPECIAL OPERATORS (SIZEOF, POINTER, COMMA, DOT, ETC.)


sizeof operator
This operator is used to find the size of the memory (in bytes) allocated for a variable. This operator
is used with the following syntax.
sizeof(variableName);
Example
sizeof(A); ⇒ the result is 2 if A is an integer

P BHANU PRAKASH 9676288008 [email protected] 53


Pointer operator (*)
This operator is used to define pointer variables in c programming language.
Comma operator (,)
This operator is used to separate variables while they are declaring, separate the expressions in function
calls, etc.
Dot operator (.)
This operator is used to access members of structure or union.
Operators Description
& This is used to get the address of the variable.
Example : &a will give address of a.
* This is used as pointer to a variable.
Example : * a where, * is pointer to the variable a.
Sizeof () This gives the size of the variable.
Example : size of (char) will give us 1.

EXAMPLE FOR & AND * OPERATORS EXAMPLE FOR SIZEOF()


#include <stdio.h> #include <stdio.h>
int main() #include <limits.h>
{ int main()
int *ptr, q; {
q = 50; int a;
/* address of q is assigned to ptr */ char b;
ptr = &q; float c;
/* display q's value using ptr double d;
variable */ printf("storage size for int data type:%d \n",sizeof(a));
printf("%d", *ptr); printf("storage size for char data type:%d \n",sizeof(b));
return 0; printf("storage size for float data type:%d \n",sizeof(c));
} printf("storage size for double data type:%d\n",sizeof(d));
OUTPUT: return 0;
50 }
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

P BHANU PRAKASH 9676288008 [email protected] 54


C EXPRESSIONS
What is an expression?
Def: -An expression is a collection of operators and operands that represents a specific value.
In any programming language, if we want to perform any calculation or to frame any condition etc., we use
a set of symbols to perform the task. These set of symbols makes an expression.

In the above definition, an operator is a symbol that performs tasks like arithmetic operations, logical
operations, and conditional operations, etc.
Operands are the values on which the operators perform the task. Here operand can be a direct value or
variable or address of memory location.
Expression Types in C
In the C programming language, expressions are divided into THREE types. They are...
1. Infix Expression
2. Postfix Expression
3. Prefix Expression
The above classification is based on the operator position in the expression.
Infix Expression
The expression in which the operator is used between operands is called infix expression.
EXAMPLE

Postfix Expression
The expression in which the operator is used after operands is called postfix expression.
EXAMPLE

Prefix Expression
The expression in which the operator is used before operands is called a prefix expression.
EXAMPLE

C OPERATOR PRECEDENCE AND ASSOCIATIVITY


What is Operator Precedence?

P BHANU PRAKASH 9676288008 [email protected] 55


Operator precedence is used to determine the order of operators evaluated in an expression. In c
programming language every operator has precedence (priority). When there is more than one operator in
an expression the operator with higher precedence is evaluated first and the operator with the least
precedence is evaluated last.
What is Operator Associativity?
Operator associativity is used to determine the order of operators with equal precedence evaluated
in an expression. In the c programming language, when an expression contains multiple operators with
equal precedence, we use associativity to determine the order of evaluation of those operators.

Category Operator Associativity

Postfix () [] -> . ++ - - Left to right

Unary + - ! ~ ++ - - (type)* & sizeof Right to left

Multiplicative */% Left to right

Additive +- Left to right

Shift << >> Left to right

Relational < <= > >= Left to right

Equality == != 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 ?: Right to left

Assignment = += -= *= /= %=>>= <<= &= ^= |= Right to left

Comma , Left to right

EXAMPLE CODE
#include <stdio.h> OUTPUT
main() { Value of (a + b) * c / d is : 90
int a = 20; Value of ((a + b) * c) / d is : 90
int b = 10; Value of (a + b) * (c / d) is : 90
int c = 15; Value of a + (b * c) / d is : 50
int d = 5;
int e;
e = (a + b) * c / d; // ( 30 * 15 ) / 5
printf("Value of (a + b) * c / d is : %d\n", e );
e = ((a + b) * c) / d; // (30 * 15 ) / 5

P BHANU PRAKASH 9676288008 [email protected] 56


printf("Value of ((a + b) * c) / d is : %d\n" , e );
e = (a + b) * (c / d); // (30) * (15/5)
printf("Value of (a + b) * (c / d) is : %d\n", e );
e = a + (b * c) / d; // 20 + (150/5)
printf("Value of a + (b * c) / d is : %d\n" , e );
return 0;
}

C EXPRESSION EVALUATION
An expression is evaluated based on the precedence and associativity of the operators in that expression.
In the C programming language, an expression is evaluated based on the operator precedence and
associativity. When there are multiple operators in an expression, they are evaluated according to their
precedence and associativity. The operator with higher precedence is evaluated first and the operator with
the least precedence is evaluated last.
To understand expression evaluation in c 10 + 4 * 3 / 2
In the above expression, there are three operators +, * and /. Among these three operators, both
multiplication and division have the same higher precedence and addition has lower precedence. So,
according to the operator precedence both multiplication and division are evaluated first and then the
addition is evaluated. As multiplication and division have the same precedence they are evaluated based on
the associativity. Here, the associativity of multiplication and division is left to right. So, multiplication is
performed first, then division and finally addition. So, the above expression is evaluated in the order of * /
and +. It is evaluated as follows...

4 * 3 ====> 12
12 / 2 ===> 6
10 + 6 ===> 16
The expression is evaluated to 16.

TYPES OF ERRORS IN C

There are five different types of errors in C.


1. Syntax Error
2. Run Time Error
3. Logical Error
4. Semantic Error
5. Linker Error
1. Syntax Error
➢ Syntax errors occur when a programmer makes mistakes in typing the code's syntax correctly or
makes typos. In other words, syntax errors occur when a programmer does not follow the set of
rules defined for the syntax of C language.
➢ Syntax errors are sometimes also called compilation errors because they are always detected by the
compiler. Generally, these errors can be easily identified and rectified by programmers.

P BHANU PRAKASH 9676288008 [email protected] 57


The most commonly occurring syntax errors in C language are:
• Missing semi-colon (;)
• Missing parenthesis ({})
• Assigning value to a variable without declaring it
2. Run Time Error
➢ Errors that occur during the execution (or running) of a program are called Run Time Errors. These
errors occur after the program has been compiled successfully. When a program is running, and it is
not able to perform any particular operation, it means that we have encountered a run time error. For
example, while a certain program is running, if it encounters the square root of -1 in the code, the
program will not be able to generate an output because calculating the square root of -1 is not
possible. Hence, the program will produce an error.
➢ Run time errors can be a little tricky to identify because the compiler can not detect these errors.
They can only be identified once the program is running. Some of the most common run time errors
are: number not divisible by zero, array index out of bounds, string index out of bounds, etc.

Run time errors can occur because of various reasons. Some of the reasons are:

• Mistakes in the Code: Let us say during the execution of a while loop, the programmer forgets to
enter a break statement. This will lead the program to run infinite times, hence resulting in a run
time error.
• Memory Leaks: If a programmer creates an array in the heap but forgets to delete the array's data,
the program might start leaking memory, resulting in a run time error.
• Mathematically Incorrect Operations: Dividing a number by zero, or calculating the square root
of -1 will also result in a run time error.
• Undefined Variables: If a programmer forgets to define a variable in the code, the program will
generate a run time error.
3. Logical Error
Sometimes, we do not get the output we expected after the compilation and execution of a program.
Even though the code seems error free, the output generated is different from the expected one. These types
of errors are called Logical Errors. Logical errors are those errors in which we think that our code is correct,
the code compiles without any error and gives no error while it is running, but the output we get is different
from the output we expected.
4. Semantic Error
➢ Errors that occur because the compiler is unable to understand the written code are called Semantic
Errors. A semantic error will be generated if the code makes no sense to the compiler, even though
it is syntactically correct. It is like using the wrong word in the wrong place in the English language.
For example, adding a string to an integer will generate a semantic error.
➢ Semantic errors are different from syntax errors, as syntax errors signify that the structure of a
program is incorrect without considering its meaning. On the other hand, semantic errors signify the
incorrect implementation of a program by considering the meaning of the program.
➢ The most commonly occurring semantic errors are: use of un-initialized variables, type
compatibility, and array index out of bounds.

P BHANU PRAKASH 9676288008 [email protected] 58


5. Linker Error
Linker is a program that takes the object files generated by the compiler and combines them into a
single executable file. Linker errors are the errors encountered when the executable file of the code can not
be generated even though the code gets compiled successfully. This error is generated when a different
object file is unable to link with the main object file. We can run into a linked error if we have imported an
incorrect header file in the code, we have a wrong function declaration, etc.

TYPE CASTING AND CONVERSION


In a programming language, the expression contains data values of the same data type or different data
types. When the expression contains similar data type values then it is evaluated without any problem. But
if the expression contains two or more different data type values, then they must be converted to the single
data type of destination data type. Here, the destination is the location where the final result of that
expression is stored. For example, the multiplication of an integer data value with the float data value and
storing the result into a float variable. In this case, the integer value must be converted to float value so that
the final result is a float data type value.
In a c programming language, the data conversion is performed in two different methods
➢ Type Conversion
➢ Type Casting

Type Conversion
The type conversion is the process of converting a data value from one data type to another data type
automatically by the compiler. Sometimes type conversion is also called implicit type conversion. The
implicit type conversion is automatically performed by the compiler.
For example, in c programming language, when we assign an integer value to a float variable the integer
value automatically gets converted to float value by adding decimal value 0. And when a float value is
assigned to an integer variable the float value automatically gets converted to an integer value by removing
the decimal value. To understand more about type conversion observe the following...

int i = 10 ;
float x = 15.5 ;
char ch = 'A' ;

i = x ; =======> x value 15.5 is converted as 15 and assigned to variable i

x = i ; =======> Here i value 10 is converted as 10.000000 and assigned to variable x

i = ch ; =======> Here the ASCII value of A (65) is assigned to i

P BHANU PRAKASH 9676288008 [email protected] 59


Example Program
#include<stdio.h> OUTPUT
#include<conio.h> i value=90
void main() x value=90.000000
{ I value =65
int i = 95 ;
float x = 90.99 ;
char ch = 'A' ;
i=x;
printf("i value is %d\n",i);
x=i;
printf("x value is %f\n",x);
i = ch ;
printf("i value is %d\n",i);
}

In the above program, we assign i = x, i.e., float variable value is assigned to the integer variable. Here, the
compiler automatically converts the float value (90.99) into integer value (90) by removing the decimal part
of the float value (90.99) and then it is assigned to variable i. Similarly, when we assign x = i, the integer
value (90) gets converted to float value (90.000000) by adding zero as the decimal part.

Typecasting
Typecasting is also called an explicit type conversion. Compiler converts data from one data type to
another data type implicitly. When compiler converts implicitly, there may be a data loss. In such a case,
we convert the data from one data type to another data type using explicit type conversion. To perform this
we use the unary cast operator. To convert data from one type to another type we specify the target data
type in parenthesis as a prefix to the data value that has to be converted.
(TargetDatatype) DataValue
Example
int total Marks = 450, max Marks = 600;
float average;
average = (float) total Marks / max Marks * 100;
In the above example code, both total Marks and max Marks are integer data values. When we perform
total Marks / max Marks the result is a float value, but the destination (average) data type is a float. So we
use type casting to convert total Marks and max Marks into float data type.
Example Program
Implicit Explicit
#include <stdio.h> #include <stdio.h>
int main() int main()
{ {
int num1 = 10; float num1 = 15.6;
int num2 = 5; int num2=14, num3;
float result; num3 = (int) num1+num2; // Explicit cast from
result = num1 / num2; // Implicit cast from int to float to int
float printf("The result is: %d\n", num3);
printf("The result is: %.2f\n", result); return 0;
return 0; }
}

P BHANU PRAKASH 9676288008 [email protected] 60


PROBLEM SOLVING TECHNIQUES:
An algorithm is a step-by-step procedure to solve a problem. A good algorithm should be optimized
in terms of time and space. Different types of problems require different types of algorithmic techniques to
be solved in the most optimized manner. There are many types of algorithms but the most important and
fundamental algorithms are under an Algorithmic approach.
Algorithmic approach:
There may be several methods under an approach. Example, Sorting is an approach and different
sorting techniques are methods each. An algorithm is a sequence of logical steps to solve a problem.
There are many types of algorithms but the most important and fundamental algorithms that
you must are discussed in this article.
➢ Brute Force Algorithm
➢ Recursive Algorithm
• Divide and Conquer Algorithm
• Dynamic Programming Algorithms
• Greedy Algorithm
• Backtracking Algorithm
➢ Randomized Algorithm
➢ Sorting Algorithm
➢ Searching Algorithm
➢ Hashing Algorithm
1. Brute Force Algorithm:
This is the most basic and simplest type of algorithm. A Brute Force Algorithm is the
straightforward approach to a problem i.e., the first approach that comes to our mind on seeing the
problem. More technically it is just like iterating every possibility available to solve that problem.
Example: If there is a lock of 4-digit PIN. The digits to be chosen from 0-9 then the brute force
will be trying all possible combinations one by one like 0001, 0002, 0003, 0004, and so on until we get
the right PIN. In the worst case, it will take 10,000 tries to find the right combination.
2. Recursive Algorithm:
This type of algorithm is based on recursion. In recursion, a problem is solved by breaking it into
subproblems of the same type and calling own self again and again until the problem is solved with the
help of a base condition.
Example: Some common problem that is solved using recursive algorithms are Factorial of a Number,
Fibonacci Series, Tower of Hanoi, DFS for Graph, etc.
2.a) Divide and Conquer Algorithm:

P BHANU PRAKASH 9676288008 [email protected] 61


In Divide and Conquer algorithms, the idea is to solve the problem in two sections, the first
section divides the problem into subproblems of the same type. The second section is to solve the smaller
problem independently and then add the combined result to produce the final answer to the problem.
Example: Some common problem that is solved using Divide and Conquers Algorithms are Binary
Search, Merge Sort, Quick Sort, Strassen’s Matrix Multiplication, etc.
2.b) Dynamic Programming Algorithms:
This type of algorithm is also known as the memoization technique because in this the idea is
to store the previously calculated result to avoid calculating it again and again. In Dynamic Programming,
divide the complex problem into smaller overlapping subproblems and store the result for future use.
Example: The following problems can be solved using the Dynamic Programming algorithm Knapsack
Problem, Weighted Job Scheduling, Floyd Warshall Algorithm, etc.
2.c) Greedy Algorithm:
In the Greedy Algorithm, the solution is built part by part. The decision to choose the next part
is done on the basis that it gives an immediate benefit. It never considers the choices that had been taken
previously.
Example: Some common problems that can be solved through the Greedy Algorithm are Dijkstra Shortest
Path Algorithm, Prim’s Algorithm, Kruskal’s Algorithm, Huffman Coding, etc.
2.d) Backtracking Algorithm:
In Backtracking Algorithm, the problem is solved in an incremental way i.e., it is an
algorithmic technique for solving problems recursively by trying to build a solution incrementally, one
piece at a time, removing those solutions that fail to satisfy the constraints of the problem at any point of
time.
Example: Some problems can be solved through the Backtracking Algorithm are the Hamiltonian
Cycle, M-Coloring Problem, N Queen Problem, Rat in Maze Problem, etc.
3. Randomized Algorithm:
In the randomized algorithm, we use a random number.it helps to decide the expected
outcome. The decision to choose the random number so it gives the immediate benefit
Example: Some common problems that can be solved through the Randomized Algorithm are Quicksort:
In Quicksort we use the random number for selecting the pivot.
4.Sorting Algorithm:
The sorting algorithm is used to sort data in maybe ascending or descending order. It’s also
used for arranging data in an efficient and useful manner.
Example: Some common problems that can be solved through the sorting Algorithm are Bubble sort,
insertion sort, merge sort, selection sort, and quick sort are examples of the Sorting algorithm.

P BHANU PRAKASH 9676288008 [email protected] 62


5.Searching Algorithm:
The searching algorithm is the algorithm that is used for searching the specific key in particular
sorted or unsorted data.
Example: Some common problems that can be solved through the Searching Algorithm are Binary
search or linear search is one example of a Searching algorithm.
6.Hashing Algorithm:
Hashing algorithms work the same as the Searching algorithm but they contain an index with a key
ID i.e. a key-value pair. In hashing, we assign a key to specific data.
Example: Some common problems can be solved through the Hashing Algorithm in password
verification.
Characteristics of an Algorithm:
There are some important characteristics which every algorithm should follow. They are as follows:
1.Clear and Unambiguous: The algorithm should be unambiguous. Each of its steps should be clear in all
aspects and must lead to only one meaning.
2.Well-Defined Inputs: If an algorithm says to take inputs, it should be well-defined inputs. It may or may
not take input.
3.Well-Defined Outputs: The algorithm must clearly define what output will be yielded and it should be
well-defined as well. It should produce at least 1 output.
4.Finiteness: The algorithm must be finite, i.e., it should terminate after a finite time. An algorithm must
terminate after a finite number of steps in all test cases.
5.Feasible: The algorithm must be simple, generic, and practical, such that it can be executed with the
available resources. It must not contain some future technology or anything.
6.Language Independent: The Algorithm designed must be language-independent, i.e., it must be just
plain instructions that can be implemented in any language, and yet the output will be the same, as
expected.
7.Effectiveness: An algorithm must be developed by using very basic, simple, and feasible operations so
that one can trace it out by using just paper and pencil.
8.Modularity and reusability: Algorithms may be modular, they may be divided into smaller subproblems
or features that may be reused in unique parts of the algorithm or in other algorithms.
9.Understandability: Algorithms need to be designed with clarity and ease in mind, making them easy to
apprehend and implement.
PROBLEM SOLVING STRATEGIES:

Structured programming is a programming paradigm aimed on improving the clarity, quality,


and development time of a computer program by making extensive use of subroutines. It is possible to

P BHANU PRAKASH 9676288008 [email protected] 63


do structured programming in any programming language, though it is preferable to use something like
a procedural programming language. Example: ALGOL, Pascal, PL/I and Ada.
There are three main principles of structured programming,
1. Program design using top-down or bottom-up approach
2. Decomposition of program into components i.e. modular programming
3. Structuring of control flow
Top-down approach:
➢ Program design concentrates on planning the solution as a collection of sub solutions. During top-
down design the divide and conquer policy is followed.
➢ The problem is divided into smaller sub problems and these sub problems are further divided into
even smaller sub problems.
➢ In the top-down approach, the calling components is always designed before its sub component.
➢ Thus top-down design represents a successive refinement of functionality of the program.

➢ It allows us to build solutions to a problem in a stepwise fashion.

For example, the following figure shows top-down approach,

Bottom-up approach:
The bottom-up design is the reverse of the top-down approach.
➢ Here the process starts with the identification of the smallest sub component of the total program
which can be easily implemented.
➢ Such smallest components are combined to reach to a more abstract level and plan components of

P BHANU PRAKASH 9676288008 [email protected] 64


the higher level.
➢ This process is continued till the complete program does not get realized.
➢ The main drawback of this approach is that it is rarely possible to identify smallest sub component
needed for the program, especially for bigger program.
For example, the following figure shows bottom-up approach,

Deference between top-down and bottom-up approaches are,


Sl. TOP DOWN APPROACH BOTTOM UP APPROACH
In this approach We focus on breaking up In this approach, we solve smaller problems
1.
the problem into smaller parts. and
integrate it as whole and complete the solution.
Mainly used by structured programming Mainly used by object oriented programming
2.
language such as COBOL, Fortran, C, etc. language such as C++, C#, Python.
Each part is programmed separately therefore Redundancy is minimized by using data
3.
contain redundancy. encapsulation and data hiding.
In this the communications is less
4. In this module must have communication.
among modules.
It is used in debugging, module
5. It is basically used in testing.
documentation, etc.
In top down approach, decomposition takes
6. In bottom up approach composition takes place.
place.
In this top function of system might be hard to In this sometimes we can not build a program
7.
identify. from the piece we have started.
8. In this implementation details may differ. This is not natural for people to assemble.

Time and Space complexities of Algorithms:


An algorithm is defined as complex based on the amount of Space and Time it consumes. Hence the
Complexity of an algorithm refers to the measure of the time that it will need to execute and get the
expected output, and the Space it will need to store all the data (input, temporary data, and output). Hence
these two factors define the efficiency of an algorithm.
The two factors of Algorithm Complexity are:

P BHANU PRAKASH 9676288008 [email protected] 65


•Time Factor: Time is measured by counting the number of key operations such as comparisons in the
sorting algorithm.
•Space Factor: Space is measured by counting the maximum memory space required by the algorithm to
run/execute
Therefore the complexity of an algorithm can be divided into two types:
1.Space Complexity: The space complexity of an algorithm refers to the amount of memory required by
the algorithm to store the variables and get the result. This can be for inputs, temporary operations, or
outputs.
How to calculate Space Complexity?
The space complexity of an algorithm is calculated by determining the following 2 components:
➢ Fixed Part: This refers to the space that is required by the algorithm. For example, input variables,
output variables, program size, etc.
➢ Variable Part: This refers to the space that can be different based on the implementation of the
algorithm. For example, temporary variables, dynamic memory allocation, recursion stack space, etc.

Therefore, Space complexity S(P) of any algorithm P is S(P) = C + SP(I), where C is the fixed part and
S(I) is the variable part of the algorithm, which depends on instance characteristic I.
2. Time Complexity: The time complexity of an algorithm refers to the amount of time required by the
algorithm to execute and get the result. This can be for normal operations, conditional if-else
statements, loop statements, etc.
How to Calculate, Time Complexity?
The time complexity of an algorithm is also calculated by determining the following 2 components:
1. Constant time part: Any instruction that is executed just once comes in this part.
For example, input, output, if-else, switch, arithmetic operations, etc.
2. Variable Time Part: Any instruction that is executed more than once, say n times,
comes in this part. For example, loops, recursion, etc.
Therefore, Time complexity of any algorithm P is T(P) = C + TP(I), where C is the constant time
part and TP(I) is the variable part of the algorithm, which depends on the instance characteristic I.
The analysis of Algorithms:
Algorithm analysis is an important part of computational complexity theory, which provides
theoretical estimation for the required resources of an algorithm to solve a specific computational
problem. Analysis of algorithms is the determination of the amount of time and space resources required
to execute it.
Analysis of algorithm is the process of analyzing the problem-solving capability of the algorithm
in terms of the time and size required (the size of memory for storage while implementation). However,

P BHANU PRAKASH 9676288008 [email protected] 66


the main concern of analysis of algorithms is the required time or performance.
Generally, we perform the following types of analysis –
• Worst-case − The maximum number of steps taken on any instance of size a.
• Best-case − The minimum number of steps taken on any instance of size a.
• Average-case − An average number of steps taken on any instance of size a.
• Amortized − A sequence of operations applied to the input of size an averaged over time.
Some Important sort outs:

Problem: Draw a flowchart to find the roots of Problem: Write the PSEUDO CODE for
a quadratic equation checking whether a given number is a prime
number or not.

************************************************************************************

P BHANU PRAKASH 9676288008 [email protected] 67

You might also like