0% found this document useful (0 votes)
52 views156 pages

Module 1

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

Module 1

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

PRINCIPLES OF PROGRAMMING IN C

BPOPS103

PAVITHRA J
ASSISTANT PROFESSOR,
DEPT. OF AI & DS,
RNSIT
MODULE 1:

/* C Program listing the contents in Module1*/


#include<stdio.h>
main()
{
printf(“Module 1 Contents:\n”);
printf(“Introduction to Computer Hardware and Software\n”);
printf(“Overview of C\n”);
}
/* End of Program*/
INTRODUCTION
Computer is an advanced electronic device that takes raw data as an input from the user and
processes it under the control of a set of instructions (called program), produces a result (output),
and saves it for future use.

▪ Step 1 - Takes data as input.


▪ Step 2 - Stores the data/instructions in its memory and uses them as required.
▪ Step 3 - Processes the data and converts it into useful information.
▪ Step 4 - Generates the output.
▪ Step 5 - Controls all the above four steps

.
INTRODUCTION
CHARACTERISTICS OF COMPUTER
▪Speed
▪Accuracy
▪Automation
▪Diligence
▪Versatile
▪Memory
▪NoIQ
▪Economical
STORED PROGRAM CONCEPT

Address Bus carries addresses

Data Bus -carries data and instructions Main memory


Processor

Von Neumann architechture by Sir John Von


Neumann

Fig: Shared memory for instructions and data.

• Data and instructions are transferred to and from the memory through a shared bus.
• Process execution becomes slower.
SEPARATE MEMORIES FOR INSTRUCTIONS
AND DATA
▪Byb

• Separate memory to store to store data and instructions.


• Instructions are selected serially from the instruction memory and executed in the processor
GENERATIONS OF COMPUTERS
First Generation Computers
▪The period of first generation was from 1946-1959.
▪The computers of first generation used vacuum tubes as the basic components for memory and
circuitry for CPU .
▪Therefore, they were very expensive and only large organizations were able to afford it.
▪large in size.
▪Vacuum tubes burn frequently.
▪Maintenance problems .
▪Examples: IBM 701, ENIAC,EDVAC, EDSAC, UNIVAC-I
▪Languages used : Machine or assembly level language
GENERATIONS OF COMPUTERS
GENERATIONS OF COMPUTERS
Second Generation Computers
▪The period of second generation was from 1959-1965.
▪In this generation, transistors were used that were cheaper, consumed less power, more
compact in size, more reliable and faster than the first-generation machines made of vacuum
tubes.
▪In this generation, magnetic cores were used as the primary memory and magnetic tape and
magnetic disks as secondary storage devices.
▪High-level programming languages were also being
developed at this time, such as early versions of COBOL
and FORTRAN.
▪Example : IBM 1401
▪Languages used : HLL (Batch OS)
GENERATIONS OF COMPUTERS
Advantages :
Size reduced The very fast
Disadvantages :
They over heated quickly
Maintenance problems
GENERATIONS OF COMPUTERS
▪Third Generation Computers
▪The period of third generation was from 1965-1971.
▪The computers of third generation used Integrated Circuits (ICs) in place of transistors.
A single IC has many transistors, resistors, and capacitors along with the associated
circuitry.
▪This development made computers smaller in size, reliable, and efficient.
▪High-level languages (FORTRAN-II
TO IV, COBOL, PASCAL PL/1,
BASIC, ALGOL-68 etc.) were
used during this generation.
GENERATIONS OF COMPUTERS
The main features of third generation are:
▪IC used
▪More reliable in comparison to previous two generations
▪Smaller size
▪Generated less heat
▪Faster
▪Lesser maintenance
▪Costly
▪AC required
▪Consumed lesser electricity
▪Supported high-level language
GENERATIONS OF COMPUTERS
Fourth Generation Computers
▪The period of fourth generation was from 1971-1980.
▪ Computers of fourth generation used Very Large Scale Integrated (VLSI) circuits.
▪VLSI circuits having about 5000 transistors and other circuit elements with their associated circuits on a
single chip made it possible to have microcomputers of fourth generation.
▪Fourth generation computers became more powerful, compact, reliable, and affordable. As a result, it
gave rise to Personal Computer (PC) revolution.
▪In this generation, time sharing, real time networks, distributed operating system were used. All the
high-level languages like C, C++, DBASE etc., were used in this generation.
▪Fourth generation computers also saw the development of GUIs, the mouse and other devices.
GENERATIONS OF COMPUTERS
The main features of fourth generation are:
▪ VLSI technology used
▪ Very cheap
▪ Portable and reliable
▪ Use of PCs
▪ Very small size
▪ Pipeline processing
▪ No AC required
▪ Concept of internet was introduced
▪ Great developments in the fields of networks
▪ Computers became easily available
GENERATIONS OF COMPUTERS
▪Fifth Generation Computers
▪The period of fifth generation is 1980-till date.
▪In the fifth generation, VLSI technology became ULSI (Ultra Large Scale Integration)
technology, resulting in the production of microprocessor chips having ten million electronic
components.
▪Fifth generation computing devices, based on artificial intelligence.
▪Are still in development, though there are some applications, such as voice recognition.
▪The use of parallel processing and superconductors is helping to make artificial intelligence a
reality.
▪Example: Super computer, IBM note books, Pentium PCs,
COMPUTER CLASSIFICATION
Computers can be classified by size and power to:
▪Minicomputer
▪Microcomputer
▪Mainframe
▪Supercomputer
COMPUTER CLASSIFICATION
Personal computer(PCs)
▪A small, single-user computer based on a microprocessor.
▪In addition to the microprocessor, a personal computer has a keyboard for entering
data, a monitor for displaying information, and a storage device for saving data.
▪Also called as microcomputer .
▪Microcomputer can be classified
1. Desktops
2. Portables
3. Hand-held devices
4. Workstations
5. Network computers.
COMPUTER CLASSIFICATION
The different portable computers are: -
1) Laptop 2) Notebooks 3) Palmtop (hand held) 4) Wearable computers
▪Laptop: -
this computer is similar to a desktop computers but the size is smaller.
They are expensive than desktop. The weight of laptop is around 3 to 5 kg.

▪Notebook: -
These computers are as powerful as desktop but size of these computers
are comparatively smaller than laptop and desktop. They weigh 2 to 3 kg.
They are more costly than laptop.
COMPUTER CLASSIFICATION
▪Palmtop (Hand held): -
They are also called as personal Digital Assistant (PDA). These computers are
small in size. They can be held in hands. It is capable of doing word
processing, spreadsheets and hand writing recognition, GAME
playing, faxing and paging. These computers are not as powerful as desktop computers.
▪Wearable computer: -
The size of this computer is very small so that it can be worn on the
body. It has smaller processing power. It is used in the field of
medicine. For example pace maker to correct the heart beats.
COMPUTER CLASSIFICATION
Workstation:
▪A powerful, single-user computer. A workstation is like a personal computer, but it has
a more powerful microprocessor and a higher-quality monitor.
▪Workstations are more powerful
and higher in performance than
desktop computers, especially
with respect to CPU and
Graphics, memory capacity and
multitasking capability.
COMPUTER CLASSIFICATION
Minicomputer
▪A class of multi-user Computer that lies between the largest Multi-user systems (mainframe computer)
and the smallest Microcomputers or personal computers.
▪Mainframe computers are used to run
commercial applications and other large-
scale computing purposes.
▪It is also used in banking and insurance
businesses.
▪For example millions of records are processed, each day.
COMPUTER CLASSIFICATION
Mainframe
▪Mainframe computers can support hundreds or thousands of users, handling massive
amounts of input, output, and storage.
▪Mainframe computers are used in large
organizations where many users need
access to shared data and programs.
▪Mainframes are also used as e-commerce
servers, handling transactions over the
Internet.
COMPUTER CLASSIFICATION
Super computer
▪Computer which are designed for scientific job like whether forecasting and artificial intelligence etc.
They are fastest and expensive. A super computer contains a number of CPU which operate in parallel to
make it faster. It also known as grand father computer.
▪Application – whether forecasting, weapons research and development.
DATA / INFORMATION
Data is a representation of facts or concepts in an organized manner. i.e. Data is a piece of
information that is given.
For example : numbers, names, ,marks etc are the data.
Consider the two data items “Ram” and “10”.
Both these will not convey any specific name.
Information is a collection of data from which conclusions may be drawn.
Information is obtained from data and it is the result of processing, manipulating and organizing
the data which adds to the knowledge of a person.
Example: “Ram scored 10 marks “ This may be the output of the program and this sentence is an
information.
ASCII
What is ASCII?
⮚ ASCII code is a 7-bit code to represent various characters such as alphabets, digits,
punctuation marks and other symbols.
⮚ ASCII stands for American Standard Code for Information Interchange.
⮚ Since, it is 7-bit code, 2^7=128 symbols can be represented.
⮚ The standard ASCII character set consists of 128 decimal numbers ranging from 0 to
127.
⮚ Use: To achieve compatibility between various types of data processing equipments.
3
1
PROGRAM TO PRINT ASCII VALUE OF A CHARACTER
#include <stdio.h>
int main()
{
char ch; // variable declaraaa /.\
O}tion
printf("Enter a character");
scanf("%c", &ch); // user input
printf("\n The ascii value of the ch variable is : %d", ch);
return 0;
}

1/18/2022 3
2
UNITS OF DATA
⮚The data represented can be grouped or measured using following units:
Bit = 0 or 1
Nibble = 4 bits
Units of Data Byte = 8 bits
Kilobyte = 1024 bytes
Megabyte = 1024 Kilobytes
Gigabytes = 1024 Megabytes
Terabytes = 1024 Gigabytes
BITS, BYTES AND WORDS
What is a bit?
Bit is short for 'binary digit.' It's a single digit in a binary number, and it can be either 1
or 0.
What is a byte?
A byte is 8 bits. That's the definition. With 8 bits you can store any number between 0
and 255, since there are 256 different combinations of 1 and 0 to choose from.
What is a word?
You often hear about 32-bit or 64-bit computer architectures. A word is basically the
number of bits a particular computer's CPU can deal with in one go. It varies depending
on the computer architecture you're using.
▪Convert 80GB into bytes.
1GB = 1024MB
80 GB = 80 * 1024 MB
80 GB = 80 * 1024 * 1024KB
80 GB = 80 * 1024 * 1024 * 1024 bytes
80 GB = 85,899,345,920 bytes

• What is a word?
A word is a unit of information.
Word is usually an even multiple of bytes such as 2/4/8/16 bytes etc. depending on word length of
computer.
example: for 16-bit machine ,1 word = 16-bits = 2 bytes.
for 32-bit machine, 1 word =32 bits = 4 bytes
for 64 bit machine, 1 word = 64 bits = 8 bytes
Components of a Computer

Hardware Software

System Software Application


Software

General Purpose

Application Specific
Components of a Computer

Hardware Software

Keyboard, Mouse, Scanner

Arithmetic calculations, comparing values,


movement of data

Main memory, temporary, RAM

Monitor, Printer, Plotter

Secondary memory, permanent, Hard


Disk, Pen Drive
Components of a Computer

Software Hardware
Application
System Software Software

Interface, File access from database

Provides System utilities, Disk fragmentation

Translators, Debugging tools


Components of a Computer

Hardware Software

System Software Application


Software

General Purpose Ms-Office,


Notepad,
Ms-paint

Application Ledger maintenance,


Specific Talley
FUCTIONAL UNITS OF COMPUTER
▪Computer consists of
INPUT DEVICES
▪An input device is any hardware device that sends data to a computer, allowing you to interact with and
control it.
▪The most commonly used or primary input devices on a computer are the keyboard and mouse.
However, there are other devices that input data into a computer.
Types of input devices
INPUT DEVICES
CENTRAL PROCESSING UNIT
CPU Components
The CPU is comprised of three main parts
▪ALU(Arithmetic Logic Unit)
▪Control Unit(CU)
▪Registers: Stores the data that is to be executed next.

Arithmetic Logic Unit (ALU)


▪Executes all arithmetic and logical operations.
▪Arithmetic calculations like as addition, subtraction, multiplication and division.
▪Logical operation like compare numbers, letters, or special characters
CENTRAL PROCESSING UNIT
Control Unit (CU)
▪Controls and co-ordinates computer components.
▪Read the code for the next instruction to be executed.
▪Increment the program counter so it points to the next instruction.
▪Read whatever data the instruction requires from cells in memory.
▪Provide the necessary data to an ALU or register.
▪If the instruction requires an ALU or specialized hardware to complete, instruct the hardware to
perform the requested operation.
Registers
▪Stores the data that is to be executed next, "very fast storage area".
CENTRAL PROCESSING UNIT
Unit of Measurement -Speed
▪The speed of CPU measured by unit called Hertz (Hz)
▪1 Hz represent 1 cycle per second.
▪The speed of CPU is known as Computer Speed.
MEMORY
▪Memory unit stores the data, instructions, intermediate results and output,
temporarily, during the processing of data.
▪This memory is also called the main memory or primary memory of the
computer.
▪Another kind of storage unit is also referred to as the secondary memory of the
computer.
▪The data, the programs and the output are stored permanently in the storage unit
of the computer. Magnetic disks, optical disks and magnetic tapes are examples
of secondary memory.
MEMORY
Primary Memory
RAM:
▪Random Access Memory: is a memory scheme within the computer system responsible for storing data
on a temporary basis, so that it can be promptly accessed by the processor as and when needed.
▪It is volatile in nature, which means that data will be erased once supply to the storage device is turned
off.
▪RAM stores data randomly and the processor accesses these data randomly from the RAM storage.

ROM:
▪ ROM (Read Only Memory): ROM is a permanent form of storage. ROM stays active regardless of
whether power supply to it is turned on or off.
▪ROM devices do not allow data stored on them to be modified.
MEMORY
Secondary Memory
▪Stores data and programs permanently its retained after the power is turned off.
It is a non-volatile memory.
▪It provides back-up storage for data and instructions. Hard disk drive, floppy
drive and optical disk drives are some examples of storage devices.
▪The data and instructions that are currently not being used by CPU, but may be
required later for processing, are stored in secondary memory.
▪Secondary memory has a high storage capacity than the primary memory.
▪Secondary memory is also cheaper than the primary memory.
▪It takes longer time to access the data and instructions stored in secondary
memory than in primary memory.
▪Main Examples MEMORY
1.Hard Disk
2.Optical Disk
3.Flash memory
Hard Disk
▪Also called as Disk drive or HDD
▪stores and provides relatively quick access to large amounts of data.
▪Stores data on an electromagnetically charged surface or set of surfaces.
Optical Disk & Flash
▪An optical disc drive(ODD) is a disk drive that use laser light to store data.
▪There are three main types of optical media: CD, DVD, and Blu-ray disc
MEMORY
Flash Disk
▪A storage module made of flash memory chips.
▪A Flash disks have no mechanical platters or access arms, but the term "disk" is used
because the data are accessed as if they were on a hard drive. The disk storage
structure is emulated.

Floppy diskette
▪Represented by a small rectangular plastic case containing a thin magnetic disk.
▪They offer the capacity of 1.2 MB to 1.44MB.
OUTPUT DEVICES
▪Output device receives information from the CPU and presents it to the user in the desired from.
▪The processed data, stored in the memory of the computer is sent to the output unit, which then converts
it into a form that can be understood by the user.
▪The output is usually produced in one of the two ways – on the display device, or on paper (hard copy).
Monitor:
▪Monitor is an output device that resembles the television screen.
▪It may use a Cathode Ray Tube (CRT) to display information. The monitor is associated with a keyboard
for manual input of characters and displays the information as it is keyed in.
▪It also displays the program or application output. Like the television, monitors are also available in
different sizes.
OUTPUT DEVICES
Printer
▪Printer is a device that outputs text and graphics information obtained from the computer and prints it on to a paper.
▪Printers are available in the market in a variety of size, speed, sophistication, and cost.
Dot matrix printer:
▪A dot matrix printer prints characters and images of all types as a pattern of dots.
▪It has a print head (or hammer) that consists of pins representing the character or image.
▪The print head runs back and forth, or in an up and down motion, on the page and prints by striking an ink-soaked
cloth ribbon against the paper, much like the print mechanism on a typewriter.
Line printer
▪Line printer is a high speed impact printer in which one typed line is printed at a time.
▪The speed of a line printer usually varies from 600 to 1200 lines-per-minute or approximately 10 to 20 pages per
minute.
OUTPUT DEVICES
INKJET PRINTERS
▪In inkjet printers, the print head has several tiny nozzles, also called jets.
▪As the paper moves past the print head, the nozzles spray ink onto it, forming the characters and images.
▪The dots are extremely small (usually between 50 and 60 microns in diameter) and are positioned very
precisely, with resolutions of up to 1440x720 dots per inch

LASER PRINTER:
▪It is a non-impact printer that works at a very high speed and produces high quality text and graphics.
▪It uses the photocopier technology. When a document is sent to the printer, a laser beam "draws" the
document on a drum (which is coated with a photo-conductive material) using electrical charges.
▪After the drum is charged, it is rolled in toner (a dry powder type of ink).
OUTPUT DEVICES
PLOTTER
A plotter is used to print vector graphics with a high print quality.
They are widely used to draw maps, in scientific applications and
in applications like CAD, CAM and CAE
OUTPUT DEVICES
▪Output Devices
PORTS AND CONNECTORS
▪Devices like scanners and printers are connected through the points called as ports.
▪All ports are connected to the mother board of the computer but are visible from
outside.
▪The following are the ports that are commonly used.
▪Universal Serial Bus (USB) They have replaced serial and parallel ports in the
motherboard. Computers are provided with at least 4 USB ports to support scanner,
printer and mouse. Current USB ports are capable of transferring 1 GB file in 20
Seconds.
PROGRAMMING LANGUAGES
Program: The set of instructions given to the computer to achieve a specific task is called program.
Programming: The process of providing instructions to solve a specific problem is called programming.
Programming Language: The language that is used to write a program is called programming language.
There are mainly 3 types of programming languages.
1) Machine level language
▪This is the language of computers. It is set of instructions which are given to the computer in the form of
0’s and 1’s.
▪Program execution is very fast.
▪Difficult to read and write machine language programs.
PROGRAMMING LANGUAGES
2) Assembly level language
▪It is also called as Symbolic language. The set of instructions are given to the computer in the
form of symbolic names.
▪Easy to remember, easy to write as compared to machine language.
▪Ex: ADD R1,R2
▪MUL R1, R2
▪There is a need of translator to translate assembly language into machine language.
▪Assembler: Assembler is a translator which translates the program written in assembly
language into the machine language.
PROGRAMMING LANGUAGES
3) High level language
▪It is written using symbols and words just like English language.
▪It is easy to read, write and maintain.
▪Ex: ‘C’ is a programming language.
▪It takes more time to execute when compared with machine or assembly language.
▪Compiler: The compiler is a translator which accepts the program written in high-level language and
produces the corresponding machine language program (machine code).
APPLICATIONS OF COMPUTER
▪Word Processing: This software enables users to read and write
documents,alos add images, tables, graphs to illustrate concept.
▪Internet: It is a network of networks that connects computers all over the
world.
▪Digital audio or video composition: computer makes audio or video
composition and editing very simple.
▪Desktop publishing: This software enables users to create page layouts for
entire books,
CONTINUED..
▪Application areas of computers:
◦e-Business
◦Business to consumer or B2C
◦Business to business or B2B
◦Consumer to consumer or C2C
◦Electronic banking.
▪Bioinformatics: is a interdisciplinary field of molecular biology,computer
science, statistics and mathematics which involves analysis os genome
information to understand human diseases and thus discovery of new drugs to
treat them.
INTRODUCTION TO C PROGRAMMING
▪C is a programming language. It was developed at AT&T's Bell Laboratories of USA in 1972.
▪It was designed and written by “Dennis Ritchie”. It is being used on several different software platforms.

Characteristics of C
▪C is a Robust language.
▪It is considered as a High-level language.
▪C is a Core language as many other programming languages (such as C++, Java or Perl) are based on C.
▪Portable language.
▪Suited for Structured programming.
▪Extensible language.
APPLICATIONS OF C
▪C is a very simple language that is widely used by software professionals around the globe.
▪C is primarily used for system programming. The portability, efficiency, the ability to access specific
hardware addresses and low runtime.
▪The compiler, libraries and interpreters of other programming languages are often implemented in C.
▪Major parts of popular operating systems like windows, UNIX, Linux are still written in C.
▪Mobile devices like cellular phones and palmtops consisting of microprocessor, operating system and
some applications are written in C.
APPLICATIONS OF C
▪Common consumer devices like microwave ovens, washing machines and digital
cameras are consisting of many programs which are written in C language.
▪Several professional 3D computer games and many popular gaming frameworks
have been built using C language.
FUNDAMENTALS OF PROBLEM SOLVING
▪Problem Solving is the process of working through the details of a problem to reach a solution.
▪There are three approaches to problem solving:
1. Algorithm
2. Flowchart
3. Pseudo Code
Algorithm
▪The algorithm is a ‘step-by-step procedure’ to be followed in solving a problem.
▪In order to qualify as an algorithm, a sequence of instructions must possess following
characteristics:
a. Definiteness: Instructions must be precise and unambiguous. i.e., each and every
instruction should be clear and should have only one meaning.
b. Finiteness: Not even a single instruction must be repeated infinitely. i.e., each instruction
should be clear and performed in finite time.
c. Termination: After the algorithm gets executed, the user should get the desired result.
ALGORITHM
i. Sequence: Sequence means that each step of the Algorithm is executed in the specified
order.
ii. Decision: Decision statements are used when the outcome of process depends on some
condition.
iii. Repetition: Repetition involves executing one or more steps for a number of times
can be implemented using while, do-while, for loops.
ALGORITHM
Example:
1. Write an algorithm to compute the simple interest.
Step 1: [Initialize]
Start
Step 2: [Input the values of P, T, R]
Read P, T, R
Step 3: [Compute the Simple Interest]
SI= (P*T*R)/100
Step 4: [Display the Simple Interest]
Print SI
Step 5: [Finished] Stop
FLOWCHARTS
▪A flowchart is a “graphical or symbolic” representation of an algorithm.
▪Flowcharts used to design and develop complex programs to help the users to visualize the
logic of the program or better understanding of the program.
▪The symbols used to write flowcharts are given below:

Oval – Represents the terminal point (Start / End symbol)

Rectangle- Computational steps (used while assigning and calculating some results)

Parallelogram- Reading operation used for Input / Output or data or information from/to

any device
FLOWCHARTS
Diamond- Decision (questions) and consequently the branch points

Hexagon- Represents looping structures

Predefined process- Indicates subroutines, used when functions are used

Small Circle- Continuation from one point in the process flow to another

Arrows- the flowchart direction and connects the various flow chart symbols.
FLOWCHARTS
Advantages of Flowcharts
▪They act as a guide or blueprint for the programmer to code the solution in any programming language.
▪It helps programmers to understand the logic of complicated and lengthy problems.
▪They help to analyse the problem in a more effective manner.
▪Flowchart can be used to debug programs that have error(s).
Limitations of Flowcharts
▪Drawing flowcharts is a laborious and time consuming activity.
▪Flowchart of a complex program becomes complex and clumsy.
▪A little bit of alteration in the solution may require complete redrawing of the flowchart.
▪The essentials of what is done may get lost in the technical details of how it is done.
▪There are no well-defined standards that limit the details that must be incorporated in a flow chart.
PSEUDO CODE
▪“Pseudo code is nothing but a series of steps to solve a given problem written using a
mixture of English language and C like language.”
▪Pseudo code consists of statements which are a combination of English and C. It is not
quite ‘C’ code but can be translated.
▪Pseudo code is an outline of a program that can easily be converted into programming
language.
▪Flowcharts can be considered as graphical alternatives to pseudo codes but requires
more space on paper.
KEY DIFFERENCES BETWEEN ALGORITHM AND PSEUDOCODE
• An algorithm is a definite, clear sequence-wise procedure to solve a problem. It
involves the high-level language builds which cannot be understood by a non-
technical person. On the other hand, pseudo code is a more plain and human
understandable form of algorithm where natural language is also combined with the
high-level programming language constructs.

• Pseudo code is easy to understand and interpret as compared to an algorithm.

• The algorithm uses high-level constructs meaning the snippet of code but the pseudo
code involves natural language with high-level programming builds.

• Pseudo code is easily constructed and debugged relative to the algorithm.


Algorithm & Flowchart to calculate Simple Interest.
Start

Input P, T, R
Steps
Start
1. Input P, T, R SI = (P * T * R) / 100

2. SI = (P * T * R)/100
3. Print SI Print SI
Stop
Stop
PSUEDO CODE TO FIND SIMPLE INTEREST.

• Step 1: start
• Step 2 : Read the three input quantities P, N and R.
• Step 3 : Calculate simple interest as Simple interest = P* N* R/100
• Step 4: Print simple interest.
• Step 5: Stop.
Input an integer n and check whether it is odd or even
Steps Start

Start
Input n
Input n
If n%2 = 0
N%2= No Print
Print “Even” 0? “Odd”
Else Print “Odd” Yes
Print
Stop
“Even”

Stop
Find the biggest of 3 numbers Start
A
Steps Input a, b,
Start c
Input a, b, c No
c > big ?
big = a
big = a
If b > big Yes
big = b
big = c
If c > big No
big = c b > big?
Print big
Stop Yes
big = b Print big

A Stop
Generate the numbers 1 to 100 Start
Steps
Start c=1
Initialize counter, c = 1
while c<=100 repeatedly do
print c Print c
c=c+1
End while
c=c+1
Stop

No
c <= 100 ? Stop

Yes
Assignments – Algorithms and Flow Chart
1.Input radius of a circle, find the area and circumference of the circle.
2.Input marks in 5 subjects, find the total and average.
3.Input 2 values, simulate a calculator.
4.Input value in degrees and convert to radians radians = degrees * π / 180
5.Input 3 sides of a triangle a, b, c and find the area. area = √s (s-a)(s-b)(s-c) s = (a +
b + c)/2
6.Input 2 values, swap them and print the new values.
7.Input 3 numbers and find the smallest of them.
8.Find the sum of the following number sum = 1 + 2 + 3+ 50
HISTORY OF C
CREATING AND RUNNING PROGRAMS

1. Writing and editing program

2. Compiling program

3. Linking the program with required modules

4. Executing the program


Building a C Program Source code

Programmer

Object

Executable

Results
BUILDING A C PROGRAM
1. Writing and editing programs
• Text Editor : The software used to write programs
• After completing a program, save the file to the disk. The file is known as source
file.
2. Compiling programs
• Code in a source file must be translated into machine language which is done by
compiler.
• C compiler contains 2 separate programs
Pre processor Translator
Pre processor
•Reads the code and prepares it for translator.
•While preparing the code, scans pre processor commands.
•Translation Unit : The process of preparing the code for translation into machine
language.
Translator
•Does the actual work of translating the code to machine language.
•Reads translation unit and writes the resulting object module to a file that can be
compiled with other precompiled units to form final program.
•Object model : code in machine language.
BUILDING A C PROGRAM
3. Linking programs
• Linker assembles all the functions – our’s and system’s into final executable
program.
4. Executing programs
• Loader : OS program which gets the program into main memory.
• After this, the file is executed.
• The program reads data for processing and prepares for output.
INTRODUCING C LANGUAGE
• C is a structured and procedural programming language.
•C is used to develop both system and application software due to its portable
features.
Features of C
•Structured programming language
•Provides various operators and data types
•Can be compiled and executed on any computer
•Use of functions
•Use of pointers
8
7
STRUCTURE OF A C PROGRAM
Preprocessor directives

Global declarations

void main()
{
Local declarations

Statements
}
Other functions as required

8
8
1/18/2022 8
9
/* First C Program */
#include<stdio.h>
void main()
{
printf(“My first C Program”);
}

Output :
My first C Program

9
0
/* Three lines of statement */
#include<stdio.h>
void main()
{
printf(“Two types of Software”);
printf(“1.System Software”);
printf(“2.Application Software”);
}
Output :
Two types of Software 1.System Software 2.Application Software
9
1
Backslash constants (Escape sequence)
Non printing characters can be printed using escape sequence.
It always starts with \ followed by a character.

Escape sequence Description Escape sequence Description

\a System alarm \” Double quote


\b Backspace \’ Single quote
\n Newline \\ \ (backslash)
\t Horizontal tab \0 Null character

9
2
1.
#include<stdio.h>
void main()
{
printf(“RNS Istitute of Technology\n”);
printf(“R.R.Nagar\tBangalore”);
}
Output
RNS Istitute of Technology
R.R.Nagar Bangalore

9
3
2.
#include<stdio.h>
void main()
{
printf(“A\nA\tB\nA\tB\tC\nA\tB\tC\tD”);
}
Output
A
A B
A B C
A B C D
9
4
Write C programs to get the following outputs
1.
Students’ of RNSIT
Semester I \ II
“Bangalore”

2.
Marks Grade
75 – 100 A
60 – 74 B
50 – 59 C
40 – 49 D
<40 E

9
5
BASIC C CONCEPTS
1. Character set
2. Tokens

Character Set
• Alphabets A - Z, a - z
• Digits 0-9
• Special symbols *,@,%,{,[,),#
• White spaces, new line, horizontal tab

9
6
2. Tokens
Each individual unit in a program is a Token.
Example
c = a + b * 10; Result = (x * y) * (x – y);

97
Keywords (Reserved words)
• Reserved words which have a pre-defined meaning in C compiler.
• Used for specific task in C language.

auto double int struct


break else long switch
case enum register typedef
char extern return union
const float short unsigned
continue for signed void
default goto sizeof volatile
do if static while

98
Identifiers
Names provided to the elements of the program such as variables, functions and arrays.
Rules for naming an identifier
1. Can consist of alphabets, digits and _ (underscore).
2. Must always begin with an alphabet or _ and can be followed by digits.
3. No special symbols allowed.
4. Case sensitive.
5. Cannot be a keyword.

99
Valid examples of Identifiers
Total sum1
Voter_ID roll_no
Invalid Identifiers
for 1stname
sum-of-digits roll number
#USN NO I Class
void stream(branch)

10
0
Constants(Literals)
A fixed value assigned to an identifier whose value cannot be changed.
Types of constants

Constants

Integer Float Character String

Decimal

Octal

Hexa Decimal

10
1
1. Integer constant b) Octal
Whole numbers without decimal part. • Constants having digit combination
a) Decimal between 0 – 7.
Constants having digit combination • Can be + or –
between 0 – 9. • The constant must have the prefix 0
Can be + or – (Zero).
Valid ex: -45 756 Valid ex: 077 -0756
1234 01234
Invalid ex : 102 56 4.50 Invalid ex : 0102 56 -017.7 856
-+56
10
2
c) Hexa Decimal
• Constants having digit combination between 0 – 9 and A – F.
• A ---> 10 F --->15
• Can be + or –
• The constant must have the prefix 0X / 0x.

Valid ex: 0X917 -0x1AF 0x304a


Invalid ex : 18C 0X1GA 0x4.6E

10
3
2. Float constant
• Represents a number having fractional part.
• May be + or –
Examples : -221.45, 44567.34, 0.000009
3. Character constant
• Represents a single character within a pair of ‘ ‘
• Stored as integers in computer’s memory.
Examples :
char op = ‘+’;
char choice = ‘Y’;
10
4
4. String constant
Represents a sequence of characters within a pair of “ “
Examples : “Good Morning”, “10 + 40”, “R.N.S”

Data Types
• Defines the type of data that is stored in a variable.
• Determines how much storage should be allocated to a variable.

10
5
BUILTIN DATATYPES IN C
Data type Description Size (bytes) Range

char Stores single character 1 -128 to 127

int Stores integer values 2 - 32768 to 32767

float Stores real numbers 4 3.4 e-38 to 3.4 e38

double Stores real numbers 8 1.7 e-308 to 1.7 e308

void Stores no values - -


Returns no values

10
6
char
Each character constant is stored internally in the computer as integer constant.
Ex :
Char constant ASCII value
void main()
‘A’ 65
{ ‘B’ 66
char var1 =‘a’; ‘a’ 97
‘b’ 98
char var2 = ‘E’; ‘0’ 48
char var3 = ‘7’, var4 = ‘*’; ‘1’ 49
}

10
7
int float
Signed int : +ve or –ve values Ex :
Unsigned int : only +ve values void main()
Ex : { float a, b, c;
void main() a=7.1;
{ int a = 10; b=77.89;
int b, sum; c=a-b;
b=60; }
sum=a+b;
}
10
8
double
Ex :
void main()
{ double a, b, c;
a=78907.1976;
b=751237.89;
c=a*b;
}
void
Stores no values, non-specific data type.
10
9
PROGRAM TO DISPLAY SIZE OF DIFFERENT DATA TYPES
#include <stdio.h>
#include <conio.h>
main()
{
clrscr();
printf(" short int is %2d bytes \n", sizeof(short int));
printf(" int is %2d bytes \n", sizeof(int));
printf(" int * is %2d bytes \n", sizeof(int *));
printf(" long int is %2d bytes \n", sizeof(long int));
printf(" long int * is %2d bytes \n", sizeof(long int *));
printf(" signed int is %2d bytes \n", sizeof(signed int));

1/18/2022 11
0
printf(" signed int is %2d bytes \n", sizeof(signed int));
printf(" unsigned int is %2d bytes \n", sizeof(unsigned int));
printf("\n");
printf(" float is %2d bytes \n", sizeof(float));
printf(" float * is %2d bytes \n", sizeof(float *));
printf(" double is %2d bytes \n", sizeof(double));
printf(" double * is %2d bytes \n", sizeof(double *));
printf(" long double is %2d bytes \n", sizeof(long double));
printf(“ \n ");
printf(" signed char is %2d bytes \n", sizeof(signed char));
printf(" char is %2d bytes \n", sizeof(char));

1/18/2022 11
1
printf(" char * is %2d bytes \n", sizeof(char *));
printf("unsigned char is %2d bytes \n", sizeof(unsigned char));
getch();
}
▪OUTPUT:

1/18/2022 11
2
Variable
An identifier which can store a value.
The value may change later in the program.
Refers to a specific memory location where the data can be stored.

Rules for naming a variable:


Same as naming identifiers

11
3
Declaring a Variable Initializing a Variable
Syntax: Ex:
Datatype variablename; int a =40;
Ex: float num1, num2;
int a; num1=67;
float num1, num2; num2=6.8;
char grade, name[21]; char grade=‘A’;

When a variable is defined, it is not initialized.


We must initialize any variable requiring
prescribed data when the function starts.

11
4
MANAGING INPUT AND OUTPUT FUNCTIONS
Stream is a logical entity that represents
a file or device, that can accept input or
output.

Text stream consists


Binary stream
of one or more lines
consists of long
of text-terminated
series of characters
by \n
MANAGING INPUT AND OUTPUT OPERATIONS
• GETCHAR – Reads one character from standard input
Variable_name = getchar ();
For Example:
void main()
{
answer = getchar(); (OR)
while(character != ‘\n’)
{
character = getchar();
}
}

11/19/2021 1
1
MANAGING INPUT AND OUTPUT OPERATIONS
• PUTCHAR - Writes one character to the standard output

putchar ( variable_name)
For example:
alphabet = getchar();
if(islower(alphabet))
putchar(toupper(alphabet));
else
putchar(tolower(alphabet));

11/19/2021 1
1
EXAMPLE 1
#include<stdio.h>
void main()
{
char c;
printf("\n Enter a character \n");
c=getchar(); //get a single character;
printf("Thanks for entering!!!See the entered character below");
putchar(c); //print a single character;
}

11/19/2021 1
1
EXAMPLE 2

#include <stdio.h>
#include <conio.h>
int main()
{
printf("Enter a key to exit the console screen.\n");
getch();
return 0;
}

11/19/2021 1
1
FORMATTED INPUT - SCANF
• FORMATTED INPUT – Refers to the input data that has been scanned in a
specific format to enhance readability. scanf ( formatted scan using the format
identifiers )
scanf(“control string”, arg1,arg2,arg3…argn);

The format string or control string consists of

Conversion character (%), a data type character (d,f,e,s,..) , optional field width

11/19/2021 1
2
▪The scanf function is used to read Formatted data from the keyboard. This
function takes the text stream from the keyboard Extracts and formats data from
the stream According to a format control string and then stores the data in
specified program variables.

• Width is an optional argument that specifies the maximum number of


characters to be read.
• Modifier is an optional argument that can be h, l or L for the data pointed
by the corresponding additional arguments.
• Type specifies the type of data that has to be read
Common Modifiers:
•h: Used for short integer types. For example, %hd reads or prints a short (16-bit) integer.
•l: Used for long integer types or double types in the case of floating-point numbers. For
example,
%ld reads or prints a long integer (32 or 64-bit, depending on the system).
•L: Used for long double types. For example, %Lf is used to read or print a long double,
which has more precision than a regular double.
FORMATTED INPUT – SCANF EXAMPLE 1
#include<stdio.h>
int main()
{
int a,b,c;
printf("Enter the first value");
scanf("%d",&a);
printf("Enter the second value");
scanf("%d",&b);
c=a+b;
printf("%d + %d = %d\n",a,b,c);
return 0;
}

11/19/2021 1
2
FORMATTED INPUT – SCANF EXAMPLE 2
int main ()
{
char city[20];
float gdp;

printf("Enter name of the city: ");


scanf("%s", &city);
printf("The city value is: %s", city);

printf("Enter the GDP of the city: ");


scanf("%f", &gdp);
printf("The GDP value of the city value: %f", gdp);
return 0;
}
11/19/2021 1
2
FORMATTED INPUT
▪ INPUTTING INTEGER NUMBERS:
Field specification for reading an integer number is: %wd
Example: int num1,num2,num4;
float num3;
scanf(“%2d %5d”, &num1, &num2); 89765 45
printf(“%d %d”, num1, num2); --------- 89 765
scanf(“%f %d”, &num3, &num4); 59.0 657
printf(“%f %d”, num3, num4);-----59.0 657

Suppose Input data is : 31426 50 num1 ----- 31


num2 ----- 426

1
2
FORMATTED INPUT
▪An input field may be skipped by specifying * in the place of field width.
scanf(“%4d %*d %3d”, &a, &b);
Input values : 123 456 789

a b
▪INPUTTING REAL NUMBERS :
scanf(“%f %f %f ”, &x, &y, &z); Input data : 475.89 43.21e-01 678

Values assigned : 475.89--- x 4.321---- y 678.0 ---- z

1
2
FORMATTED INPUT
▪Inputting Character Strings : %ws OR %wc

▪READING MIXED DATA TYPES :


scanf(“%d %c %f %s”, &count, &code, &ratio, name);
Will read the data ----------- 15 p 1.575 coffee

1
2
FORMATTED OUTPUT – PRINTF
▪ FORMATTED OUTPUT – Refers to the output data that has been arranged in
a specific format to enhance readability. printf ( formatted print using the
format identifiers )
printf(“control string”, arg1,arg2,arg3….argn);
▪ Characters that has to be printed on the screen as they appear
▪ Format specifications that define the output format
▪ Escape sequence characters such as \n, \t and \b

11/19/2021 1
3
▪The printf function is used to display information required by the user and also
to print the values of the variables

Flags Specify output justification such as decimal point,numerical sign, trailing


zeros or octal, decimal or hexadecimal prefixes.
▪Width specifies the minimum number of characters to print after being padded
with zeros or blank spaces, that is it specifies the minimum number of positions
in the output
PRINTF FORMAT SPECIFIERS

11/19/2021 1
3
PRINTF – EXAMPLE 1
#include <stdio.h>
int main()
{
char ch;
char str[100];
printf("Enter any character \n");
scanf("%c", &ch);
printf("Entered character is %c \n", ch);
printf("Enter any string ( up to 100 character ) \n");
scanf("%s", &str);
printf("Entered string is %s \n", str);
}

11/19/2021 1
4
PRINTF – EXAMPLE 2
#include <stdio.h>
int main ()
{
char str1[20], str2[30];

printf("Enter name: ");


scanf("%s", str1);

printf("Enter your website name: ");


scanf("%s", str2);

printf("Entered Name: %s\n", str1);


printf("Entered Website:%s", str2);
}
11/19/2021 1
4
FORMATTED OUTPUT
OUTPUT OF INTEGER NUMBERS:
Format specification for printing an integer number is: %wd
Format
printf(“%d”, 1234);
printf(“%5d”, 123);
printf(“%-3d”, 12);
printf(“%03d”,12);

1
4
FORMATTED OUTPUT
▪OUTPUT OF REAL NUMBERS :
Format specification: %w.pf
We can also display a real number in exponential notation : %w.pe
The display takes the form : [-] m.nnnne[+-]xx ---- 12345.67891
▪Some systems also support a special field specification character that lets the
user define the field size at run time.
printf(“%*.*f ”,7,2,number);

1
4
FORMATTED OUTPUT
▪y = 98.7654 ---- 9.87650e+01

1
4
FORMATTED OUTPUT
▪PRINTING A SINGLE CHARACTER: %wc

▪PRINTING STRINGS :
The format specification for outputting strings is similar to that of real numbers.
%w.ps

1
4
MIXED DATA OUTPUT
▪It is permitted to mix data types in one printf statament.

printf(“%d %f %s %c”, a, b, c, d);

1
4
1
4
1
5
1
5
QUERIES THANK YOU
??

1/18/2022 15
6

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy