Unit - I Overview of C
Unit - I Overview of C
AATTUKARAMPATTI, DHARMAPURI-9
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.
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 &ersand
. 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
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
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.,
Constant Meaning
‘\a’ Audible alert (bell)
‘\b’ Backspace
‘\ ‘ Double quote
‘\ \ ‘ 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.
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.
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;
Variable_name=constant
Variable_name=constant
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;
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);
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.
- 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:-
- 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:-
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:
- 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
- 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
Operator Meaning
&& Logical AND
|| Logical OR
! Logical NOT
- 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.
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 - -;
- 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
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
-----------
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.
- 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
- 32 –
> Greater than
>= Greater than or equal to
== Equal to 7 Left Right
!= Not Equal to
+= 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
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
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
- 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.
Real numbers can also display in exponential notation by using the following specification.
%w.pe
Example:-
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
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);
- 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
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
*************Unit – I Completed******************
- 43 –