Module 1
Module 1
BPOPS103
PAVITHRA J
ASSISTANT PROFESSOR,
DEPT. OF AI & DS,
RNSIT
MODULE 1:
.
INTRODUCTION
CHARACTERISTICS OF COMPUTER
▪Speed
▪Accuracy
▪Automation
▪Diligence
▪Versatile
▪Memory
▪NoIQ
▪Economical
STORED PROGRAM CONCEPT
• 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
▪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
General Purpose
Application Specific
Components of a Computer
Hardware Software
Software Hardware
Application
System Software Software
Hardware Software
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:
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
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.
• The algorithm uses high-level constructs meaning the snippet of code but the pseudo
code involves natural language with high-level programming builds.
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
2. Compiling program
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.
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.
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
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.
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
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.
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’;
11
4
MANAGING INPUT AND OUTPUT FUNCTIONS
Stream is a logical entity that represents
a file or device, that can accept input or
output.
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);
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.
11/19/2021 1
2
FORMATTED INPUT – SCANF EXAMPLE 2
int main ()
{
char city[20];
float gdp;
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
1
2
FORMATTED INPUT
▪Inputting Character Strings : %ws OR %wc
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
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];
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.
1
4
1
4
1
5
1
5
QUERIES THANK YOU
??
1/18/2022 15
6