DD CP Chapter2
DD CP Chapter2
UNIT - II
INTRODUCTION
Computer has emerged as the most useful machine in recent times. It can perform wide
variety of tasks like receiving data, processing it, and producing useful results. However, being
a machine, the computer cannot perform on its own. A computer needs to be instructed to
perform even a simple task like adding two numbers. Computers work on a set of instructions
called computer program, which clearly specify the ways to carry out a task. A computer takes
instructions, in the form of computer programs, and carries out the requested task.
The human beings use natural languages such as English, Spanish, or French to
communicate. Similarly, a user communicates with the computer in a language understood by
it. The instructions, provided in the form of computer programs, are developed using computer
or programming languages.
DEVELOPING A PROGRAM
A program consists of a series of instructions that a computer processes to perform, the
required operation. In addition, it also contains some fixed data, required to perform the
instructions, and the process of defining those instructions and data. Thus, in order to design a
program, a programmer must determine three basic rudiments:
1. The instructions to be performed.
2. The order in which those instructions are to be performed.
3. The data required to perform those instructions.
To perform a task using a program, a programmer has to consider various inputs of the
program along with the process, which is required to convert input into desired output. Suppose
we want to calculate the sum of two numbers, A and B, and store the sum in C, here A and B
are the inputs, addition is the process, and C is the output of the program.
A, B C=A+B C
1
Computer Programming Unit II
programming language. One common technique is to use the program development cycle, with
the number of steps that may vary according to the person who has formalized the development.
Development cycle of a program includes the following phases.
Algorithm Testing
1. Analyze/Define the Problem: The problem is analyzed precisely and completely. Based on
understanding, the developer knows about the scope within which the problem needs to be
analyzed.
2. Task Analysis: After analyzing the problem, the developer needs to develop various
solutions to solve the given problem. From these solutions, the optimum solution is chosen,
which can solve the problem comfortably and economically.
3. Designing Phase: After selecting the appropriate solution, algorithm is developed to depict
the basic logic of the selected solution. An algorithm depicts the solution in logical steps.
Further, algorithm is represented by flowcharts and pseudocodes. These tools make program
logic clear and they eventually help for coding. This phase is also known as design phase.
4. Testing the Algorithm for Accuracy: Before converting the algorithms into actual code, it
should be checked for accuracy. The main purpose of checking algorithm is to identify major
logical errors at an early stage, because logical errors are often difficult to detect and correct at
later stages.
5. Coding: After meeting all the design considerations, the actual coding of the program takes
place in the chosen programming language. Depending upon application domain and available
resources, a program can be written by using computer languages of different levels such as
machine, assembly or high-level languages.
6. Test and Debug the Program: It is common for the initial program code to contain errors,
2
Computer Programming Unit II
a program compiler and programmer-designed test data machine tests the code for syntax
errors. The results obtained are compared with results calculated manually from this test data.
Depending upon the complexity of the program, several rounds of testing may be required.
7. Documentation and Implementation: Once the program is free from all the errors, it is the
duty of the program developers to ensure that the program is supported by suitable
documentation. After documentation, the program is installed on the end user's machine.
ALGORITHMS
Algorithms are one of the most basic tools that are used to develop the problem solving
logic. An algorithm is defined as a finite sequence of explicit instructions that, when provided
with a set of input values produces an output and then terminates. In algorithm, after a finite
number of steps, solution of the problem is achieved. Algorithms can have steps that repeat
(iterate) or require decisions (logic and comparison) until the task is completed.
Different algorithms may accomplish the same task, with a different set of instructions,
in more or less the same time, space, and efforts. For example, two different recipes for
preparing tea, one ' add the sugar' while 'boiling the water' and the other 'after boiling the water'
produce the same result. However, performing an algorithm correctly does not guarantee a
solution, if the algorithm is flawed or not appropriate to the context. For example, preparing
the tea algorithm will fail if there were no tea leaves present; even if all the motions of preparing
the tea were performed as if the tea leaves were there. We use algorithms in our daily life.
For example, to determine the largest number out of three numbers A, B, and C, the
following algorithm may be used.
Step 1: Start
Step 2: Read three numbers say A, B, C
Step 3: Find the larger number between A and B and store it in MAX_AB
Step 4: Find the larger number between MAX_AB and C and store it in MAX
Step 5: Display MAX
3
Computer Programming Unit II
Step 6: Stop
The above-mentioned algorithm terminates after six steps. This explains the feature of
finiteness. Every action of the algorithm is precisely defined; hence, there is no scope for
ambiguity. Once the solution is properly designed, the only job left is to code that logic into a
programming language.
Algorithm Properties
The properties of Algorithm are:
1. There must be no ambiguity in any instruction.
2. There should not be any uncertainty about which instruction is to be executed next.
3. The algorithm should conclude after a finite number of steps. An algorithm cannot be open-
ended.
4. The algorithm must be general enough to deal with any contingency.
FLOWCHART
A flowchart is a pictorial representation of an algorithm in which the steps are drawn
in the form of different shapes of boxes and the logical flow is indicated by interconnecting
arrows. The boxes represent operations and the arrows represent the sequence in which the
operations are implemented. The primary purpose of the flowchart is to help the programmer
in understanding the logic of the program.
Flowcharts can be compared with the blueprint of a building. Just as an architect draws
a blueprint before starting the construction of a building, a programmer draws a flowchart
before writing a computer program. As in the case of the drawing of a blueprint, the flowchart
is drawn according to defined rules and using standard flowchart symbols prescribed by
,American National Standard Institute (ANSI). Some standard symbols that are frequently
required for flowcharts are shown below.
4
Computer Programming Unit II
5
Computer Programming Unit II
Benefits of-Flowcharts A flowchart helps to clarify how things are currently working and how
they could-be improved. The reasons for using flowcharts as a problem-solving tool are given
below.
• Makes Logic Clear: The 'main advantage of using a flowchart to plan a task is that it
provides a pictorial representation of the task, which makes the logic easier to follow. Even
less experienced personnel can trace the actions represented by a flowchart, that is, flowcharts
are ideal for visualizing fundamental control structures employed in computer programming.
• Communication: Being a graphical representation of a problem-solving logic, flowcharts
are better way of communicating the logic of a system to all concerned. The diagrammatical
representation of logic is easier to communicate to all the interested parties as compared to
actual program cede as the users may not be aware of all the programming techniques and
jargons.
• Effective Analysis: With the help of a flowchart, the problem can be analyzed in an
effective way. This is because the analyzing duties of the programmers can be delegated to
6
Computer Programming Unit II
other persons, who may or may not know the programming techniques, but they have a broad
idea about the logic.
• Useful in Coding: The flowcharts act as a guide or blueprint during the analysis and
program development phase. Once the flowcharts are ready, the programmers can plan the
coding process effectively as they know where to begin and where to end, making sure that no
steps are omitted. As a result, error free programs are developed in high-level language and
that too at a faster rate.
• Proper Testing and Debugging: By nature, a flowchart helps in detecting the errors in a
program, as the developers know exactly what the logic should do.
• Appropriate Documentation: Flowcharts serve as a good program documentation tool.
Since normally the programs are developed for novice users; they can take the help of the
program documentation to know what the program actually does and how to, use the program.
Limitations of Flowcharts Flowchart can be used for designing the basic concept of the
program in pictorial form but cannot be used for programming purposes. Some of the
limitations of the flowchart are given as follows:
• Complex: The major disadvantage in using flowcharts is that when a program is very large,
the flowcharts may continue for many pages, making them hard to follow.
• Costly: Drawing flowcharts are viable only if the problem-solving logic is straightforward
and not very lengthy. However, if flowcharts are to be drawn for a huge application, the time
and cost factor of program development may get out of proportion, making it a costly affair.
• Difficult to Modify: Due to its symbolic nature, any changes or modification to a flowchart
usually requires redrawing the entire logic again, and redrawing a complex flowchart is not a
simple task. It is not easy to draw thousands of flow lines and symbols along with proper
spacing, especially for a large complex program.
• No Update: Usually programs are updated regularly. However, the corresponding update
of flowcharts may not take place, especially in the case of large programs. As a result, the logic
used in the flowchart may not match with the actual program's logic.
PSEUDOCODE
Pseudocode (pronounced soo-doh-kohd) is made up of two words: pseudo and code.
Pseudo means imitation and code refers to instructions, written in a programming language. As
the name suggests, pseudocode is not a real programming code, but it models and may even
7
Computer Programming Unit II
look like programming code. Pseudocode uses plain English statements rather than symbols,
to represent the processes of a computer program. It is also known as PDL (Program Design
Language), as it emphasizes more on the design aspect of a computer program or structured
English, because usually pseudocode instructions are written in normal English, but in a
structured way.
If an algorithm is written in English, the description may be at such a high level that it
may prove difficult to analyze the algorithm and then to transform it into actual code. If instead,
the algorithm is written in code, the programmer has to invest a lot of time in determining the
details of an algorithm, which he may choose not to implement (since, typically, algorithms are
analyzed before deciding which one to implement). Therefore, the goal of writing pseudocode
is to provide a high-level description of an algorithm, which facilitates analysis and eventual
coding, but at the same time suppresses many of the details that are insignificant. For example,
the pseudocode given below calculates the area of a rectangle.
Pseudocode uses some keywords to denote programming processes. Some of them are:
• Input: READ, OBTAIN, GET, and PROMPT
• Output: PRINT, DISPLAY, and SHOW
• Compute: COMPUTE, CALCULATE, and DETERMINE
• Initialize: SET and INITIALISE
• Add One: INCREMENT
Pseudocode Guidelines Writing pseudocode is not a difficult task. Even if you do not know
anything about the computers or computer languages, you can still develop effective and
efficient pseudo codes, if you are writing in an organized manner.
Here are a few general guidelines for developing pseudocodes:
• Statements should be written in simple English and should be programming language
independent. Remember that pseudocodes only describe the logic plan to develop a
program, it is not programming.
• Steps must be understandable, and when the steps are followed, they must produce a
8
Computer Programming Unit II
Benefits of Pseudocode Pseudocode provides a simple method of developing the program logic
as it uses everyday language to prepare a brief set of instructions in the order in which they
appear in the completed program. It allows the programmer to focus on the steps required to
solve a program rather than on how to use the computer language. Some of the most significant
benefits of pseudocode are:
• Since it is language independent, it can be used by most programmers.
• It is easier to develop a program from a pseudocode than with a flowchart.
• Often, it is easy to translate pseudocode into a programming language, a step which can be
accomplished by less experienced programmers.
• Unlike flowcharts, pseudocode is compact and does not tend to run over many pages. Its
simple structure and readability makes it easier to modify.
INTRODUCTION TO C
HISTORY OF C
C is a high level programming language. C language is derived from two languages
BCPL & B in 1960 at Cambridge University. C language is developed at Bell Laboratories in
9
Computer Programming Unit II
1972. Dennis Ritchie invented C language. C Language mainly evolved from ALGOL, BCPL
and B. C is developed for programming in OS called UNIX.
STRUCTURE OF C PROGRAM
Documentation Section
Header File Section / Link Section
Definition Section
Global (Variable) Declaration Section
main()
{
10
Computer Programming Unit II
Documentation Section
Documentation section consists of set of command lines. It is included in the first line
of a C program. It consists of comments. There are two types of comments. They are Single
line Comments and Multi line comments. Comments are used to give a meaningful name to a
C Program.
Single line comments are specified with two backslash // or /*’ and ended with */ in a
same Line. Multi line comments are specified by a backslash ( / ) followed by an asterisk ( * )
symbol and ended with asterisk symbol ( * ) followed by Backslash ( / ).
Definition Section
It is used to define symbolic constants.
11
Computer Programming Unit II
Global variable can be used inside and outside or anywhere within the program.
Variables must be declared before being used in a C program. clrscr() statement is used after
variable declaration and before the beginning of control statements. Declaration helps to define
a variable and use it in a Program. Sub program contains user defined function.
main( ) section
The execution of C program starts from the main function. Every C program must have
a main function. It contains two parts. They are declaration part and executable part.
Declaration part and executable part must appear between opening ‘ { ' and closing braces ‘ }’.
Opening brace specifies the beginning of C program and close brace specifies the logical end
of C program.
Declaration part
Declaration part is used to declare variables. Every variable must be declared before
using it in C program. Every variable are specified with their data type followed by a name. If
there are more variables of same data type then they must be separated by commas.
Execution part
Execution part contains program statements. There may or may not be a declaration
part but there must be an execution part. It includes input and output statements.
C CHARACTER SET
Character set denotes alphabet, digit or special character. Characters combine to form
variables. Characters in C are grouped into Letters, Digits, Special characters and White spaces.
Compiler generally ignores white space when it is not a part of string constant. White Space
may be used to separate words, but not used between characters of keywords or identifiers.
The character set in C Language can be grouped into the following categories.
1. Letters 2. Digits 3. Special Characters 4. White Spaces
Alphabets
12
Computer Programming Unit II
Special Characters
& .Ampersand # .Number Sign
' .Apostrophe < .Opening Angle (Less than sign)
* .Asterisk . .Period ( Dot )
@ At symbol % .Percentage Sign
\ .Backslash + .Plus Sign
^ .Caret ? .Question Mark
> .Closing Angle (Greater than sign) " .Quotation Marks
: .Colon } .Right Flower Brace
, .Comma ) .Right Parenthesis
$ .Dollar Sign ] .Right Bracket
.= Equal to ; .Semicolon
! .Exclamation Mark / .Slash
( .Left Parenthesis ~ .Tilde
[ .Left Bracket _ .Underscore
{ .Left Flower Brace | .Vertical Bar
TOKENS
Among the group of text individual word, punctuation marks are called Tokens. It is a
smallest individual unit in a C program. C has 6 types of Tokens. They are
• Keyword
• Identifier
• Special symbols
13
Computer Programming Unit II
• Constant
• String
• Operators.
TOKENS
Keywords
Every word in C language is a keyword or an identifier. Keywords in C language cannot
be used as a variable name. The compiler specifically uses them for its own purpose and they
serve as building blocks of a c program. The following are the Keyword set of 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
Identifiers
Identifier is a name given to program elements such as variables, functions, procedure,
arrays and soon. First character must be an Alphabet or Underscore. Identifier consists of
sequence of letters, digits or combination of both.
14
Computer Programming Unit II
CONSTANT
Constant is a fixed value that doesn’t or does not change during the execution of a
program. It remains same throughout the program. Its value cannot be altered or modified in a
program. A variable is declared by the Keyword const. Constant is classified into three main
types.
Eg: const int a,b,c;
Constant is classified into three main types. They are described as follows.
1. Numeric Constant
2. Character Constant and
3. Symbolic Constant.
CONST
Character Constant is also known as single character constant. The Character constant
is mainly classified into three types. They are
i. Single character constants
Single character constant is also known as character constant. It contains single
character or number enclosed within a pair of single quotes. If number specified within single
quotes it is considered as character constant. It cannot be used with arithmetic expression.
15
Computer Programming Unit II
Strings are stored in memory as ASCII codes of characters. Each character is stored in one byte
or length of single character constant is one.
E.g:- Valid ‘A’ ‘m’ ‘’ ‘3’
Invalid “W” “ma”
Character M Y ” a g e i s
#
ASCII Code 77 121 34 97 103 101 35 105 115
Character % 2 blank ( t w o ) @
SYMBOLIC CONSTANT
16
Computer Programming Unit II
VARIABLE
Variable is a name given to Memory location in which data is stored. Variable acts as
value, which changes during the execution of program. Variable may take different value at
different times during execution.
The general format of any declaration
datatype v1, v2, v3, ……….. vn
where v1, v2, v3 are variable names. Variables are separated by commas. A declaration
statement must end with a semicolon.
Eg: int sum;
double average, mean;
VARIABLE ASSIGNMENT
It is another format of variable declaration. The general form is
data-type variable name [=value];
Here data type refers to the type of value used in the C program. Variable name is a
valid name. Square brackets [ ] denotes that the value may or may not be used or
specified within the program.
Eg: int a; (or) int a=10;
Here if the value of a is assigned 10 the value remains the same throughout the program.
If no value is specified then the value keeps on changing.
17
Computer Programming Unit II
Volatile Variable
A variable is volatile if the value gets changed at any time by some of the external sources.
Eg: volatile int num;
when we declare a variable as volatile the compiler will examine the value of the variable each
time it is encountered to see if an external factor has changed the value.
DATA TYPES
Data Type is used to define the type of value to be used in a Program. Based on the type
of value specified in the program specified amount of required Bytes will be allocated to the
variables used in the program. Data types are broadly classified into three main types. They are
as follows.
• Primary data type ( Fundamental Data Types)
• Derived data type
• User defined data type.
Primary Data Type
Integers are represented as int, character are represented as char, floating point value
are represented as float, double precision floating point are represented as double and finally
void are primary data types. Primary data type offers extended data types. longint, long double
are extended data types.
Integer Data Type
Integer data type can store only the whole numbers.
18
Computer Programming Unit II
19
Computer Programming Unit II
ARITHMETIC OPERATORS
Arithmetic operators are used to perform Arithmetic operations. They form a part of
program. Programs can be written with or without operators. But calculations are performed
only using operators. Operators act along Operand to produce result.
20
Computer Programming Unit II
RELATIONAL OPERATOR
Relational Operators are used to compare two same quantities. There are six relational
operators. They are mentioned one below another as follows.
Operator Meaning Operator Meaning
< is less than >= is greater than or equal to
<= is less than or equal to == is equal to
> is greater than != is not equal to
LOGICAL OPERATORS
Logical Operators are used when we need to check more than one condition. It is used
to combine two or more relational expressions. Logical Operators are used in decision making.
Logical expression yields value 0 or 1 i.e.,( Zero or One) . 0 indicates that the result of logical
expression is TRUE and 1 indicates that the result of logical expression is FALSE.
21
Computer Programming Unit II
Logical OR ( || )
If any of the expression is true the result is true else false otherwise. The result is similar
to basic Binary addition.
The logical OR is used to combine 2 expressions or the condition evaluates to true if
any one of the 2 expressions is true.
Eg: a < m || a < n
It evaluates to true if a is less than either m or n and when a is less than both m and n.
Logical NOT ( ! )
It acts upon single value. If the value is true result will be false and if the condition is
false the result will be true. The logical not operator takes single expression and evaluates to
true if the expression is false and evaluates to false if the expression is true.
Eg (!a)
EQUALITY OPERATOR
Equality operator ( = ) is used together with condition. The value of the expression is
one or zero. If the expression is true the result is one, if false result is zero.
Operator Meaning
== Equal to
!= Not equal to
Example :
x = 1 and y = 2 then
x = =2 is false , x = = 1 true , y != 3 true
22
Computer Programming Unit II
ASSIGNMENT OPERATORS
The Assignment Operator evaluates an expression on the right of the expression and
substitutes it to the value or variable on the left of the expression. The general form is
identifier = expression
Eg: x = a + b;
Here the value of a + b is evaluated and substituted to the variable x. ‘=’ equal to is used in
Assignment operators. It is of two types. They are
23
Computer Programming Unit II
CONDITIONAL OPERATORS
Conditional Operator Ternary operator is also known as “Ternary operator”. The
general form of Conditional Operator is
(exp1)?(exp2):(exp3);
where exp1 is the condition which is to be checked and exp2 is the true value and exp3 is the
false value. If the condition in exp1 is false then statement in exp3 will be automatically
executed.
Eg:
#include<stdio.h> Output:
void main() Enter the value of a and b: 125 100
{ The biggest value is 125
int x,y,z;
clrscr(); Enter the value of a and b: 25 100
printf(“Enter the value of a and b :”); The biggest value is 100
scanf(“%d %d”,&x,&y);
z=((x>y)?x:y);
printf(“The biggest value is %d”,z);
getch();
}
SPECIAL OPERATORS
Special operators are known as separators or punctuators. Special operators are
Ampersand ( & ) Braces ( { } ) Colon ( : ) Ellipsis ( … )
Asterisk ( * ) Brackets ( [] ) Comma ( , ) Hash ( # )
Parenthesis ( () ) Semicolon ( ; )
Ampersand ( & )
It is also known as addresss operator. It is specified before the identifier name. i.e.,
variable name. It indicates memory location of the identifier.
Asterisk ( * )
Asterisk ( * ) is also known as indirection operator. It is specified before identifier name.
It indicates creation of pointer variable. It is also a unary operator.
Braces ( { } )
24
Computer Programming Unit II
The opening brace ( { ) and closing brace ( } ) specify the start and end of compound statement
in a function. Here semicolon ( ; ) is not necessary. Semicolon ( ; ) is used only in structure
declaration.
Brackets
Brackets [] also referred as array subscript operator. It is used to indicate single and
multi dimensional arrays.
Eg: int x[10]; float l[10][20];
Colon ( : )
Colon ( : ) is used in labels. It is used in unconditional control statement i.e., in goto
statement.
Eg: goto d;
Comma Operator ( , )
It is used to link expressions together. It is used together with variables to separate one
variable from another. It is used in for loop. It has the lowest precedence among operators
Eg: for(n=1,m=10;n<=m; n++, m++)
int a,b,c;
sum= (x=5,y=3,x+y);
Ellipsis ( … )
Ellipsis ( … ) are three continuous dots with no white spaces between them. It is used
in function prototype. It indicates that the function can have any number of arguments.
Eg: void fun(char s,int n, float f, …);
Hash ( # )
Hash ( # ) is also known as pound sign. it is used to indicate preprocessor directives.
Eg: #include“stdio.h”
Parenthesis ( () )
Parenthesis ( () ) is also known as function call operator. It is used to indicate the open
and end of function prototypes, function call, function parameters, …. Parentheses are used to
group expressions.
Semicolon ( ; )
25
Computer Programming Unit II
SIZE-OF OPERATOR
This operator is used to return the size of string or character. It cannot be used in
together with Integers. The syntax is
sizeof(variable-name);
Eg:
26
Computer Programming Unit II
#include<stdio.h>
Output:
void main()
The value of x is 2
{
int x;
clrscr();
printf(“The value of x is %d”,sizeof(x));
getch();
}
PRECEDENCE OF OPERATORS
• Outermost Parenthesis is evaluated first.
• Then innermost parenthesis.
• If there is two or more parenthesis, then the order of execution is from left to right.
• Next Multiplication and Division are performed.
• Finally Addition and Subtraction.
Decrement Operators
It is used to decrease the value of the Operand by 1. There are two types of Decrement
Operators in C Language. They are pre decrement operator and post decrement operator.
27
Computer Programming Unit II
main() {
int a = 21;
int c ;
UNARY OPERATORS
Unary operators act on single operand to produce new value. It proceeds with operands.
Unary minus denotes subtraction. Subtraction operators require two operands but unary minus
require one operand. The operand used with this operator must be a single variable.
Operator Meaning
+ Unary plus operator; indicates positive value (numbers are positive without this, however)
- Unary minus
++ Increment by 1
-- Decrement by 1
28
Computer Programming Unit II
Eg:
Expression Result
++x 4
x++ 3
--x 2
x-- 3
In ‘C’ language, two types of Input/output statements are available, and all input and
output operation are carried out through function calls. Several functions are available for
input/output operations in ‘C’. These functions are collectively known as the standard I/O
library
29
Computer Programming Unit II
Input Output
Input Output
scanf() printf()
getchar() putchar()
getc() putc()
gets() puts()
Input Output
getchar() putchar()
getc() putc()
i) Single Character gets() puts() Input-getchar( ) function
A Single character can be given to the computer using ‘C’ input library function getchar()
The getchar() function is written in standard I/O library. It reads a single character
from a standard input device. This function do not require any arguments, through a
pair of empty parentheses, must follow the statements getchar().
The first statement declares x as a character type variable. The second statement causes
a single character to be entered from the standard input device and then assigned to variable x.
The putchar() function is used to display one character at a time on the standard output device.
This function does the reverse operation of the single character input function as discussed
above
Description Character variable is the valid ‘C’ variable of the type of char
data type
30
Computer Programming Unit II
This is used to accept a single character from the standard input to a character variable
Description Character variable is the valid ‘C’ variable of the type of char
data type
This is used to display a single character in a character variable to standard output device.
Description Character variable is the valid ‘C’ variable of the type of char
data type
❖ The getc() and putc() function are often used in file processing
Example char c; put(c);
The gets() function is used to read the string (string is a group of characters) from the standard
input device (keyboard)
Example gets(s);
The puts() function is used to display/write the string to the standard output device.
31
Example put(s);
Computer Programming Unit II
❖ The gets() and puts() function are similar to scanf() and printf() function but the
difference is in the case of scanf() input statement, when there is a blank space in input
text, then it takes the space as an ending of the string the remaining string are not been
taken.
Formatted Input/output refers to input and output, that has been arranged in a
particular format
Eg : LAK 3977
This line contains two parts of data that is arranged in a format, such data can be read
to the format of its appearance, as the first data should be read into a variable char, the second
into int. Such operation can be made possible in ‘C’ language by using the formatted
Input/output statements. Using these statements, the user must specify the type of data, that is
going to be accessed(Input/output)
Input Output
scanf() printf()
Input data can be entered into the computer using the standard input ‘C’ library function
called scanf(). This function is used to enter any combination of input.
The scanf() function is used to read information form the standard input
device(keyboard), scanf() function starts with a string arguments and may contain
additional arguments. Any additional argument must be pointer
32
Computer Programming Unit II
Example int n;
scanf(“%d”,&n);
Control String:
It is the type of data that the user going to accept via the input statements, this can be
formatted and always preceded with a ‘%’ sign. The below table illustrates code formats
(control strings) in Input/Output statements.
Format Meaning
String
%c Read single character.
%d Read a decimal integer.
%e Read a floating point value in Exponential form.
%f Read a floating point value.
%g Read a floating point value.
%h Reads a short integer.
%i Read a decimal, hexadecimal or octal integer.
%o Reads an octal integer.
%s Reads an string.
%u Reads an unsigned decimal integer.
%x Reads an Hexadecimal integer. (Unsigned) using lower case a – f
%[..] Reads a string of word(s).
%X Reads a hexadecimal integer (Unsigned) using upper case A – F
%u Reads a unsigned integer.
%U Reads a unsigned long integer.
%p Reads a pointer value
%hx Reads hex short
%lo Reads octal long
%ld Reads long
Each variable name (argument) must be preceeded by an ampersand(&). The (‘&’) symbol
gives the meaning “ address of” the variable.
33
Computer Programming Unit II
The scanf control string or placeholder consists of % at the beginning and type indicator at the
end. Apart from that it can have *, a maximum field width indicator and a type indicator
modified.
1. The control string must be preceded with (%) sign and must be within quotations, i.e.,
the address of variable should be passed.
2. If there is an number of input data items, items must be separated by commas and must
be preceded with (&) sign except for string input
3. The control string and the variables going to input should match with each other
Output data or result of an operation can be displayed from the computer to a standard
output device using the library function printf(). This function used to output any combination
of data. It is similar to the input function scanf(), except that it display data rather than input.
34
Computer Programming Unit II
4. The control string must be in quotations and there we can also use any other text to print
with data
5. Provide blank space in between the numbers for better readability
6. Print special messages wherever required in output
Scanf printf
Used to accept data Used to display data
Control string and & operator is used Control string only used.
It end with semicolon It end with semicolon
Number of input specified with format Number of input specified with format
String and enclosed within double string and separated by commas.
quotes.
The Input variables are specified using The output variables are specified by
Address operator (&) is separated by their name and separated by commas.
commas.
getchar() gets()
Used to receive a single character Used to receive a string with white spaces and blanks
Does not require any argument It require a single argument
scanf() gets()
Strings with white spaces cannot be Strings with any number of spaces can be
accessed until ENTER key is pressed accessed
Spaces and tabs are not acceptable as a Spaces and tabs are acceptable as a part of
part of the input string input string.
Can receive any number of characters and Only one string can be received at a time.
integers.
Format string and input variable name is Format string and address is specified.
specified.
All data types can be accessed Only character data types can be accessed
35
Computer Programming Unit II
puts() printf()
It can display only one string It can display any number of characters, integers or strings
at a time. at a time.
All data types are considered Each data type is considered separately, depending upon
as characters. the conversion specifications.
36