You are on page 1of 56

0 # 55

C FUNDAMENTALS

Prepared by S.Gunasekaran B.E…, 7/1/2011
Prepared by
S.Gunasekaran B.E…,
7/1/2011

This unit is explained about the fundamentals of C language such as C character set-Identifiers and keywords-Data types-Constants-Variables-Declaration-Expressions-Statements-Symbolic constants- Operators-Data input and output-control statements-Unconditional statements, nested loop.

1 # 55

HISTORY OF „C‟ LANGUAGE

„C‟

is

one

of the most popular programming languages.

It was developed by Dennis

Ritchie

at AT & T‟s Bell Laboratories

at USA in the early 1970s. It is an upgraded version of

two earlier languages, called Basic Combined Programming Language (BCPL) and B, which

were also developed at Bell laboratories. The following table illustrates the history of “C” language. Language
were
also
developed
at
Bell laboratories.
The
following table
illustrates
the
history of “C”
language.
Language
Year
Founder
1960
ALGOL
1967
BCPL
1970
B
1972
C
1978
K&RC
1989
ANSI C
1990
International group
Martin Richards
Ken Thompson
Dennis Ritche
Kernighan and Ritche
ANSI Committee
ISO Committee
ANSI/ISO C
„C‟ IS A MIDDLE LEVEL LANGUAGE
a)
Low level language:
Low level language
is
in terms
of 0‟s
and
1‟s (bits).
„C‟
language has the certain features of “Low-level Language”, that allow the
programmer to carry out operations on bits that are normally available in Assembly
language or Machine language.
b)
High level language: High level language
looks like normal English, whose
instruction set is more compatible with human languages. These languages are easily
understandable and designed to provide a better program efficiency.
These are
machine independent. Examples are FORTAN, PASCAL, COBOL, BASIC, C++
…etc.
  • c) Middle level language: C lies in between these two categories it is neither a low level language nor a high level language, it is a middle level language. i.e., performs the task of Low level language as well as high level language. We can write the code for Operating System, Application Programs, and Assembly language programs in „C‟ language. Unix Operating System is written in „C‟ language.

2 # 55

STRUCTURE OF A „C „PROGRAM

There are some sections in „C‟ program given below:

  • i) Documentation Section

It consists of set of comment lines used to specify the name of program, author and
It consists
of set of comment lines used
to specify the name of program,
author and other details etc.,
Comments:
It
is
helpful
in
identifying
the
program features and
underlying logic of the program.
The line
begins
with „/*‟
and ending with „*/‟.
These are not executable, the compiler is ignored anything between /* and */.The
new style is //
ii)
Preprocessor Section
Definition section
It
is
used
to
link system library files, for defining the macros and
for defining the conditional inclusion.
Eg:
#include<stdio.h>, #define A 10, #if def, #endif… etc.
iii)
Global Declaration Section
The
variables that are
used
in
more
than one function throughout the
program are called global variables and declared outside of all the function i.e.,
before main(). It has two parts:
Declaration part
to declare all the variables used in the program
Execution part
Contains
at
least
one
valid
„C‟ statement.
It
begins with
opening braces „{„and
ends with closing braces
„}‟.
The
closing brace of main function is the logical end of the
program.

iv)

Sub Program Section

  • It contains the function definitions included.

The following tables are explained the programming structure.

3 # 55

STRUCTURE SAMPLE documentation section preprocessor section definition section global declaration section main() { /* finding area
STRUCTURE
SAMPLE
documentation section
preprocessor section
definition section
global declaration section
main()
{
/* finding area of circle */
#include<stdio.h>
#define PI 3.14
main()
{
int r=5;
declaration part;
execution part;
float area;
area = PI * r * r;
}
sub program section
{
printf(“Area of circle: %f”, area);
}
OUTPUT:
Body of the subprogram;
Area of circle: 78.5
}
CHARACTER SET
Character set is
the
fundamental raw material of any language and
they are
used to
represent information. „C‟ language consists of two character set namely,
a)
Source character set
b)
Execution character set
Source Character Set
These are useful to construct the statements in the source program Alphabets  Upper

case A……Z, Lower case a…z ,Digits 0,1……9 ,Special character , + - * / $ _ { [ ] <

> \ |

~ @ # % ^ & : ; ? „…

Execution Character Set

These are employed at the time of execution. This set of characters are also called as non graphic characters because, these characters are invisible and cannot be printed or displayed directly. This will be effect when program is being executed. Execution characters set are always represented by a backslash (\) followed by a character. We simply call it as escape sequences.

4 # 55

CHARACTER ESCAPE SEQUENCE Bell (alert) Backspace Horizontal tab Vertical tab Newline (Line feed) Form feed Carriage
CHARACTER
ESCAPE SEQUENCE
Bell (alert)
Backspace
Horizontal tab
Vertical tab
Newline (Line feed)
Form feed
Carriage return
Quotation Mark
Apostrophe
Question Mark
Back Slash
Null
\a
\b
\t
\v
\n
\f
\r
\”
\‟
\?
\\
\0 (indicate end of string)
C TOKENS
The
individual units
of
„C‟
programming language
are
called
C
tokens.
It
is
referred as individual text and punctuation in a passage of text and has the following types
C Tokens
Special
Identifiers
Keywords
Constants
Strings
Operators
Symbols
Total,
int,
39,
“Guna”
+, -, *, /
#, $, %
Age
double,
39.77
“Vikram”

usually

5 # 55

IDENTIFIERS

Identifiers are referring to the names of variable, functions and arrays.

RULE FOR NAMING AN IDENTIFIERS

First character must be an alphabet

Must consist of only letters, digits or underscore

Only first 31 characters are significant

Must not contain white space

The following are valid Salary, aug99_sales, I, index The following are not valid 2001_sales, aug99+sales, my
The following are valid
Salary, aug99_sales, I, index
The following are not valid
2001_sales, aug99+sales, my age, printf
KEYWORDS
There are certain reserved words called keywords that have standard and predefined
meaning in „C‟ language, which can‟t be changed.
All keywords are fixed meanings and these meanings are can‟t be changed
Keywords serve as basic building blocks for program statements
Example:
Auto, double, int, struct, break, else, case, char, float, for………
DATA TYPES
Data type
is
the
type
of the data,
which are going to access within the program.
„C‟
supports different data types. Each data type may have predefined memory requirement and
storage representations in program.

6 # 55

They are four data types:

Primary „C‟ Empty User defined Derived Data Type Char typedef arrays void int enum pointers float
Primary
„C‟
Empty
User defined
Derived
Data Type
Char
typedef
arrays
void
int
enum
pointers
float
structures
double
union
Type Keyword Character char Integer int Floating point float Double double floating point Valueless void signed
Type
Keyword
Character
char
Integer
int
Floating point
float
Double
double
floating point
Valueless
void
signed
unsigned
short
long
The
type
modifiers precede
the
type
name that they modify.

Basic data types:

Several of the basic types can be modified using one or more of these type modifiers:

The basic arithmetic types,

including modifiers, allowed by „C‟ are shown in the following table along with their guaranteed minimum ranges. Most compilers will exceed the minimums for one or more types. Also, if your

computer uses two‟s complement arithmetic (as most do), then the smallest negative value that

can be stored by a signed integer will be one more than the minimums shown. For example, the

range of an int for most computers is 32,768 to 32,767. Whether type char is signed or unsigned is implementation dependent.

7 # 55

Type Byte Minimum Range CHARACTER TYPE char unsigned char signed char INTEGER TYPE Int unsigned int
Type
Byte
Minimum Range
CHARACTER TYPE
char
unsigned char
signed char
INTEGER TYPE
Int
unsigned int
signed int
short int
–127 to 127 or 0 to 255
1
bytes
0 to 255
–127 to 127
2
bytes
–32,767 to 32,767
2
bytes
0 to 65,535
2
bytes
same as int
1
bytes
same as int
unsigned
short
1 bytes
0 to 65,535
int
signed short int
1
bytes
same as short int
long int
signed long int
4
bytes
–2,147,483,647 to 2,147,483,647
4
bytes
same as long int
unsigned
long
4 bytes
0 to 4,294,967,295
int
FLOAT TYPE
float
4
bytes
3.4E-38 to 3.4E+38 (6 digits of precision)
double
8
bytes
1.7E-308
to
1.7E+308
(10
digits
of
precision)
long double
10 bytes
3.4E-4932
to
1.1E+4932
(10
digits
of
precision)
EMPTY DATA TYPE
void
When a type modifier is used by itself, int is assumed. For example, you can specify an unsigned
integer by simply using the keyword unsigned. Thus, these declarations are equivalent.
unsigned int
i; // here, int is specified
unsigned
i; // here, int is implied
VARIABLES
A variable
is
an identifier
that
is
used
to
represent some type of information within a

designated portion of the program.

Example int a,b,c; Here a,b,c is a variable

8 # 55

RULES FOR NAMING THE VARIABLE:

Variable name can be any combination of 1 to 18 alphabets, digits or underscore

First character must be an alphabet

Length of the variable can‟t exceed upto 8 characters long, and some „C‟ compilers can be recognizing upto 31 characters long.

No commas or blank spaces are allowed within a variable name.

 No special symbol, an underscore can be used in a variable name. Syntax: datatype v1,
No special symbol, an underscore can be used in a variable name.
Syntax:
datatype v1, v2, v3,…., vn;
Where
datatype
v1, v2, v3
 is the
type of the data
...
vn
 are the list of variables
Example:
main()
{
int i,j;
//These 3 lines declare 4 variable
char c;
float x;
//rest of program follows
}
USER DEFINED VARIABLES:
a)
Type declaration: „C‟ Language provides a feature to declare a variable of the type
of user defined type declaration, which allows users to define an identifier that would
represents an existing data type and this can be used to declare variables.

Syntax:

typedef datatype identifier;

Where

typedef

user defined type declaration

datatype

existing data type

9 # 55

Eg:

identifier

typedef int marks; marks m1, m2, m3;

refers to the new name given type

to

the data

b)

Enumerated data type: „C‟ language provides another user defined data type is called enumerated data type.

Syntax: enum identifier {value 1, value2, …., value n}; where enum  user defined enumerated data
Syntax:
enum identifier {value 1, value2, …., value n};
where
enum  user defined enumerated data type.
identifier  refers to the new name given to the datatype
value1, value2, …, value n enumeration constants
Eg:
enum day {mon, tue, wed,…,sun};
enum day w_st, w_end;
w_st = mon;
w_end=sun;
CONSTANTS
The items whose values can‟t be changed during the execution of program are called
constants. „C‟ constants can be classified as follows:

10 # 55

Constants

10 # 55 Constants Numeric Character Integer Real Character String INTEGER CONSTANTS An integer constant formed
Numeric Character Integer Real Character String INTEGER CONSTANTS An integer constant formed with the sequence of
Numeric
Character
Integer
Real
Character
String
INTEGER CONSTANTS
An integer constant formed with the sequence of digits. There are three types of integer
constants which are different number system.
Decimal number
Octal number
Hexadecimal
0 to 9
0 to 7
0 to 9, A, B, C, D, E, F
Eg:
marks = 90;
per = 75;
discount = 15;
These are basically three types of integer namely,
Decimal
Octal
Hexadecimal
Eg: 10, 153, -342, 089, etc.
Eg: 037, 0,0567, etc.
Eg: 0x4, 0x8F, 0xBCF etc.

11 # 55

REAL CONSTANTS

It is made up of a sequence of numeric digits with presence of decimal point.

Eg:

weight = 56.8; height = 5.6; speed = 3.11; CHARACTER CONSTANTS The character constant contains is
weight = 56.8;
height = 5.6;
speed = 3.11;
CHARACTER CONSTANTS
The character constant contains is a character with enclosed quotes
Eg:
„p‟
„N‟ „4‟ „+‟
STRING CONSTANTS
A string constant is a sequence of characters enclosed
in double
quotes
(“
”),
the
characters may be letters, numbers, special characters and blank spaces etc. At the end of
string „\0‟ is automatically placed.
Eg:
“String”, “HI”
“39.56”,
“22”
i)
Declaring a variable as constant:
When the value of some of the variables may remain constantly during the
execution of the program,
keyword const.
in
such
a
situation,
this
can
be
done
by
using the
Syntax:
const datatype variable =
Where
const
variable
datatype
constant
 keyword to declare constant
name of the variable
type of the data
constant

Eg:

const int rate = 397;

12 # 55

STRING:

String is a collection of character

Eg: “India”, “Tamilnadu”

OPERATORS:

An operator is a symbol that tells the computer to perform the certain mathematical or logical
An operator is
a
symbol that tells the computer to perform the certain mathematical or
logical manipulations C operators can be classified into a number of categories. They include
Arithmetic operator
Relational operator
Logical operator
Assignment operator
Operators
Increment and decrement operator
Conditional operator
Bitwise operator
Special operator
1. ARITHMETIC OPERATOR
C provides the entire basic arithmetic operator

+ Addition operator

-

Subtraction operator

/

Division operator

% modulo division

Modulo operator can‟t used to floating point data

13 # 55

Example:

a=10, b=5

a+b=15

a-b=5

a/b=2

a%b=2

which is used to
which is
used
to

RELATIONAL OPERATOR

2.

<

less than

>

greater than

Example:

a=10, b=5

a<b false

a>b true

a<=b false

a>=b true

a==b false

a!=b true

3.

They operator are

Relational operator relation take certain decisions

compare two quantities and depending on their

Relational expressions are used in decision statements such as if and while

<= less than or equal to >= greater than or equal to == is equal to != not equal to

LOGICAL OPERATOR

Logical operator which is used to test more than one condition and make decisions

14 # 55

They operator are

&& ->Logical AND ||->Logical OR !->Logical NOT

Example:

if((a<b) && (c>d)) {

printf(“ This is true”); } The variable a must be less than b and, at the
printf(“ This is true”);
}
The variable
a must be less than b and, at the same time, c must be greater than d .if both
condition is true then if block statement execute, either one or false statement not execute
If((a<b)||(c>d))
{
printf(“ This is true”);
}
The variable
a must be less than b and, at the same time, c must be greater than d .if both
condition either one or true or both true then if statement block execute
If(!(a<b))
If a is not small than b or not equal to b then the if block statement
is executed
4. ASSIGNMENT OPERATOR
Assignment operator are used to assign the results of an expression to a variable
= ->assignment operator
Example:
Variable operator = expression
a=10, b=5
a=a+b ->a=15 is equal to a+=b ->a=15

5. INCREMENT AND DECREMENT OPERATOR

The operator ++ add 1 to operand while subtract 1. Increment and decrement statements in for and while loops extensively

15 # 55

Two types

Prefix: A prefix operator first adds 1 or subtract to the operand and then the result is assigned to the variable on left

Example:

Assume a=5;

b=++a;

a=6,b=6

b=--a; a=5,b=5; Postfix: A postfix operator first operator first assigns the value to the variable on
b=--a;
a=5,b=5;
Postfix: A postfix operator first operator first assigns the value to the variable on left and then
increment or decrement the operand
Example:
Assume a=5;
b=a++
b=5,a=6
b=a- -
b=5,a=4
6. CONDITIONAL OPERATOR
Conditional operator also called as ternary operator. This conditional operator is used to
replace if – else logic in some situation
The conditional operators are
Conditional exp? expression1: expression 2;
If the condition exp
expression 2 is execute
is
true
is expression 1
is execute
.if the condition exp
is
false
then

a>b?(ans=10);(ans=25);

is equal to if(a>b) {

ans=10;

}

else

16 # 55

{

ans=25;

}

  • 7. BITWISE OPERATOR

Bitwise operator for manipulation of data at bit level. These operator are used for testing the bits or shifting them right or left .bitwise operator not be applied to float or double

The bitwise operators are

& Bitwise AND | Bitwise OR ^ Bitwise Exclusive OR << Shift left >> Shift right
& Bitwise AND
| Bitwise OR
^ Bitwise Exclusive OR
<< Shift left
>> Shift right
Eg:
24
>> 2 is 6
24
 0001
1000
After shifting right by 2 position,
0000
0110  6
8. SPECIAL OPERATOR
Comma operator:
The comma operator can be
used
to link the related expressions together .the comma
linked list of expressions are evaluated left to
value combined
right and
the value of right most expression is the
Example:
Value=(x=10,y=5,x+y);
Sizeof() operator:

The sizeof is compile time operator and when used with an operand it returns the number of bytes the operand occupies. The operand may be variable, a constant or a data type qualifier

a=sizeof(sum); b=sizeof(long int);

c=sizeof(234);

17 # 55

SPECIAL SYMBOLS:

These are the symbols, which has some syntactic meaning and has got significance. These will not
These
are
the
symbols,
which has
some
syntactic
meaning and has got significance.
These will not specify any operation. In „C‟ language call it as “Delimiters” as given below:
SYMBOLS
NAME
MEANING
#
Hash
Pre-Processor directive
,
comma
Variable delimiters to separate
list of variables
:
Colon
;
Semicolon
Label Delimiters
Statement Delimiters
()
Paranthesis
Used
in
expressions
or
in
functions
{ }
Curly braces
using
for
blocking
„C‟
[]
Square braces
structure
used along with arrays
EXPRESSIONS
An expression consists of a sequence of constants,
identifiers, and operators that the
program evaluates by performing the
operations
indicated.
The
expression's purpose in the
program may be to
both.
obtain the resulting value,
or
to produce
side effects of the evaluation, or
Single constant, a string literal,
or
the
identifier
of an object
or
function
is
in
itself an
expression. Such a simple expression, or a more complex expression enclosed in parentheses, is
called a primary expression.
Every expression has a type.
An expression's type
is
the
type
of the
value that results
when the expression is evaluated.
If the expression yields no value,
it
has
the
type
void. Some

simple examples of expressions are listed below:

Variable = Expression;

Eg:

y = (a/b) +c;

k = ((2 * x * x)/b) c;

18 # 55

OPERATOR PRECEDENCE AND ASSOCIATIVITY

An

expression

may

contain

several

operators.

In

this

case,

the

precedence

of

the

operators determines which part of the expression is treated as the operand of each operator. For example, in keeping with the customary rules of arithmetic, the operators *, /, and % have higher precedence in an expression than the operators + and -. For example, the following expression:

a - b * c

is equivalent to parentheses, thus: a - (b * c). If you intend the operands to
is equivalent to
parentheses, thus:
a
-
(b
*
c). If you intend the operands to be grouped differently, you must use
(a - b) * c
If two
operators in an expression have the same precedence, then their associativity
determines whether they are grouped with operands in order from left to right, or from right to
left. For example, arithmetic operators are associated with operands from left to right, and
assignment operators from right to left, as shown below lists the precedence and associativity of
all the C operators.
OPERATOR GROUPING
EXPRESSION
ASSOCIATIVITY
EFFECTIVE GROUPING
a / b % c
a = b = c
Left to right
Right to left
(a /
b) % c
a = (b = c)
OPERATOR PRECEDENCE AND ASSOCIATIVITY
PRECEDENCE
OPERATORS
ASSOCIATIVITY
1.
Postfix operators :
Left to right
.
(type name){list}
[ ]
( )
->
++
--
2.
Right to left
Unary operators:
++
--
!
~
+
-
*
& sizeof
3.
The cast operator: (type name)
4.
Multiplicative operators: * / %
Right to left
Left to right
5.
Additive operators: + -
Left
to right
6.
Shift operators: << >>
Left
to right

19 # 55

OPERATOR PRECEDENCE AND ASSOCIATIVITY PRECEDENCE OPERATORS ASSOCIATIVITY 7. Relational operators: < <= > >= 8. Equality
OPERATOR PRECEDENCE AND ASSOCIATIVITY
PRECEDENCE
OPERATORS
ASSOCIATIVITY
7.
Relational operators: < <= > >=
8.
Equality operators: == !=
9.
Bitwise
AND: &
10.
Bitwise exclusive OR: ^
11.
Bitwise
OR: |
12.
Logical
AND: &&
13.
Logical
OR: ||
14.
The conditional operator: ? :
15.
Assignment operators:
Left to right
Left to right
Left to right
Left to right
Left to right
Left to right
Left to right
Right to left
Right to left
=
+=
-=
*=
/=
%=
&=
^=
|= <<=
>>=
16.
The comma operator: ,
Left to right
DATA INPUT AND OUTPUT
Standard devices
C
always assumes that input comes
from stdin
or
the
standard
input device
.this
is
usually the keyboard. C assumes that all output goes to stdout or the standard output device
Standard I/O devise in C
I/O DEVICE
C NAME
Screen
Stdout
Keyboard
Stdin
Printer
Stdprn
Serial port
Stdaux
Error messages
Stderr
Disk files
None

20 # 55

SIMPLE INPUT AND OUTPUT STATEMENT

scanf

The

scanf ()

functions is used

to

read

the formatted data items from

the keyboard the

format is user defined data items .it can be read or written as defined by a programmer

The general format

scanf(“control string” ,argument list);

The control string is a specified format code to read from the keyboard and the argument
The
control string is
a
specified
format code
to
read from
the keyboard and
the
argument list is
a
user
defined
variable
list
.usually,
the
argument
list
of
the
user
defined
variables must include the address operator(&) as a prefix to the variable
For example
int x,y;
scanf(“%d%d”,&x,&y);
char c,i;
scanf(“%f%f”,&c,&i);
The complete format code used
below
in
the
scanf() function for the various data variables shown
Code
Meaning
%c
Read a single character
%d
Read a decimal integer
%i
Read a decimal integer
%e
Read a floating point number
%f
Read a floating point number
%h
Read a short integer
%o
Read a octal number
%s
Read a string
%x
Read a hexadecimal number

All the variables used to receive values through scanf() must be passed by their addresses .this

means that all arguments must be pointed

to the variables used as arguments

21 # 55

printf()

The

printf()

function

is

one

of the most important and

useful function

to

display the

formatted output data items on the standard output device normally the video screen

The general form of printf() function is as

printf(“control strings”,argument list);

Where the control strings are user defined format code and the argument list is a set of data items to be displayed in a proper format as defined by the control stings

The complete format code used below in the printf() function for the various data variables shown
The complete format code used
below
in
the
printf() function for the various data variables shown
Code
Meaning
%c
Read a single character
%d
Read a decimal integer
%i
Read a decimal integer
%e
Read a floating point number
%f
Read a floating point number
%h
Read a short integer
%o
Read a octal number
%s
Read a string
%x
Read a hexadecimal number
%%
Print a percent sign
THE get() AND putc() FUNCTIONS
The most fundamental character I/O functions are getc() and putc().

getc()

The

getc() function inputs a

keyboard ,unless you redirect it

single character form the

standard

input device which is

The format for getc( ) follows

intvar=getc(device);

22 # 55

Don‟t

let

the

integer

intvar confuse

you.

Even though getc() is a character function,

you use

a

integer variable to store the

getc() input value. getc() returns a 1 when an end-of-file condition

occurs. If you are using getc() to read information from a disk file, the 1 is read when the end of

the file is reached

The getc() device can be any c standard input device .if you are getting character input from the keyboard ,use stdin as the device

putc()

The putc() functions writes a single character to the standard output device ,which is the screen,
The putc() functions writes a single character to the standard output device ,which is the
screen, unless you redirect it from your operating system.
The format of putc() follows:
putc(intval,device);
The intval can be integer variable, expression, or constant. You output character data with
putc().the device can be any standard output c device.to write a character to your printer, use
stdprn for the device.
Example program
/*Introduces getc() and putc()*/
#include<stdio.h>
#include<conio.h>
void main()
{
int inchar; //Holds incomming initial
char first,last;
//Holds converted first and last intial
clrscr();
printf("what is your first name initial?");
inchar=getc(stdin); //Wait for first initial

first=inchar;

inchar=getc(stdin);

// ignore newline

printf("what is your last name initial?");

inchar=getc(stdin);

last=inchar;

inchar=getc(stdin);

//Wait for last initial

// ignore newline

23 # 55

printf("\nHere they are!!!\n");

putc(first,stdout);

putc('\n',stdout); // A newline is output

putc(last,stdout);

getch();

}

23 # 55 printf("\nHere they are!!!\n"); putc(first,stdout); putc('\n',stdout); // A newline is output putc(last,stdout); getch(); }

OUTPUT

23 # 55 printf("\nHere they are!!!\n"); putc(first,stdout); putc('\n',stdout); // A newline is output putc(last,stdout); getch(); }
23 # 55 printf("\nHere they are!!!\n"); putc(first,stdout); putc('\n',stdout); // A newline is output putc(last,stdout); getch(); }

The getchar() and putchar() functions

When you perform character I/O ,the getchar() functions are easier to use than getc() and putc(). The getchar() and putchar() functions are identical to getc() and putc(),except you do not specify a because they assume that the standard input and output devices are stdin and stdout (typically ,the screen and the keybord).in the following

inchar=getc(stdin);

Is identical to

inchar=getchar();

And

24 # 55

putc(var.stdout);

is identical to

putchar(var);

The getchar() and the

getc() functions are both buffered input functions. That is as you

type characters, the data goes to a buffer rather than immediately to your program. The buffer is a section of memory managed by C

When your program gets to a getc() or a getchar(),the program temporarily waits as you type
When your program gets to a getc() or a getchar(),the program temporarily waits as you type the
input. The program does not seethe characters because they are going to the buffer in memory
there is no limit to the size of the buffer; it keeps filling up with you press enter. Pressing the
enter key signals the computer to release the buffer to your program
/*Illustrates simple getchar() and putchar()*/
#include<stdio.h>
#include<conio.h>
void main()
{
int mychar; // Must be integer
clrscr();
mychar=getchar();
// Get the character
printf("You Typed This!!!\n");
putchar(mychar);
getch();
}

25 # 55

OUTPUT

25 # 55 OUTPUT The getch() and putch() functions are not ANSI C standard functions, but
The getch() and putch() functions are not ANSI C standard functions, but they
The
getch()
and
putch() functions are
not ANSI
C
standard functions, but they

getch() and putch() funtoins

The getch() and putch() functions are slightly different than the previous character I/O functions. Their formats are similar to getchar() and putchar() ; they both assume that stdin and stdout are the standard input and output devices, and you can‟t specify other devices(unless you redirect them with your operating system)

The format of getch()

intvar=getch();

The format of putch()

putch(intvar);

are

available on a large number of compilers and well worth mentioning,

getch() and putch() are

non-buffered functions

Both getch() and putch() assume that stdin and stdout are the standard input and output devices. When you want your program to respond immediately to keyboard input use getch().some programmers want to make users press enter after answering a prompt or selecting from a menu. They feel that buffered input gives users more time to decide if they really want to give that answer: users can press Backspace and correct the input before pressing Enter

Example program

/*uses getch() and putch() input and output */

#include<stdio.h>

#include<conio.h>

26 # 55

void main()

{

int ctr; // The for loop counter

char letters[5];

// Holds five input characters

clrscr();

printf("Please Type Five Letters ....\n");

for(ctr=0;ctr<5;ctr++)

{ letters[ctr]=getch(); // Add input to array } printf("\nYou Typed Five Letters are!!!\n"); for(ctr=0;ctr<5;ctr++) // Print
{
letters[ctr]=getch(); // Add input to array
}
printf("\nYou Typed Five Letters are!!!\n");
for(ctr=0;ctr<5;ctr++) // Print them to the screen
{
putch(letters[ctr]);
}
for(ctr=0;ctr<5;ctr++)
{
putc(letters[ctr],stdprn); // Print them to the printer
}
getch();
}

27 # 55

OUTPUT

STRING I/O FUNCTIONS The input and output functions are listed fellow gets(s):stores input from stdin(usually directed
STRING I/O FUNCTIONS
The input and output functions are listed fellow
gets(s):stores input from stdin(usually directed to the keyboard)into the string named s
puts(s):output the s string to stdout(usually directed to the screen by the operating system)
Therefore when you enter stings with gets(), C places a string-terminating character in
the
string at the point where you press Enter. This creates the input sting. (Without the null zero,
the input would
not be
a
string).when you output a string,
the null zero
at
the
end
of the sting
becomes a newline character. This is good because you typically prefer a newline at the end of a
line of output (to put the cursor on the next line)
Example Program
/*using gets() and puts()*/
#include<stdio.h>

#include<conio.h>

void main()

 

{

char

book[30];

// Holds the string

clrscr();

printf("What is the Book Tittle?\n");

28 # 55

gets(book);

// Get an input String

printf("You Typed the Book Tittles are!\n");

puts(book);

// Display the String

printf("Thanks for the Book!!!\n");

getch();

}

OUTPUT

28 # 55 gets(book); // Get an input String printf("You Typed the Book Tittles are!\n"); puts(book);

29 # 55

DECISION MAKING AND BRANCH STATEMENTS

Decision Making and Branching Statements
Decision Making
and Branching
Statements
Simple if The if else Nesting of if else The else if Ladder statements statements statements
Simple if
The if else
Nesting of if else
The else if Ladder
statements
statements
statements
False
Condition
True True Statements
True
True Statements

Simple if statements:

Syntax:

if(test expression) {

Statement block one or more;

}

Statement x;

If the test expression is true then the statement is executes otherwise it goes to out of branch

30 # 55

Example:

//simple if program

#include<stdio.h> #include<conio.h> void main()

{ int age=21; //declare and assign age as 21 clrscr(); printf(“\n What is student age? ”); scanf(“%d”,&age);

if(age<=18)

{

30 # 55 Example: //simple if program #include<stdio.h> #include<conio.h> void main() { int age=21; //declare and

printf(“Your are Minor”);

}

getch();

}

Output:

30 # 55 Example: //simple if program #include<stdio.h> #include<conio.h> void main() { int age=21; //declare and

31 # 55

Simple if else statements:

Syntax:

if(condition) { Block of one or more statements } else { Block of one or more statements }

True False Condition True Statements False Statements
True
False
Condition
True Statements
False Statements
31 # 55 Simple if else statements: Syntax: if(condition) { Block of one or more statements

The if condition is true then execute entire if block statement other wise else statement is execute

32 # 55

Example:

//simple if else program #include<stdio.h> #include<conio.h> void main() { int num; clrscr(); printf("What is your number?"); scanf("%d",&num);

32 # 55 Example: //simple if else program #include<stdio.h> #include<conio.h> void main() { int num; clrscr();

if(num>=10)

{ printf("More than 10\n"); } else { printf("Less or equal to 10\n"); } getch(); }

33 # 55

OUTPUT

33 # 55 OUTPUT When a series of decisions are involved. We may have to if(test
When a series of decisions are involved. We may have to if(test condition-2) { Statements -1;
When a
series
of decisions are involved.
We may have
to
if(test condition-2)
{
Statements -1;

Nested if else statements:

use more than one if….else

statements

Syntax:

if(test condition-1) {

}

else

{

statements -2;

}

}

else

34 # 55

{

Statements-3;

}

Statements x;

If the condition-1

is

false,

the statement-3 will be executed, otherwise to perform the

second test. if the condition -2 is true, the statement-1 will be evaluated, otherwise the statement- 2 will be evaluated and then the control is transferred to the statement-x

34 # 55 { Statements-3; } Statements – x; If the condition-1 is false, the statement-3
34 # 55 { Statements-3; } Statements – x; If the condition-1 is false, the statement-3

35 # 55

Example:

//nested if else program #include<stdio.h> #include<conio.h> void main() { int a,b,c; clrscr(); printf("\nEnter the three valus:"); scanf("%d%d%d",&a,&b,&c); prtinf(“\n***OUTPUT***\n”); printf("The Largest values are:"); if(a>b) {

if(a>c) { printf("%d",a); } else { printf("%d",c); }
if(a>c)
{
printf("%d",a);
}
else
{
printf("%d",c);
}

}

else

{

if(c>b)

{

printf("%d",c);

}

else

{

36 # 55

printf("%d",b);

}

}

getch();

}

OUTPUT

36 # 55 printf("%d",b); } } getch(); } OUTPUT The else if ladder statements: A multiple
36 # 55 printf("%d",b); } } getch(); } OUTPUT The else if ladder statements: A multiple

The else if ladder statements:

A multiple decision is a chain of if is which statement associated with each else is an

Syntax:

If(condition) Statement -1; else if (condition 2)

if

statement-2;

else if(condition-3)

statement-3;

else if(condition n) statement n; else default statements;

37 # 55

statement x;

The conditions are evaluated from the top to downwards. As soon as a true condition is found, the statement associated with it is executed and the control is transferred to the statement-

x.

When

all

the

condition is false

then the

final else

containing the default statement will be

executed

 

Example:

//else if ladder #include<stdio.h> #include<conio.h> void main() { int num; clrscr(); printf("Enter the Number(1-5)"); scanf("%d",&num); printf(“\n***OUTPUT***\n”);

37 # 55 statement – x; The conditions are evaluated from the top to downwards. As

if(num==1)

printf("color=RED"); else if(num==2) printf("color=GREEN"); else if(num==3) printf("color=WHITE"); else if(num==4) printf("color=YELLOW"); else if(num==5) printf("color=BLUE"); else printf("color=BLOCK"); getch(); }

38 # 55

OUTPUT

38 # 55 OUTPUT The switch statement is sometimes called the multiple choice statement switch case
The switch statement is sometimes called the multiple choice statement switch case 1 block-1; Statements break;
The switch statement is sometimes called the multiple choice statement
switch
case 1
block-1;
Statements
break;
case 2
Statements
block-2;
default
break;
Statements

switch case statement:

Syntax:

switch (expression)

{

case value1:

case value2:

….

….

….

default:

default-block;

break;

39 # 55

The expression can be an integer expression, a character, a constant or a variable. The sub expression (value1, value 2 and so on)

If the expression matches value1

the statement execute and

so

on.

None

of the value

is

not match then default statement is executes

Example:

//simple switch program #include<stdio.h> #include<conio.h> void main() { int num; clrscr(); printf("Enter the number(1-7)"); scanf("%d",&num); switch(num) { case 1:

39 # 55 The expression can be an integer expression, a character, a constant or a

{ printf("This is Sunday"); break; } case 2:

{ printf("This is Monday"); break; } case 3:

{ printf("This is Tuesday"); break; }

40 # 55

case 4:

{ printf("This is Wendsday"); break; } case 5:

{ printf("This is Thursday"); break; } case 6: { printf("This is Friday"); break; } case 7:
{
printf("This is Thursday");
break;
}
case 6:
{
printf("This is Friday");
break;
}
case 7:
{
printf("This is Saturday");
break;
}
default:
printf("You Enter the Wrong Number try again");
}
getch();
}

41 # 55

OUTPUT

UNCONDITIONAL STATEMENTS break The for loop was designed to execute for a specified number of times,
UNCONDITIONAL
STATEMENTS
break
The for loop was designed to execute for a specified number of times, sometimes, though
rarely the
for loop
should quit before the counting variable has reached its final value,
as with
while loops, you use the break statements to quite a for loop early.
The break statement goes in the body of the for loop. Programmers rarely put break on a line by
itself, and
it almost comes
after
an
if test.if the
break
were
on
a
line
by itself the
loop
would
always quit early defeating the purpose of the for loop
The format of break is
break;
Example
for(ctr=0;ctr<n;ctr++)
{
break;
printf(“Loop now\n‟); // this never print break terminates loop immediately
}

42 # 55

Example

/*a for loop running at the user's request*/

#include<stdio.h> #include<conio.h> void main() { int num,ans;

// loop counter variable

clrscr(); printf(" Here are the numbers from 1 to 20\n");

// will exit the for loop if user wants
// will
exit the for loop if user wants

for(num=1;num<=20;num++)

{ printf("%d\n",num); printf("Do you want to see another (Y/N)?"); ans=getchar(); if((ans=='N')||(ans=='n')) {

break;

} } printf("\n That's all !!!"); getch(); }

43 # 55

OUTPUT

43 # 55 OUTPUT THE CONTINUE STATEMENT The break statements exits a loop early ,but the
43 # 55 OUTPUT THE CONTINUE STATEMENT The break statements exits a loop early ,but the

THE CONTINUE STATEMENT

The break statements exits a loop early ,but the continue statements forces the computer to perform another iteration of the loop.if you put a continue statements in the body of a for or a while loop, the computer ignores any statements in the loop that follow continue

The format of continue is continue; Example

for(ctr=0;ctr<n;ctr++)

{ continue; printf(“Loop now\n‟); // this never print }

continue causes loop to repeat once again

/* demonstrates use of continue statement */ #include<stdio.h> #include<conio.h> void main(){ int ctr; clrscr();

for(ctr=1;ctr<=10;ctr++)

{

printf("%d",ctr);

// Loop 10 times

44 # 55

continue;

// Causes body to end early

printf("C Programming\n");

}

getch();

}

OUTPUT

GOTO STATEMENT: C supports the goto statement to branch unconditionally from one point to another in
GOTO STATEMENT:
C supports the goto statement to branch unconditionally from one point
to another in the
program. The goto requires a label to identify the
place
where
the
branch is to be made. A label
is any valid variable name, must be followed by a colon. The label is placed immediately before
the statement where the control is to be transferred.
General forms:
goto label;
label:
……………
..
statement;
……………
..
……………
..
label:
……………
..
statement;
goto label;
Forward jump
Backward jump

Syntax:

goto begin;

45 # 55

goto breaks the normal sequential execution of the program. If the label: is before the statement goto label; a loop will be formed and some statements will be executed repeatedly. such a jump is called backward jump. If the label: is placed after the goto label; some statements

will be skipped and the jump is known as forward jump. A goto is used at the end of a program to direct the control to go to the input statement, to read further data.

Example

/* This is Program demonstrates the overuse of goto */ #include<stdio.h> #include<conio.h> void main() { clrscr();
/* This is Program demonstrates the overuse of goto */
#include<stdio.h>
#include<conio.h>
void main()
{
clrscr();
goto Here;
First:
printf("A\n");
goto Final;
There:
printf("B\n");
goto First;
Here:
printf("C\n");
goto There;
Final:
getch();
}

46 # 55

OUTPUT

46 # 55 OUTPUT DECISION MAKING AND LOOP STATEMENTS DECISION MAKING AND LOOP STATEMENTS while do-while
DECISION MAKING AND LOOP STATEMENTS DECISION MAKING AND LOOP STATEMENTS while do-while for while parts of
DECISION MAKING AND LOOP STATEMENTS
DECISION
MAKING AND
LOOP
STATEMENTS
while
do-while
for
while
parts of a program to
entry-controlled loop statement.
Syntax:

The while statement is one of several C construct statement. Looping statements cause

execute repeatedly as long as a certain condition is being met. While is an

while(test-condition) { Body of the loop }

The test condition is evaluated

and

if the condition is

true(non zero),the block of one or

more C statements execute repeatedly until the test condition becomes false(evaluates to zero)

47 # 55

Body of the loop True Condition False
Body of the loop
True
Condition
False

Example:

//simple while program #include<stdio.h> #include<conio.h> void main() { char name[15]; int count=0; clrscr(); printf("What is Your First Name?"); scanf("%s",name); while(name[count]) { count++; } printf(“\n***OUTPUT***\n”); printf("Your Name has %d Characters",count); getch(); }

48 # 55

OUTPUT

48 # 55 OUTPUT Body of the loop True Condition False do… while The do…while is
Body of the loop True Condition
Body of the loop
True
Condition
False
False

do…while

The do…while is exit controlled loop. The body of the do-while execute at least once.

The do-while statement controls the do-while loop, which is similar to the while loop except the relational test occurs at the bottom (rather than top) of the loop. This ensures that the body of the loop executes at least once.

Syntax:

do

{

Body of the loop

}

while(test-condition);

Example:

//simple do while program

#include<stdio.h> #include<conio.h> void main() { int ctr=0; clrscr(); do

49 # 55

{ printf(" Computers are fun!\n"); ctr++; }

while(ctr<0);

getch();

}

OUTPUT

49 # 55 { printf(" Computers are fun!\n"); ctr++; } while(ctr<0); getch(); } OUTPUT for loop:
49 # 55 { printf(" Computers are fun!\n"); ctr++; } while(ctr<0); getch(); } OUTPUT for loop:
for loop: program for a specific number of times unlike determinate loop, and single lines then
for loop:
program for a specific number of times unlike
determinate loop, and
single lines
then initialization and
test
syntax:

The for loop is another entry-controlled loop, that enables you to repeat sections of your

for loop

is

a

decrement

in

the while and do-while loops, the

condition and

increment

and

for (initialization; test condition; increment/decrement operator)

{

Body of loop;

}

50 # 55

Initialization Increment/Decrement Example: //simple for program #include<stdio.h> #include<conio.h> void main() { int total,ctr; Body of the
Initialization
Increment/Decrement
Example:
//simple for program
#include<stdio.h>
#include<conio.h>
void main()
{
int total,ctr;
Body of the loop
Condition
True
False
total=0;
clrscr();
for(ctr=100;ctr<=200;ctr++)
{
total+=ctr;
}
printf(”\n***OUTPUT***\n”);
printf("The total is %d",total);
getch();
}

51 # 55

OUTPUT

51 # 55 OUTPUT for (………) { ………. for (…… ) .. { ………. } }
for (………) { ………. for (…… ) .. { ………. } }
for (………)
{
……….
for (…… ) ..
{
……….
}
}

NESTED LOOPS:

One for loop statement within another for loop statement called nested for loop.

Syntax:

Example:

#include<stdio.h> #include<conio.h> void main() {

int i,j; clrscr();

for(i=1;i<=5;i++)

52 # 55

{

 

for(j=1;j<=i;j++)

{

printf("%d",j);

}

printf("\n\n");

}

getch();

}

OUTPUT

52 # 55 { for(j=1;j<=i;j++) { printf("%d",j); } printf("\n\n"); } getch(); } OUTPUT  Jumping Out
52 # 55 { for(j=1;j<=i;j++) { printf("%d",j); } printf("\n\n"); } getch(); } OUTPUT  Jumping Out
 Jumping Out of loop: Exiting from a loop inside a
Jumping Out of loop:
Exiting
from a
loop
inside a

JUMPS IN LOOPS:

can be

used

by break

or goto

statement. When a break

statement is used

loop, the loop is immediately exited and the program continues with

the statement immediately follows the loop. When the break is used in nested loop the program

will exit only from the single loop.

53 # 55

Example:

a) while (……) b) do { { if (condition) ………. break; ………. Exit ………… if (condition
a)
while (……)
b)
do
{
{
if (condition)
……….
break;
……….
Exit
…………
if (condition
From
…………
Exit
break;
loop
}
from
}while (……….);
…………
loop
…………
c)
for (……)
d)
for (………)
{
{
……….
……….
……….
for (…… ) ..
if (error)
{
break;
…… ..
Exit
……
..
if (condition)
from
……
..
break;
loop
Exit from
……….
}
Inner loop
}
..............
……….
}
  • Skipping a part of loop:

During the loop operations, to skip a body of loop under some conditions we may use continue statement. It tells the compile to skip the following statement and then continues with the next iteration.

54 # 55

Example:

a) while (test-condition) { b) do { -------------- --------------- if (-----------) if (-----------) continue; continue; -----------
a)
while (test-condition)
{
b)
do
{
--------------
---------------
if (-----------)
if (-----------)
continue;
continue;
-----------
-----------
-----------
-----------
}
}while(test-condition);
c)
for (initialization; test condition; increment/decrement operator)
{
------------
if -----------)
continue;
--------------
--------------
}
THE STANDARD HEADERS
Each standard library function is declared in one or more of the standard headers. These
headers also contain all the macro and type definitions that the C standard provides. This chapter
describes the contents and use of the standard headers.

Each of the standard headers contains a set of related function declarations, macros, and type definitions. The standard headers are also called header files, as the contents of each header are

Usually stored in a file. Strictly speaking, however, the standard does not require the headers to be organized in files.

55 # 55

The C standard defines the following headers.

assert.h

limits.h

signal.h

stdlib.h

ctype.h

math.h

stdarg.h

string.h

stdio.h

conio.h

stddef.h

time.h

55 # 55 The C standard defines the following headers. assert.h limits.h signal.h stdlib.h ctype.h math.h