0% found this document useful (0 votes)
66 views43 pages

Unit - I Overview of C

The document provides an overview of the C programming language including its history, importance, basic structure, and components. It details how C evolved from other languages in the 1960s and 1970s and was standardized in the late 1980s. The summary outlines the typical sections of a C program including documentation, definitions, global declarations, the main function, and subprograms.

Uploaded by

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

Unit - I Overview of C

The document provides an overview of the C programming language including its history, importance, basic structure, and components. It details how C evolved from other languages in the 1960s and 1970s and was standardized in the late 1980s. The summary outlines the typical sections of a C program including documentation, definitions, global declarations, the main function, and subprograms.

Uploaded by

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

JSV COLLEGE OF ARTS AND SCIENCE

AATTUKARAMPATTI, DHARMAPURI-9

C lass : I B.Sc., (PHYSICS) Staff :J.GANESAN M.CA.,


Subject : SBEC:Programming in “C”

Unit – I Overview of C
History of C
 C seems a strange name for a programming language.
 But this strange sounding language is one of the most popular computer languages today because
it is a structured, high level, machine independent language.
 The root of all modern languages is ALGOL., introduced in the early 1960s. ALGOL was the
first computer language to use a block structure.
 ALGOL gave the concept of structured programming to the computer science community.
 In 1967,martin Richards developed a language called BCPL primarily for writing system
software.
 In 1970 ,ken Thompson created a language using many features of BCPL and called it simply B.
 B was used to create early versions of UNIX operating system at bell laboratories. both BCPL
and B were “type less” system programming languages.
 C was evolved from ALGOL, BCPL and B by Dennis Ritchie at the bell laboratories in 1972.
 C uses many concepts from these languages and added the concept of data types and other
powerful features.
 Since it was developed along with the UNIX operating system, it is strongly associated with
UNIX .
 This operating system, which was also developed at bell laboratories, was coded almost in
entirely in C.
 During 1970s, C had evolved into what is now known as “traditional c”. The language became
more popular after publication of the book “The C programming language” by brian
kerningham and dennis Ritchie in 1978.
 To assure that the C language remains standard in 1983, American national standards
institute(ANSI) appointed a technical committee to define a standard for C.
 The committee approved a version of C in December 1989 which is now known as ANSI C.
 It was then approved by the International Standards Organization (ISO)in 1990).
 During 1990’s , C++ , a language entirely based on C, underwent a number of improvements
and changes and became an ANSI/ISO approved language in November 1977.

-1–
 During the same period, sun Microsystems of USA created a new language Java modeled on C
and C++.
 Although C++ and java were evolved out of C, the standardization committee of C felt that a few
features of C++/Java.
 The result was the 1999 standard for C.
 The history and development of C is illustrated in fig1.1

Importance of C
 The increasing popularity of C is probably due to its many desirable qualities.
 It is robust language whose rich set of built –in functions and operators can be used to write any
complex program.
 The c compiler combines the capabilities of an assembly language with the features of a high
level language and therefore it is well suited for writing both system software and business
packages.
 Programs written in C are efficient and fast.
 This is due to its variety of data types and powerful operators it is many times faster than BASIC.
 There are 32 keyboards in ANSI C and its strength lies in its built –in functions.
 Several standard functions are available which can be used for developing programs.
-2–
 C is highly portable.
 C language is well suited for structured programming ,thus requiring the user to think of a
problem in terms of function modules or blocks.
 Another important feature of C is its ability to extend itself.
 A C program is basically a collection of functions that are supported by the C library.

Basic Structure of C Program


 A C program may contain one or more sections as shown in the following fig.
 The documentation section consists of a set of comment lines giving the name of the program,
the author and the other details, which the programmer would like to use later.
 The link section provides instructions to the compiler to link functions from the system library.
 The definition section defines all symbolic constants.
 There are some variables that are used in more than one function.
 Such variables are called global variables and are declared in the global declaration section that
is outside of all the functions.
 This section also declares all the user-defined functions.
 Every C program must have one main() function section.
 This section contains two parts, declaration part and executable part.
 The declaration part declares all the variables used in the executable part.
 There is at least one statement in the executable part.
 These two parts must appear between the opening and closing braces.
 The program execution begins at the opening brace and ending at the closing brace.
Documentation
 The closing brace of thesection
main() function section is the logical end of the program.
 All theLink
statements in the declaration and executable parts end with a semicolon(;).
Section
 The subprogram section contains all the user-defined functions that are called in the main()
Definition Section
function.
Globalfunctions
 User-defined Declaration Section placed immediately after the main function, although they
are generally
may appear
Main()in Function
any order.Section
Documentation
{
Section:-
 Documentation section consists of a set of comment lines giving the name of the program, author
name and other details.
}
Link Section:-
 Link section providesSection
Subprogram instruction to the compiler to link functions from the system library.

User

define
d-3–
Declaration Part

Executable Part

Function 1

Function2

-----------
-----------

Function n

Definition Section:-
 Definition section defines all symbolic constants.
Global declaration:-
 The global variables are declared in the section. Variables that are used in move than one
function are called global variables.
Main ( ) function section:-
 Every C program must have one main function section. This section contains two parts
 Declaration Part: The declaration part declares all the variables used in the executable part.
 Executable part: Contains at least one statement
 These two parts must appear between the opening and the closing braces. The program execution
begins at the opening brace and ends at the closing brace. All the statements in the declaration
and executable parts end with a semicolon.
##include
include<stdio.h>
Subprogram section:- <stdio.h>
#include<conio.h>
#include<conio.h>
 The subprogram section contains all the user defined function that is called the main function.
#define
#defineMAXMAX100 definition
100 definitionsection
section
User-defined function is generally placed after the main function.
int a = 10, b=10; global
global declarationsection
declaration
int a = 10, b=10; section
void
voidmain()
main()
{{ local
localvariable
variabledeclaration
declarationpart
part
int
intc;c; executable
executablestatements
statements
c=a+b;
c=a+b;
printf(“c
printf(“cisis%d”,
%d”,c);
c);
getch();
getch();
}}
-4–
The main ( ) function:-
 The main is a part of every C program. C permits different forms of main statement. Following
forms are allowed.
 Main ( )  Default return type is taken
 int main ( )  Returns an integer value
 void main ( )  Does not return any value
 main (void)  Function has no arguments
 void main (void)  Does not return any value and has no arguments
 int main (void)  Return an integer value and has no arguments.
The # define Directive:-
 A # define instruction defines value to a symbolic constant for use in the program. A # define is a
preprocessor compiler directive and not a statement. It is placed at the beginning before the main
( ) function. It should not end with a Semicolon.
Syntax:- #define
#definesymbolic_constant_name
symbolic_constant_name

Example:
# define PI 3.14
The # include Directive:-
 Function stored in the C library header files can be accessed using the # include directive.
Syntax:- #include
#include<filename>
<filename>

 Filename is the name of the library header file that contains the required function definition.
Example:
# include<stdio.h>
Executing a C program
 Executing a program written in C involves a series of steps. these are:-
1. Creating the program.
2. Compiling the program.

-5–
3. Linking the program with functions that are needed from the C library; and
4. Executing the program.
 The following figure illustrates the process of creating, compiling and executing a C
program.
 Although these steps remain the same irrespective of the operating system, system
commands for implementing the steps and conventions for naming files may differ on different
systems.

Character Set:
 C characters are grouped into the following categories.
1. Letters
2. Digits
3. Special Characters
4. White Spaces
CATEGORY CHARACTERS

-6–
Letter Uppercase  A to Z, LowerCase a to z
Special Character , comma &ampersand
. Period ^ caret
; semicolon * asterisk
: colon – minus sign
? question mark + plus sign
“ Quotation mark < Less than sign
! Exclamation mark > Greater than sign
| Vertical bar ( Left parenthesis
/ Slash ) Right parenthesis
\ Black Slash [ Left bracket
~ Tilde ] Right brace
_ Under score { Left brace
$ Dollar sign } Right brace
% Percent Sign # number Sign
Digits All decimal digits 0…………9
White Spaces Blank space Horizontal Tab Carriage return New line Form feed

Trigraph sequences Translation


?? = # number sign
??( [ left bracket
??) ] right bracket
??< { left brace
??> } right brace
??! | vertical bar
??/ \ back slash
??/ ^ caret
??- ~ tilde

C Tokens:-
 In C programs, the smallest individual units are known as tokens.

-7–
Keywords and Identifiers:-
 Every C word is classified as either a keyword or an identifier.
 All keywords have fixed meanings and these meanings cannot be changed.
 Keywords serve as basic building blocks for statements.
Auto Continue Enum If Short tupedef
Break Default Extern Int Signed Union
Case Do Flaot Long Sizeof Struct
Char Double For Register Static Switch
Const Else Goto Return Void volatitle
Identifiers:-
 Identifiers refer to the names of variables, functions and arrays.
 They are user-defined names and consist of a sequence of letters and digits, with a letter as a first
character.
 Both uppercase and lowercase letters are permitted.
 The underscore character is also permitted in identifiers.
Rules for Identifiers:-
 First character must be an alphabet (or underscore)
 Must consists of only letters, digits or underscore( _ )
 Only first 31 characters are significant
 Cannot use a keyword
 Must not contain white space
Example:-
 Height, name, studentname
Valid Id Non-valid id
Number 1a  starts with digits

-8–
A1 A 1  space between is not allowed
_1 A , b  , is not allowed
A1b

Constants:-
 Constants in C refer to fixed values that do not change during the execution of a program.

CONSTANTS

Numeric Character Constant

Integer Constant Real Constant Single String constant

Types Constants:-
Numeric constant:-
 It consists only of numerals, with an optional sign and an optional period. It is divided into two
types namely,
 Integer constants
 Real constants

Integer Constants:-
 An integer constant refers to a sequence of digits,
 There are three types integers, namely, decimal, octal, and hexa decimal.
 Decimal integer
 Octal integer
 Hexadecimal integer
Decimal Constant:-
 It consists of a set of digits 0 through 9 preceded by optional + or – sign
Examples:-
Valid examples of decimal integer constants
123 -123 10 65478 _78
In valid examples of decimal integer constants
15 700 15,700 $ 15700

-9–
Note: Embedded spaces, commas and non-digit characters are not permitted between digits.
Eg: 1) 15 750 2)$1000
Octal Constant:-
 An octal integer constant consists of any combination of digits from the set 0 through 7, with a
leading 0.
Eg: 1) 037 2) 0435 3) 0551
Hexadecimal Constant:-
 A sequence of digits preceded by 0x or 0X is considered as hexadecimal integer.
 They may also include alphabets A through F or a through f.
Eg: 1) 0X2 2) 0x9F 3) 0Xbcd
Note:-
 The largest integer value that can be stored is machine-dependent.
 It is 32767 on 16-bit machines.
 It is possible to store larger integer constant on these machines by appending qualifiers such as U
, L and UL to the constants
56789U (unsigned integer)
98761234UL (Unsigned long integer)
9876543L (long integer)
Real Constants:-
 Certain quantities that vary continuously, such as distances, heights etc., are represented by
numbers containing functional parts like 17.548.
 These numbers are shown in decimal notation, having a whole number followed by a decimal
point and the fractional part.
 It is possible to omit digits before or after the decimal point.
 Such numbers are called real (or floating point) constants.
Eg:0.0083,-0.75 etc.,

 A real number may also be expressed in exponential or scientific notation.


Eg:215.65 may be written as 2.1565e2
 For example the value 215.65 may be written as 2.565E2 in exponential notation. E2 means
multiply by 102
 The general form:-
 Mantissa e exponent
 The mantissa is either a real number expressed in decimal notation or an integer.
 The exponent is an integer number with an optional + or _ sign.
 The letter e separates the mantissa and the exponent.
 The exponent causes the decimal point to float this notation is said to represent a real number in
- 10 –
floating point form.
Character Constants:-
 It consists of one (or) more characters of the alphabet of C. There are two types namely
 Single character constant
 String constant
Single Character Constants
 A single character constants contains a single character enclosed within a pair of single quote
marks.
Eg: ’5’ , ‘X’ , ‘;’
String Constants:-
 A string constant is a sequence of characters enclosed in double quotes.
 The characters may be letters, numbers, special characters and blank space.
Eg: ”Hello!”, “1987”, “?….!”
Backslash Character Constants:-
 C supports special backslash character constants that are used in output functions.
 These character combinations are known as escape sequences.

Constant Meaning
‘\a’ Audible alert (bell)

‘\b’ Backspace

‘\f’ From feed

‘\n’ New line

‘\r’ Carriage return

‘\t’ Horizontal tab

‘\v’ Vertical tab

‘\” Single quote

‘\ ‘ Double quote

‘\? ‘ Question mark

‘\ \ ‘ Backslash

‘\0’ Null

Variables:-
Definition:
- 11 –
 A variable is a data name that may be used to store a data value.
 The values of the variables can be changed during the execution of the program.
 A variable may take different values at different times of execution and may be chosen by the
programmer in a meaningful way.
 It may consist of letters, digits and underscore character.
Eg: 1) Average
2) Height
Rules for defining variables:-
 They must begin with a letter. Some systems permit underscore as the first character.
 ANSI standard recognizes a length of 31 characters. However, the length should not
be normally more than eight characters.
 Uppercase and lowercase are significant.
 The variable name should not be a keyword.
 White space is not allowed.

Examples of valid variable names:-


Name age
Invalid examples
123 8 height

Declaration Of Variables:-
 Declaration of a variable does two things
o It tells the compiler what the variable name is
o It specifies what type of data the variable will hold.
 The variables must be declare before they are used in the program.

The syntax is:-


Data-type v1,v2…..vn;

Eg: 1. int count;


2. double ratio, total;
Primary Type Declaration:-
 Variables can be used to store a value of any data type. The syntax for declaring the variables is
given below.

Data-
Data-type
typeVariable
Variable_name;
_name;

- 12 –
 Data-type is any valid data type such as integer, float etc.,
 Variables_name , v1, v2…vn are names of variables such as height, sum etc.,
o Example:- int a;
int a, b ;
float c;
char c;
User-defined Type Declaration:-
1. Type def:-
 The “type definition” feature in C allows users to define an identifier that would represent an
existing datatype
 The user-defined data type identifier can later used to declare variables.

typedef
typedeftype
typeidentifier;
identifier;
Where:-
 Type refers to an existing data type
 “identifier” refers to the new name given to the data type.
Example:- typedef in units:-
o Units symbolizes int
o They can be later used to define variables as follows.
o Units n,m;
2. Enumerated data types::-
 Enumerated data types is another user-defined data type provided by ANSI C
 If is defined as follows:-
 Syntax:-

enum
enumidentifier
identifier{value1,value2,……valuen};
{value1,value2,……valuen};

Where:-
 Identifier is a used defined enumerated data type which can be used declare
variables that can have one of the values enclosed within the braces (known as
enumeration constant)
 We can declare variables to be of this new type as below
 enum identifier v1, v2…vn;
Example:-
o enum day {Monday, Tuesday, ……………Sunday)
o enum day week_st, week_end;

- 13 –
o Week_st = Monday;
o week_end = Friday;

Assigning Values To Variables:-


 The variables that are used in expression must be assigned values before they are encountered in
the program.
Value = amount + inrate * amount;
while (year <= PERIOD)
{
………………………
………………………
year = year + 1;
}
Assignment statement:-
 The value can be assigned to variables using the assignment operator equal
 The Syntax is

Variable_name=constant
Variable_name=constant

 C permits multiple assignment statement in one line.


Eg:1) int a=20;
2) bal=75.84;
3) yes=’x’;
Example:
initial_value=0;final_value=100
 The value of the variable on the left of the equal sign is set to the value of the variable on the
right.
 During assignment statements operation C converts the type of the value on the right-hand side
to the type on the left.
 It is also possible to assign a value to a variable at the time the variable is declared.
 The Syntax is

Data_type
Data_typevariable
variable_name
_name==constant;
constant;

 Examples:-
o int last_value = 100;
o char yes = ‘X’;
o double balance = 75.84;
- 14 –
 The process of giving initial values to variable is called “Initialization”.
 C permits the initialization of more than one variable is one statement using multiple assignment
operator.
 Example:
o p=q=s=0;
o x=y=z=MAX;

Reading data from keyboard:-


 Reading data from keyboard is another way for giving values to variables.
 By using input statement Scanf you can get the input values from keyboard.
 The Syntax is

Scanf(“Control
Scanf(“Controlstring”,
string”,&varaibles1,
&varaibles1,&Variable2,…..);
&Variable2,…..);

 Where control string contains the format of data being received and the ampersand symbol (&)
specifies the variable name’s address.
Examples: 1) Scanf(“%d”, &no);

Declaration of storage class:-


 Variables in C can have not only data type but also storage class
 It provides information about their locality and visibility.
 The storage class decides the portion of the program within which the variables are recognized.
 Example:-
/*Example of storage class*/
int m;
main()
{
int i;
float bal;
……
……
function1();
}
function1()
{
int i;
float sum;
……
- 15 –
……
}
 In the above example the variable m has been declared before the main is called global variable.
 It can be used in all the function in the program.
 A global variable is also known as external variable.
 The variable called I, balance are called local variable because they are declared inside a
function.
 C provides a variety of storage class specified that can be used to declare explicitly the scope and
life time of variable.
Storage class Meaning
Auto Local variable known to only to the function in which it is declared. Default is auto.
Static Local variables which exists and retains its value even after the control is transferred to calling
function
Extern Global variable known to all functions in the file
Register Local variable which is stored in the register.

Examples:-
1. auto in count;
2. register char ch;
3. static in x;
4. extern long total;
Note:-
 Static and external variables are automatically initialized to zero.
 Auto variables contain undefined values

Data Types
 A data type is the representation of information using a set of values and a set of operation
required for deriving further results.
 ANSI C supports four classes of data types.

1. Primary or Fundamental data types.


2. User-defined data types.
3. Derived data types.
4. Empty data set.
 All the C compilers support five fundamental data types, namely integer, character, floating
point, double and void.
 Integer data types occupy one word of storage and since the word sizes of machines vary the size
of an integer that can be stored depends on the computer.

- 16 –
 A signed integer uses one bit for sign and 15 bits for the magnitude of the number.
 Floating point numbers are stored in32 bits with 6 digits of precision.
 Floating point numbers are defined in C by the keyboard float.
 A single character can be defined as a character type data.
 Characters are usually stored in 8 bits of internal storage.
 Void type has no values. This is usually used to specify the type of the functions.
 The type of the function is said to be void when it does not return any value to the calling
function.
 The range of basic four data types shown in the following figure shown below:-

Primary (or )Fundamental data types:-


 All c compilers support five fundamental data types namely,
1) Integer (int)
2) character (char)
3) Floating Point (float)
4) Double-precision floating (double)
5) Void

PRIMARY DATA TYPES


Integral Types
Integer Character
Signed type Unsigned Char
int Unsigned int Signed char
short in Unsigned short Unsigned char

Floating point types


Void
float Double long

- 17 –
Size and range of Basic Data types:-
Data types Ranges of values Size(bits)
Char -128 to 127 8
Int -32,768 to 32,768 16
Float 3.4e-38 to 3.4e+e38 32
Double 1.73-308 to 1.73+308 64
Integer types:-
 Integers are whole numbers within a range of values.
 It occupies one word of storage, and the word size is varying from machine to machine.
 The range is -32,768 to 32, 768.
 Integers are defined with keyword in.
 The following are the extended integer data types:-

Data types Ranges of values


Int Unsigned int
Shor int Unsigned short int
Long int Unsigned long int

Floating types:-
 Floating point numbers are numbers with fractional point.
 The range is 3.4e -38 to 3.4e +38.
 These are defined with keyword float.
 Types:-
o Float  It takes 32 bit
o Double  It uses 64 bits giving a precision of 14 digits.
o Long double  It may takes 80 bits

Character types:-
 A single character can defined as a character type data.
 It takes 8 bits to store a value.
 The ranges from -128 to 127
 It is defined using the keyword char.
Void types:-
 The void type has no values.

- 18 –
 Void types is used specify the type of functions that do not return any value to the calling
function.
Defining Symbolic Constants:-
 We often use certain unique constants in a program.
 These constants may appear repeatedly in a number of places in the program.
 One example of such a constant is 3.142, representing the value of the mathematical constant
pi”.
 We face two problems in the subsequent use of such programs.
1. Problem in modification of the programs.
2. Problem in understanding the program.
Modifiability:-
 To change the value of “pi” from 3.142 to 3.14159 to improve the accuracy of calculations or the
number 50 to 100 to process the test results of another class.
Understandability:-
 When a numeric value appears in a program, its use is not always clear, especially when the
same value means different things in different places.
 A constant is defined as follows:

# define symbolic_name value of constant

Eg: 1) #define pi 3.1415


2) #define pass_mark 50
3) # define PASS_MARK 50

Statement Validity Remarks


#define X=2.5 Invalid ‘=’ sign is not allowed
# define MAX 10 Invalid No white space between # define
# define N 25; Invalid No semicolon at the end
# define N 5, M 10 Invalid A statement can define only one
statement
# define Array 11 Invalid Define should be in lowercase letters
Rules to be followed:-
 Symbolic names have the same form as variables name
 No blank space is permitted between the sign “#” and the word define is permitted.
 “#” must be the first character in the line.

- 19 –
 A blank space is required between the # define and symbolic name and between the symbolic
name and the constant.
 # define statements must not end with a semicolon.
 After the definition the symbolic name should be assigned any other value within the program by
using an assignment statement.
 Symbolic names are not declared for data types. This data types depends on the type of constant.
 # define statements may appear anywhere in the program but before it is referenced in the
program.
Declaring a Variable as constant:-
 Variables can be declared as constant using the Const qualifier at the time of initialization.
 Example:- Const int class_size = 40;
Declaring a Variable as Volatile:-
 ANSI Standard defines another qualifier Volatile that could be used to tell explicity the compiler
that a variable value may be changes at any time by some external sources (from outside the
program)
Example:- Volatile int date;
Operators Of and Expression:-
 C supports a rich set of operators.
 Operators are used in programs to manipulate data and variables.
 They usually form a part of the mathematical of logical expressions.
 C operators are classified into a number of categories.
 Types of Operators:-

Operators Expression
Arithmetic Operators +, -, * , /, %
Relational Operators < , <=, >, >= , = =, !=
Logical Operators &&, ||, !
Assignment Operators (=) (+=, -=, /=, %=)
Increment and Decrement Operators ++, - -
Conditional Operators ?:
Bitwise Operators &, |, ^, <<, >>
Special IOperators

 The operator are the special characters which perform some operation on operand where the
operands can be variable, expression.

- 20 –
The operators are classified as follows .
1. Unary-requires only one operand.
2. Binary-requires two operand.
3. Ternary-requires three operand.
4. Prefixed-operator is indicated before the operand.
5. Post fixed-operator is indicated after the operand.
Unary:-
There is no significant effect of using unary.
Operators Meaning

+ Unary plus

- Unary minus

Binary:-
It requires two operands the operator is embedded between two operands.
Arithmetic Operators:-
 Arithmetic operators are used to perform basic operations such as addition, subtraction,
multiplication and division.. The basic operators provided by c++ are:

Operator Meaning
+ Addition
- Subtraction
* Multiplication
/ Division
% Modulo division
 Arithmetic operations can be classified in to three categories such as
 Integer arithmetic
 Real arithmetic
 Mixed-mode arithmetic
Integer Arithmetic:-
 When both the operands in a single arithmetic expression are integers, the expression is called an
integer expression, and the operation is called integer arithmetic.
 During modulo division the sign of the result is always the sign of the first operand.
That is
-14 % 3 = -2
-14 % -3 = -2
14 % -3 = 2

- 21 –
Real Arithmetic:-
 An arithmetic operation involving only real operands is called real arithmetic.
 If x and y are floats then we will have:
1) x = 6.0 / 7.0 = 0.857143
2) y = 1.0 / 3.0 = 0.333333
 The operator % cannot be used with real operands.

Mixed-mode Arithmetic:-
 When one of the operands is real and the other is integer, the expression is called a Mixed-mode
arithmetic expression and its result is always a real number.
Eg: int a = 2;
float x = 10.t,y;
y = a+ x // Mixed- mode arithmetic operation.
Relational Operators:-
 Relational operators are those which are used to compare two quantities and take a decision
depending on their relation.
 Relational expression are used in decision statements such as if and while to decide the course of
action of running program.
 Comparisons can be done with the help of relational operators.
 The expression containing a relational operator is termed as a relational expression.
 The value of a relational expression is either one or zero.
Example:-
a < b containing relational operator is termed as relational expression.
Operator Meaning
< Less than
> Greater than
<= Less than or equal to
>= Greater or equal to
= Equal to
!= Not equal to

Syntax:- Ae -1 relational operators Ae-2


 Where Ae-1 and Ae-2 are arithmetic expressions, which may be simple constants, variables or
combination of them.
 An expression such as a<b (or) 1< 20 containing a relational operators is termed as relational
expression.

- 22 –
 The value of relational expression is either one or zero.
 One if the specified relation is true.
 Zero if the relation is false.
Relational Operators Complement:-
 Among the Six relational operators, each one is a complement of another operators

> Complement <=


< Complement >=
== Complement !=
Logical Operators:-
 Logical operator is used to compare two relational expression.
 The combination of relational expression and logical operator is called logical expression
 C has the following three logical operators.

Operator Meaning
&& Logical AND
|| Logical OR
! Logical NOT

Example:- a >b && b < c


 Logical operators are used to combine two or more relational expressions.
 The resulting expression is termed as logical expression or a compound relational expression,

Op1 Op2 Op-1 && op-2 Op-1 | | Op-2


0 0 0 0
0 1 0 1
1 0 0 1
1 1 1 1
Assignment operator:-
 Assignment operators are used to assign the result of an expression to variable.
 The statement used for the purpose is called the assignment statement.
 The assignment operator is defined by “=” symbol.
 Syntax:- Variable_name
Variable_name==expression;
expression;

- 23 –
 The usual assignment operator is ‘=’.In addition, C has a set of ‘shorthand’ assignment operators
of the form, v op = exp;
Eg:1.x += y+1;
This is same as the statement
x =x + (y+1);
Shorthand Assignment Operators:-
 C has a set of “shorthand” assignment operators.
 Syntax:- V op = exp;
is equivalent to V =V op (exp);
 Where,
 V is a valid variables name
 exp is an expression
 Op is a C binary arithmetic operations.

Statement with simple assignment operator Statement with shorthand


operator
A = a+1 A+ =1
A = a-1 A- =1
A= a* 4 A* =4
A=a/4 a/=4
A=a%4 A%=4
Advantages of shorthand assignment operators:-
 What appear on the left-hand side need not be repeated and therefore it becomes easier to write.
 The statement is more concise and easier to read.
 The statement is more efficient.
Increment And Decrement Operators
 C has two very useful operators that are not generally found in other languages.
 These are the increment and decrement operator: ++ and - -
 The increment operator (++) increases the value of the variable.
 The decrement operator (--) decreases the value of the variable
 It takes the following form:
Eg:-
++ m; or m++
--m; or m - -

Operator Meaning
++ Increment
- 24 –
-- decrement

 Syntax:-
Operand
Operand++
++(or)
(or)++++Operand
Operand
Operand - - (or) - - Operand
Operand - - (or) - - Operand
Prefix Operator:-
 A prefix operator first adds or subtract 1 to the operand and then the result is assigned to the
variable on left
 Example:-
o ++ m;
o - - m;

Postfix Operator:-
 A postfix operator first assigns the value to the variables on left and then increments or
decrements the operands.
 Example:-
o m ++;
o m - -;

Rules for ++ and - - Operators:-


 Increment and decrement operators are unary operators and they require variable as their
operands.
 When postfix ++ or - - is used with a variable in an expression, the expression is evaluated first
using the original value of the variable and then the variable is incremented or decremented by
one.
 When prefix + + or ( - -) is used in an expression, the variable is incremented or decremented
first and then the expression is evaluated using the new value of the variable.
 The precedence and associatively of + + and - - operators are the same as those of unary + and
unary -
Conditional Operator:- (ternary Operator):-
 A ternary operator pair “?:” is available in C to construct conditional expression of the form:
exp1 ? exp2 : exp3;
 Where exp1, exp2 and exp3 are expression.
 Here exp1 is evaluated first. If it is true then the expression exp2 is evaluated and becomes the
value of the expression.
 If exp1 is false then exp3 is evaluated and its value becomes the value of the expression.
Eg:1) if(a>b)
x = a;

- 25 –
else
x = b;
Expression 1 false means expression 2 or expression 3 will execute.
Bitwise Operators:-
 The bitwise operator manipulation can be carried out by the bitwise logical operators which
performs the two operator independently between two bit pattern of variables.
 Bitwise operators not applied for float and double data type.
 These operators are used for testing the bits, or shifting them right or left

Operator Meaning
& Bitwise AND
| Bitwise OR
<< Shift left
>> Shift right
^ Bitwise exclusive OR

Bitwise AND (&):-


 syntax:-
Operand 1 & Operand 2

Example:-
a= 4, b= 5
Binary Equivalent of a is 0 1 0 0
Binary Equivalent of b is 0 1 0 1
---------
Output a & b 0100
----------
Bitwise OR ( | ):-
 syntax:-
Operand 1 | Operand 2

Example:-
a= 4, b= 5
Binary Equivalent of a is 0 1 0 0
Binary Equivalent of b is 0 1 0 1
---------
Output a | b 0101
-----------

Bitwise Exclusive OR (^ ):-


 syntax:-
Operand 1 ^ Operand -226 –
Example:-
a= 4, b= 5
Binary Equivalent of a is 0 1 0 0
Binary Equivalent of b is 0 1 0 1
---------
Output a ^ b 0001
-----------
Bitwise Left shift (<< ):-
 It is used to shift the given number of bits of an integer towards left.
 The vacant positions on the right of the integer would be filled with zeros.
 syntax:-

Operand < < n;

 Here n specifies number of bits shifted towards left.


Bitwise Right shift (<< ):-
 It is used to shift the given number of bits of an integer towards right.
 The vacant positions on the left of the integer would be filled with zeros.
 syntax:-
Operand >> n;

 Here n specifies number of bits shifted towards left.


Bitwise Complement ( ~) :-
 It is used to invert the bits of an integer. It replaces all zero’s by one’s and one’s by zero’s
 Example:-
a= 4;
a0000 0000 0000 0100
a 1 1 1 1 1111 1111 1011
Special Operators:-
C supports some special operators such as

Special Operators Operators


Comma operator ,
Size of operator ()
Pointer operators and (& and *)
Member selection operators (. and ->)
- 27 –
The comma Operators ( ,) :-
 The comma operator can be used to link the related expression together.
 Example:-
o Value = ( x = 10 , y n < = ; n ++, m++)
The sizeof ( ) Operator :-
 It is used to find the size of a variable ( or) the size of a data type in terms of the number of bytes.
 It is used to find the size of user-defined data type
 syntax:-

Sizeof(data-type) (or) sizeof(variable)

 The sizeof operators is normally used to determine the lengths or array and structures when their
sizes are not known to the programmer.
 Example:-
m = sizeof (sum);
n = sizeof(longint);
k = sizeof(235L);
Expressions:-
 The combination of operators and operands is said to be an expression.
Arithmetic Expressions
 An arithmetic expression is a combination of variables, constants, and operators arranged as per
the syntax of the language.
Eg 1) a = x + y;
 The following tables gives some examples for C expression and their equivalent algebraic
expression.

Special Operators Operators


aXb-c A*b-c
(m+n)(x+y) (m+n)*(x+Y)
(ab/c) A*b/c
3x2 +2X+1 3*x*x*+2*x+1
(x/y)+c x/y+c
Evaluation Of Expressions
 Expressions are evaluated using an assignment statement of the form.

- 28 –
 syntax:-

Variable
Variable==expression;
expression;

Eg:1) x = a * b – c;
2) y = b / c * a;
 When the statement is encountered the expression is evaluated first and the results then replace
the previous values of the variables on the left hand side.
 All the variables used in the expression must be assigned values before evaluation attempted.
Precedence Of Arithmetic Operators:-
 An arithmetic expression without parenthesis will be evaluated from left to right using the rule of
precedence of operators.
 There are two distinct priority levels of arithmetic.
 High priority  * , /, %

 Low priority  +, -
 The basic evaluation procedure includes two left to right passes through the expression.
 During first pass the high priority operators are applied as they are encountered.
 During the second pass, low priority operators are applied.
 Examples:-
 x= a-b/3+c*2-1
 When a=9, b=12, and e=3 the statement becomes, x=z-12/3+3*2-1
 First Step:-
 Step : 1  X = 9 – 4 + 3 * 2 – 1
 Step : 2  X = 9 – 4 + 6 -1
 Second Pass:-
 Step: 3  x = 5 + 6 -1
 Step : 4  X = 11 – 1
 Step : 5  X = 10
 The number inside parentheses refers to step number.
 The order of evaluation can be changed by introducing parentheses into an expression.
Rules for evaluation:-
 First parenthesized sub expressions from left to right are evaluated.
 If parentheses are nested, the evaluation begins with the innermost sub expression.
 The precedence rule is applied when two or more operators of the same precedence level appear
in a sub expression.
 Arithmetic expressions are evaluated from left to right using the rules of precedence.
 When parentheses are used the expressions with in parentheses assume highest priority.

- 29 –
Type Conversion In Expressions:-
 There are two types of type conversion used in C. they are,
 Implicit type conversion.
 Explicit type conversion.
Implicit type conversion:-
Automatic Type Conversion:-
 C permits the mixing of constants and variables of different types in an expression.
 C automatically converts any intermediate values to the proper type.
 This automatic conversion is known as implicit type conversion.
 If the operands are of different types, the lower type is automatically converted to the higher type
before the operation proceeds.
 The result of the expression will be in higher type mode
 At the time of assignment of the value of an expression (or0 source variable to a target variable
the value of the expression on the right hand side of an assignment statement gets converted in to
the type of the variable collecting it.

Long Double
Conversion
Hierarchy Double
Float
Unsigned Long int
Long int
Unsigned int
int
Short Char

Rules:-
 All short and char are automatically converted into int.
 If one of the operands is long double the other will be converted to long double and the result
will be long double.
 If one of the operands is double the other will be converted to double and result will be double
 If one of the operands is float the other will be converted to float and the result will be float.
 If one of the operands is long int, the other will be converted to unsigned long int and the result
will be unsigned long int.
- 30 –
 If one of the operand is long and the other is unsigned then
 If Unsigned int can be converted to long int, the unsigned int operand will be converted as such
as the result will be long int.
 Else both operands will be converted to unsigned long int and the result will be long int.
 If one of the operands is long int then the other will be converted to long int and the result will be
long int.
 Else if one of the operands is unsigned int, the other will b e converted to unsigned int and the
result will be unsigned int.
 The final result of an expression is converted to the type of the variables on the left of the
assignment sign before assigning the value to it.
Explicit Conversion:-
Casting a Value
 The process of converting the type explicitly by specifying the type to convert as (float x-y) is
known as explicit conversion or casting value.
 C performs type conversion automatically.
 However, there are instances when we want to force a type conversion in a way that is different
from the automatic conversion.
 Eg: 1) ratio = female_number / male_number
 Since female_number and male_number are declared as integers the ratio would represent a
wrong figure.
 Hence it should be converted to float. ratio = (float) female_number / male_number
The general form of a cast is:
(Type-name)expression

Operator Precedence and associatively


 Each operator in c has precedence associated with it.
 This precedence is used to determine how an expression involving more than one operator is
evaluated.
 There are distinct levels of precedence and an operator may belong to one of these levels.
 The operators at the higher level of precedence are evaluated first.
 The operators of the with equal precedence are evaluated either from left to right to from” right
to left” depending on the level.
 This is known as the associability property of an operator.
Rules for precedence and associativity:-
 Precedence rules decides the order in which different operators are applied.
 Associativity rule decides the order in which multiple occurrences of the same level operator are
applied.
 Example:-
- 31 –
 Consider the following conditional statement:-
 if(x = =10 + 15 && y < 10)
 This will be executed in the following order for x= 20 and y = 5
 The precedence rules say that the addition operator has a higher priority than the logical operator
( & &) and the relational operators ( = = and < ). Therefore, the addition of 10 and 15 is
executed first
 This is equivalent to if (x = = 25 & & y < 10)
 The next step is to determine whether X is equal to 25 and y is less than 10.
 X = = 25 is FALSE (0)
 y < 10 is TRUE (1)
 Since the operator < enjoys a higher priority compared to = = , y < 10 is tested first and then x =
= 25 is tested.
 Finally if (False & & True) is evaluated and the result is false(0).

Operators Description Precedence Associativity


() Function 1 Left to Right
II Array

Unary + Unary addition


Unary – Unary subtraction
++ Increment 2
- Decrement Right to Left
~ Bitwise Complement(ones
* complement)
& Pointer reference indirection
Size of (type) Address operator
Size of operator Type / Forcible
casting
* Multiplication 3 Left to Right
/ Division
% Remainder

+ Addition 4 Left to Right


- Subtraction
<< Left Shift 5 Left to Right
>> Right Shift

< Less than 6 Left to Right


<= Less than or equal to

- 32 –
> Greater than
>= Greater than or equal to
== Equal to 7 Left Right
!= Not Equal to

& Bitwise AND 8 Left to Right

^ Bitwise XOR 9 Left to Right

| Bitwise OR 10 Left to Right

&& Logical AND 11 Left to Right

|| Logical Or 12 Left to Right

?: Conditional operator 13 Right to Left

+= 14 Right to left
-=
*= Shorthand arithmetic assignment
/= operators
%=
, Comma Operator 15 Left to Right

Mathematical Functions:-
 Mathematical functions such as sqrt, cos, log etc., are the most frequently used ones.
 To use the mathematical functions in a C program, we should include the line
#include<math.h>
in the beginning of the program.

- 33 –
Function Meaning
Trigonometirc
Sin (x) Sine of x
Cos (x) Cosine of x
Tan (x) Tangent of x
acos(x) Arc cosine of x
asin(x) Arc sine of x
atan(x) Arc tangent of x
Hyperbolic
Sinh (x) Hyperbolic sine of x
Cosh(x) Hyperbolic cosine of x
Tanh (s) Hyperbolic tangent of x

Other Functions
root 1= -b_sqrt(discriminant)/2.0*a;
Ceil (x) root2=-b-sqrt(discriminant)/2.0*a;
X rounded up to the nearest int
printf(“\n The roots are :\nRoot1:%f\
Exp (x) E to power of ex nRoot2:%f”,root1,roo2);
Fabs(x) Absolute value of x }
}
Floor(x) X rounded down to the nearest integer
Fmod(x,y) Remainder of x/y Output:-
Enter the values for a, b, and c
Log(x) Natural log of X, X > 0 2 4 -16
# include <stdio.h> The
Log10 (x)
#include<math.h>
Base 10 log x, X > 0 root roots are :
1= -b_sqrt(discriminant)/2.0*a;
Root1:2.00
root2=-b-sqrt(discriminant)/2.0*a;
Pow (x,y)
void main( ) X to the power of Xy Root2:4.00
{ printf(“\n The roots are :\nRoot1:%f\
Sqrt(x) Square root of x X > = 0 nRoot2:%f”,root1,roo2);
float a,b,c discriminant, root1, rott2;
printf(“enter the values for a,b, and c”); }
scanf(“%f%f%f”, &a,&b,&c); }
discriminant=b*b-4*a*c;
if(discriminant<0) Output:-
{ Enter the values for a, b, and c
printf(“\n The roots are imaginary”); 2 4 -16
} The roots are :
else Root1:2.00
{ Root2:4.00

Managing Input And Output Operations:-


 All input/output operations are carried out through functions called as printf and scanf.
 There exist several functions that have become standard for input and output operations in C.
 These functions are collectively known as standard i/o library.
 Each program that uses standard I/O function must contain the statement.
#include<stdio.h>
- 34 –
 The file name stdio.h is an abbreviation of standard input-output header file.
Reading A Character :-
 The simplest of all the input/output operations is reading a character from the standard input unit
and writing it to the standard output unit.
 Reading a single character can be done by using the function getchar.
 Syntax:-
Variable_name
Variable_name==getchar(
getchar(););

 Where variable_name is a valid C name that has been declared as char type.
 When the statement is encountered the computer waits until a key is pressed and then assigns this
character as value to getchar function.
 Since getchar is used on the right side of the assignment statement, the character value of getchar
( ) is in turn assigned to the variable name on the left.
 The getchar takes the following form:
Example: char name;
Name =getchar();
 C support many other similar functions. These functions are contained in the file c type.h
 The getchar function may be called successively to read the characters contained in a line of text
 Example:-
………………………
……………………….
Char character;
Character = “ “;
While(character ! = :\n”)
{
Charcter = getchar( );
}

…………………………..

- 35 –
Program
Program OUTPUT
/*Reading OUTPUT
/*Readingaacharacter
characterfromfromterminal*/
terminal*/
Would
#include<stdio.h>
#include<stdio.h> Wouldyou
youlike
liketotoknow
knowmy
myname?
name?
main()
main() Type
{{ TypeYYfor
foryes
yesand
andNNfor
forno:Y
no:Y
My
char
charans;
ans; Myname
nameisisIndia
India
printf(“Would
printf(“Wouldyou youlike
liketotoknow
knowmy myname?
name?\ \ Would
n”); Wouldyou
youlike
liketotoknow
knowmymyname?
name?
n”);
Type
printf(“Type
printf(“TypeYYfor foryes
yesand
andNNfor forno”);
no”); TypeYYfor
foryes
yesandandNNfor
forno:n
no:n
ans=getchar();
ans=getchar(); You
if(ans Youare
aregood
goodfor
fornothing.
nothing.
if(ans==’Y’
==’Y’|| ||ans
ans===’y’)
=’y’)
printf(“\n\n
printf(“\n\n My nameisisIndia
My name India\n”);
\n”);
else
else
printf(“\n\n
printf(“\n\nYou
Youare aregood
goodforfornothing
nothing\n”);
\n”);
}}

Function Test
Isalnum (c) Is C an alphanumeric character?
Isalpha (c) Is C an alphabetic character?
Isdigit (c) Is C digit?
Islower (c) Is C an lower case letter?
Isupper (c) Is C an an upper case letter?
Isprint (c) Is C Printable character?
Ispunt (c ) IS C a punctuation mark?

Writing A Character:-
 Like getchar, there is an analogous function putchar for writing characters one at a time
to the terminal. It takes the form as shown below:
 Syntax:- Putchar(Variable_name);
Putchar(Variable_name);
- 36 –
 Where variable_name is a type char variable containing a character.
 This statement displays the character contined in the variable name at the terminal
Eg: 1) answer=’y’;
putchar(answer);
 The above statement will disp;ay the character y on to the screen
 The statement putchar(‘\n’); would cause the cursor on the screen to move to the
beginning of the next line.

/*A
/*Aprogram
programtotoread readaacharacter
characterfrom
fromkeyboard
keyboardand
and OUTPUT
then
thenprints
printsititininreverse
reversecase*/
case*/ OUTPUT
/*This
/*Thisprogram
programuses usesthree
threenew
new Enter
EnterAn
Analphabet
alphabet
functions:islower,toupper,and
functions:islower,toupper,andtolower.tolower. aa
#include<stdio.h>
#include<stdio.h>
#include<ctype.h> AA
#include<ctype.h>
main()
main() Enter
{{ EnterAn
Analphabet
alphabet
char
charalphabet;
alphabet; QQ
printf(“Enter
printf(“Enteran analphabet”);
alphabet”); qq
putchar(‘\n’);
putchar(‘\n’);
alphabet
alphabet==ghetchar();
ghetchar(); Enter
EnterAn
Analphabet
alphabet
if(islower(alphabet))
if(islower(alphabet)) zz
putchar(toupper(alphabet));
putchar(toupper(alphabet));
else ZZ
else
putchar(tolower(alphabet));
putchar(tolower(alphabet));
}}
}}

Formatted Input:-
 Formatted input refers to an input data that has been arranged in a particular format.
 The formatted data can be read with the help of scanf function.
 The general form of scanf is
Syntax:-
scanf(“control
scanf(“controlstring”,arg1,arg2….argn);
string”,arg1,arg2….argn);
 The control string specifies the field format in which the data is to be entered and the arguments
arg1,arg2...argn specifies the address of locations where the data are stored. Control strings and
arguments are separated by commas.
 Control string contains field specification which direct the interpretation of input data.
It may include

- 37 –
 Field(or format)specifications, consisting of conversion character %, a data type
character, and an optional number, specifying the field width.
 Blanks, tabs, or newlines.
Scanf Format Codes
Inputting integer Numbers:-
 The field specification for reading an integer number is :-
 The syntax:- %
%wwsd
sd
 The percentage sign (%) indicates a conversion specification follows.
 W is an integer number that specifies the field width of the number to be read
 D known as data type character, indicates that the number to be read is in integer mode
 Example:-
 Scanf (“%2d%5d”, &num1,&num2);
 Data line(input): 50 31426
 Here the value to is assigned to num1 and 31426 to num2.
 Suppose the input data is 31426 50. In this case the variable num1 will takes 31 and num will
takes 426.
 The value 50 is unread will be assigned to the first variable in the next scanf call.
 To read long integers the data type character d should preceded by 1

Inputting Real Numbers:-


 Scanf reads real numbers using the simple specification %f for both the notations, namely,
decimal point notation and exponential notation.
 Field width is not necessary for real numbers.
 Example:-
 Scanf(“%f%f%f, &x,&y,&z); with input data
 472.34 43.21E-1 678
 Will assign the value 472.34 to x,4.21E-1 to y and 678.0 to z.
 Input field specifications may be separated by any arbitrary blank spaces.
 If the number to re read is of double type, then the specification should be % if instead of simple
%f.
 A number may be skipped using % *f specification.
Inputting Character Strings:-
 The scanf function can be used to read both a single character and a string of characters.
 Field width is not necessary for real numbers.
 The syntax:-
%ws
%wsor
or%wc
%wc
 Some version of scanf support the following conversion specification for string.
- 38 –
 Example:-
 Scanf(“%f%f%f, &x,&y,&z); with input data
 472.34 43.21E-1 678
 .The specification %[characters] means that only the characters specified within the breckets are
permissible in the input string.
 The specification %[^characters] will not permit the characters specified after the circumfles(^) in
the input strings.
Reading mixed data types:-
 One scanf statement can input a data line containing mixed mode data.
 In this case the input data items should match the control specifications in order and type.
 Example:-
 Scanf (“%%f%s”&a,&b,&c)
 Input data: 15 10.75 coffee
Commonly used Scanf format codes:-

Rules for Scanf:-


 Each variable to be read must have a field specification.
 For each field specification, there must be a variable address of proper type.
 Any non-white space character used in the format string must have a matching character in the
user input.
 Never end the format string with whitespace. It is fatal error.
 The scanf reads until.
o A whitespace character is found in a numberic specification or
o The maximum number of characters have been read or
o An error is detected, or
o The end of file is reached

Formatted Output:-

- 39 –
 The printf statement provides certain features that can be effectively exploited to control the
alignment and spacing of print-outs on the terminals.
 The general form of printf statement is
printf(“control string”,arg1, arg2…argn);
Control string consists of three types of items:
1. Characters that will be printed on the screen as they appear.
2. Format specifications that define the output format for display of each item.
3. Escape sequence characters such as \n, \t and \b
 The control string indicates how many arguments follow and what their types are
 The arguments arg1, arg2……arg3 are the variables whose values are formatted and printed
according to the specification of the control string.
 The arguments should match in number, order and type with format specification.
Output of Integer numbers:-
 The format specification for printing an integer number is
 The syntax:-
%w
%w
 W is an integer dd
number that specifies the field width for the output.

 D known as data type character indicates that the number to be read is in integer mode.

 However, if a number is greater than the specified width, it will be printed in full, overriding the
minimum specification.
 The number is written right-justified in the given field width. Leading blanks will appear as
necessary.
 Example:-

 The following example illustrate the output of the number 9876 under different formats:-

Format: Output
printf (“%d”, 9876) 9 8 7 6

printf (“%6d”, 9876) 9 8 7 6

printf (“%-6d”, 9876) 9 8 7 6

printf (“%06d”, 9876) 0 0 9 8 7 6


Output of real numbers:-
 The output of a real number may be displayed in decimal notation using the following format
specification

- 40 –
 The syntax:-
%w.pf
%w.pf
 The integer w indicates the minimum number of positions that are to be used for the display of
the value

 The integer p indicates the number of digits to be displayed after the decimal point (precision).

 The value p indicates the number of digits to be displayed after the decimal point (precision).

 The value, when displayed is rounded to p decimal places and printed right justified in the field of
w columns.

 Leading blanks and trailing zeros will appear as necessary.

 The default precision is 6 decimal places.

 Real numbers can also display in exponential notation by using the following specification.

 %w.pe
 Example:-

 Output of the number y = 98.7654

Format: Output
Printf (“%7.4f”, y) 9 8 . 7 6 5 4

Printf (“%7./2f”,y) 9 8 . 7 7

Printf %-7.2f”) 9 8 . 7 7

Printf (“%06d”, 9876) 9 8 . 7 6 5 4

 Some system also supports a special field specification character that lets the user define field
size at run time. This takes the following form:
 printf(“%*.*f”, width, precision, number);
 Example
 printf(“%*.*f”,7,2,number); is equivalent to
 printf(“%7.2f”, number);

Printing of a single character:-


 A single character can be displayed in a desired position using the format;
 The syntax:-
%we
%we
 The character will be displayed right-justified in the field of W column.

- 41 –
 The default value for w is 1

Printing of strings:-
 The format specification for outputting strings is similar to that of real numbers. It is of the form
 The syntax:-
%w.ps
%w.ps
 W specifies the field width for display

 p instructs that only the first p character of string are to be displayed

 The display is right-justified.

Format: Output
printf(“%s”, BSCCS) B S C C S

Printf(“%10s”,BSCCS) B S C C S

Printf(“%10.4s”.BSCCS) B S C C S

Mixed Data Output:-


 It is permitted to mix data types in one printf statement.
 Example:-
 Printf (“%d %f %f %c”,a,b,c,d);
 Inputdata: 10 10.5 num c
 Printf uses its control string to decide how many variables to be printed and what their types are.
 Therefore, the format specifications should match the Variables in number, order and type.
Enhancing the readability of output:-
 Computer outputs are used as information for analyzing certain relationship between variables
and for making decision.
 Therefore the correctness and clarity of outputs are of at most importance.
 While correctness depends on the solution procedure, the clarity depends on the way the output is
presented.
 The following steps are used to improve the clarity, readability and understandability of outputs.
 They are,
 Provide enough blank space between two numbers.
 Introduce appropriate headings and variable names in the output.
 Print special messages whenever a peculiar condition occurs in the output
 Introduce blank lines between the important sections of the output.
Commonly used printf format codes
- 42 –
Code Characters Meaning
%c Single character
%d (%i) Signed integer
%e(%E) Exponential format
%f Signed decimal
%g(%G) Use %f or %e required
%o Unsigned octal value
%p Address stored in pointer
%s Sequence of characters
%u Unsigned decimal
%X(%x) Unsigned hex value
Commonly used Output Format Flags
Flag Meaning
- Output is left-justified within the field, Remaining field
will be blank
+ + or – will precede the signed numeric item
0 Causes leading zeros to appear
#(with 0 x) Causes octal and hex items to be preceded by ) and Ox,
repectively
# (with e, f or g) Causes a decimal point to be present in all floating point
numbers, even if it is whole number. Also prevents the
truncation of trailing zeros in g-type conversion.

*************Unit – I Completed******************

- 43 –

You might also like