You are on page 1of 33

ST.

JOSEPHS COLLEGE OF ENGINEERING & TECHNOLOGY PALAI


Affiliated to APJ Abdul Kalam Technological University, Approved by AICTE & All Four Courses Originally Started Accredited by NBA
Managed by Diocese of Palai An ISO 9001:2008 Certified Institute
Choondacherry P.O, Palai-686 579,Kerala
E-mail: sjcet@sancharnet.in Website: www.sjcetpalai.ac.in Phone: 04822-239301, 239302

INTRODUCTION TO C PROGRAMMING LANGUAGE

History

C was developed at Bell Laboratories in 1972 by Dennis Ritchie. Many of its principles and ideas
were taken from the earlier language B and B's earlier ancestors BCPL and CPL. CPL ( Combined
Programming Language ) was developed with the purpose of creating a language that was capable of
both high level, machine independent programming and would still allow the programmer to control
the behavior of individual bits of information. The one major drawback of CPL was that it was too
large for use in many applications. In 1967, BCPL ( Basic CPL ) was created as a scaled down
version of CPL while still retaining its basic features. In 1970, Ken Thompson, while working at Bell
Labs, took this process further by developing the B language. B was a scaled down version of BCPL
written specifically for use in systems programming. Finally in 1972, a co-worker of Ken Thompson,
Dennis Ritchie, returned some of the generality found in BCPL to the B language in the process of
developing the language we now know as C.

C's power and flexibility soon became apparent. Because of this, the Unix operating system which
was originally written in assembly language, was almost immediately re-written in C ( only the
assembly language code needed to "bootstrap" the C code was kept ). During the rest of the 1970's, C
spread throughout many colleges and universities because of it's close ties to Unix and the
availability of C compilers. Soon, many different organizations began using their own versions of C
causing compatibility problems. In response to this in 1983, the American National Standards
Institute ( ANSI ) formed a committee to establish a standard definition of C which became known as
ANSI Standard C. The standardization process took six years. The ANSI C standard was finally
adopted in December 1989, with the first copies becoming available in early 1990. The standard was
also adopted by ISO (International Standards Organization), and the resulting standard was typically
referred to as ANSI/ISO Standard C, or simply ANSI/ISO C. Today C is in widespread use with a
rich standard library of functions.

1
ST. JOSEPHS COLLEGE OF ENGINEERING & TECHNOLOGY PALAI
Affiliated to APJ Abdul Kalam Technological University, Approved by AICTE & All Four Courses Originally Started Accredited by NBA
Managed by Diocese of Palai An ISO 9001:2008 Certified Institute
Choondacherry P.O, Palai-686 579,Kerala
E-mail: sjcet@sancharnet.in Website: www.sjcetpalai.ac.in Phone: 04822-239301, 239302
Significant Language Features

C is a powerful, flexible language that provides fast program execution and imposes few constraints
on the programmer. It allows low level access to information and commands while still retaining the
portability and syntax of a high level language. These qualities make it a useful language for both
systems programming and general purpose programs.

C's power and fast program execution come from it's ability to access low level commands, similar to
assembly language, but with high level syntax. It's flexibility comes from the many ways the
programmer has to accomplish the same tasks. C includes bitwise operators along with powerful
pointer manipulation capabilities. C imposes few constraints on the programmer. The main area this
shows up is in C's lack of type checking. This can be a powerful advantage to an experienced
programmer but a dangerous disadvantage to a novice.
Another strong point of C is it's use of modularity. Sections of code can be stored in libraries for re-
use in future programs. This concept of modularity also helps with C's portability and execution
speed. The core C language leaves out many features included in the core of other languages. These
functions are instead stored in the C Standard Library where they can be called on when needed.. An
example of this concept would be C's lack of built in I/O capabilities. I/O functions tend to slow
down program execution and also be machine independent when running optimally. For these
reasons, they are stored in a library separately from the C language and only included when
necessary.

C is often called a middle-level computer language. This does not mean that C is less powerful,
harder to use, or less developed than a high-level language such as Pascal; nor does it imply that C is
similar to, or presents the problems associated with, assembly language. The definition of C as a
middle-level language means that it combines elements of high-level languages with the
functionalism of assembly language. As a middle-level language, C allows the manipulation of bits,
bytes, and addressesthe basic elements with which the computer functions. Despite this fact, C
code is surprisingly portable. Portability means that it is possible to adapt software written for one
type of computer to another. For example, if a program written for one type of CPU can be moved
easily to another, that program is portable. All high-level programming languages support the

2
ST. JOSEPHS COLLEGE OF ENGINEERING & TECHNOLOGY PALAI
Affiliated to APJ Abdul Kalam Technological University, Approved by AICTE & All Four Courses Originally Started Accredited by NBA
Managed by Diocese of Palai An ISO 9001:2008 Certified Institute
Choondacherry P.O, Palai-686 579,Kerala
E-mail: sjcet@sancharnet.in Website: www.sjcetpalai.ac.in Phone: 04822-239301, 239302
concept of data types. A data type defines a set of values that a variable can store along with a set of
operations that can be performed on that variable. Common data types are integer, character, and real.
Although C has several basic built-in data types, it is not a strongly typed language like Pascal or
Ada. In fact, C will allow almost all type conversions. For example, character and integer types may
be freely intermixed in most expressions. Traditionally C performs no run-time error checking such
as array-boundary checking or argument-type compatibility checking. These checks are the
responsibility of the programmer. A special feature of C is that it allows the direct manipulation of
bits, bytes, words, and pointers. This makes it well suited for system-level programming, where these
operations are common. Another important aspect of C is that it has only 32 keywords (5 more were
added by C99, but these are not supported by C++), which are the commands that make up the C
language. This is far fewer than most other languages.

C PREPROCESSOR DIRECTIVES:
The C Preprocessor is not a part of the compiler, but is a separate step in the compilation
process. In simple terms, a C Preprocessor is just a text substitution tool and it instructs the
compiler to do required pre-processing before the actual compilation. We'll refer to the C
Preprocessor as CPP.

All preprocessor commands begin with a hash symbol (#). It must be the first nonblank
character, and for readability, a preprocessor directive should begin in the first column.

Before a C program is compiled in a compiler, source code is processed by a program


called preprocessor. This process is called preprocessing.
Commands used in preprocessor are called preprocessor directives and they begin with
# symbol.
Below is the list of preprocessor directives that C programming language offers.

Preprocessor Syntax/Description

Syntax: #define
This macro defines constant value and can be any of the
Macro basic data types.

Header file Syntax: #include <file_name>


inclusion The source code of the file file_name is included in
3
ST. JOSEPHS COLLEGE OF ENGINEERING & TECHNOLOGY PALAI
Affiliated to APJ Abdul Kalam Technological University, Approved by AICTE & All Four Courses Originally Started Accredited by NBA
Managed by Diocese of Palai An ISO 9001:2008 Certified Institute
Choondacherry P.O, Palai-686 579,Kerala
E-mail: sjcet@sancharnet.in Website: www.sjcetpalai.ac.in Phone: 04822-239301, 239302

the main program at the specified place.

Syntax: #ifdef, #endif, #if, #else, #ifndef


Set of commands are included or excluded in source
Conditional program before compilation with respect to the
compilation condition.

Syntax: #undef, #pragma


#undef is used to undefine a defined macro variable.
#Pragma is used to call a function before and after main
Other directives function in a C program.

Predefined Macros

There are a number of macros automatically pre-defined by the compiler,


inlcuding the following list. Note that each one begins and ends
with TWO underscore characters:
o __LINE__ - The line number of the current file being compiled
o __FILE__ - The name of the current file being compiled
o __DATE__ - The current date
o __TIME__ - The current time

Header file

A header file is a file with extension .h which contains C function declarations and macro
definitions to be shared between several source files. There are two types of header files: the
files that the programmer writes and the files that comes with your compiler.

You request to use a header file in your program by including it with the C preprocessing
directive #include, like you have seen inclusion of stdio.h header file, which comes along with
your compiler.

Including a header file is equal to copying the content of the header file but we do not do it
because it will be error-prone and it is not a good idea to copy the content of a header file in the
source files, especially if we have multiple source files in a program.

4
ST. JOSEPHS COLLEGE OF ENGINEERING & TECHNOLOGY PALAI
Affiliated to APJ Abdul Kalam Technological University, Approved by AICTE & All Four Courses Originally Started Accredited by NBA
Managed by Diocese of Palai An ISO 9001:2008 Certified Institute
Choondacherry P.O, Palai-686 579,Kerala
E-mail: sjcet@sancharnet.in Website: www.sjcetpalai.ac.in Phone: 04822-239301, 239302

A simple practice in C or C++ programs is that we keep all the constants, macros, system wide
global variables, and function prototypes in the header files and include that header file
wherever it is required.

Include Syntax
Both the user and the system header files are included using the preprocessing
directive #include. It has the following two forms

#include <file>
This form is used for system header files. It searches for a file named 'file' in a standard list of
system directories. You can prepend directories to this list with the -I option while compiling
your source code.

#include "file"
This form is used for header files of your own program. It searches for a file named 'file' in the
directory containing the current file. You can prepend directories to this list with the -I option
while compiling your source code.

DATA TYPES AND QUALIFIERS IN C

C language is rich in data types. The fundamental data types which can be used in C are integer data
types, character data types and floating point data types. Integer data type is used to represent an
integer-valued number. Character data type represents one single alphabet or a single-digit integer.
Each character type has an equivalent integer representation. Integer and character data types can be
augmented by the use of the data type qualifiers, short, long, signed and unsigned. The range of
values which belong to each category varies with respect to the qualifiers and so, the memory
requirement.
Floating point data types are used to represent real numbers. Basic floating point data type offers six
digits of precision. Double precision data type can be used to achieve a precision of 14 digits. To
extend the precision further more, we may use the extended double precision floating point data type.
Each of the above discussed data types and their corresponding keywords are given in the table
below.

5
ST. JOSEPHS COLLEGE OF ENGINEERING & TECHNOLOGY PALAI
Affiliated to APJ Abdul Kalam Technological University, Approved by AICTE & All Four Courses Originally Started Accredited by NBA
Managed by Diocese of Palai An ISO 9001:2008 Certified Institute
Choondacherry P.O, Palai-686 579,Kerala
E-mail: sjcet@sancharnet.in Website: www.sjcetpalai.ac.in Phone: 04822-239301, 239302

DATA TYPES KEYWORD


Character char
Unsigned Character unsigned char
Signed Character signed char
Signed Integer signed int (or int)
Signed Short Integer signed short int (or short int or short)
Signed Long Integer signed long int (or long int or long)
Unsigned Integer unsigned int (or unsigned)
Unsigned Short Integer unsigned short int (or unsigned short)
Unsigned Long Integer unsigned long int (or unsigned long)
Floating Point float
Double Precision Floating Point double
Extended Double Precision long double
Floating Point

A schematic representation of the various data types in C is given below


In the table below, the memory size required by each data type in bits and the range of values they can
posses are listed.
DATA TYPE SIZE in BITS RANGE
char or signed char 8 -128 to 127.
unsigned char 8 0 to 255.
int or signed int 16 -32768 to 32767.
unsigned int 16 0 to 65535.
short int or signed short int 8 -128 to 127.
unsigned short int 8 0 to 255.
long int or signed long int 32 -2,147,483,648 to
2,147,483,647.

unsigned long int 32 0 to 4,294,967,295.


float 32 3.4e-38 to 3.4e+38.
double 64 1.7e-308 to 1.7e+308.
long double 80 3.4e-4932 to 3.4e+4932.

The syntax of the declaration of variables using data type is,


data-type vname-1, vname-2,..vname-n;
where vname-1, vname-2, vname-n are variable names. Some examples for the variable declaration
are given below.
int number;
6
ST. JOSEPHS COLLEGE OF ENGINEERING & TECHNOLOGY PALAI
Affiliated to APJ Abdul Kalam Technological University, Approved by AICTE & All Four Courses Originally Started Accredited by NBA
Managed by Diocese of Palai An ISO 9001:2008 Certified Institute
Choondacherry P.O, Palai-686 579,Kerala
E-mail: sjcet@sancharnet.in Website: www.sjcetpalai.ac.in Phone: 04822-239301, 239302
char a;
long double big-number;

EXPRESSIONS

Expressions in C are classified according to the operators used in them. The classifications are,

Relational expression.

Logical expression.

Arithmetic expression.

1. Relational expression.

An expression containing a relational operator is termed as relational expression. The list of all
relational operators is given below

OPERATOR MEANING

< Is less than.

<= Is less than or equal to.

> Is greater than.

>= Is greater than or equal to.

== Is equal to.

!= Is not equal to.

Format of a relation expression:


(a-expression-1) relational-operator (a-expression-2)
Where a-expression-1 and a-expression-2 are arithmetic expressions.
A relational expression always will have a value one or zero. The value of the relational expression
will be one if the specified relation is true and zero if the relation is false. Relational operators are

7
ST. JOSEPHS COLLEGE OF ENGINEERING & TECHNOLOGY PALAI
Affiliated to APJ Abdul Kalam Technological University, Approved by AICTE & All Four Courses Originally Started Accredited by NBA
Managed by Diocese of Palai An ISO 9001:2008 Certified Institute
Choondacherry P.O, Palai-686 579,Kerala
E-mail: sjcet@sancharnet.in Website: www.sjcetpalai.ac.in Phone: 04822-239301, 239302
used in decision statements such as if, and while to decide the course of action of a running
program. When arithmetic expressions are used on either side of a relational operator, the arithmetic
expressions will be evaluated first and then the results are compared.

2. Logical expression.

Logical expressions are the expressions where logical operators are used to combine more than one
relational expression. Logical expressions are also called compound relational expressions. The
logical operators used in C are && (logical AND), || (logical OR), and ! (logical NOT). Logical
expressions also yields a value of one or zero, and used in decision statements.
Format of a logical expression:
(rel-expression-1) logical operator (rel-expression-2)
Where rel-expression-1 and rel-expression-2 are relational expressions. The values of the above
statement when different logical operators are used is given below

Operator Value of rel-expression-1 Value of rel-expression-2 Value of the


statement
&& 0 0 0
0 1 0
1 0 0
1 1 1
| 0 0 0
0 1 1
1 0 1
1 1 1

3. ARITHMETIC EXPRESSIONS

An expression is a combination of variables constants and operators written according to the


syntax of C language. In C every expression evaluates to a value i.e., every expression results in
some value of a certain type that can be assigned to a variable. Some examples of C expressions
are shown in the table given below.

8
ST. JOSEPHS COLLEGE OF ENGINEERING & TECHNOLOGY PALAI
Affiliated to APJ Abdul Kalam Technological University, Approved by AICTE & All Four Courses Originally Started Accredited by NBA
Managed by Diocese of Palai An ISO 9001:2008 Certified Institute
Choondacherry P.O, Palai-686 579,Kerala
E-mail: sjcet@sancharnet.in Website: www.sjcetpalai.ac.in Phone: 04822-239301, 239302

C Expression
Algebraic Expression
axbc a*bc

(m + n) (x + y) (m + n) * (x + y)

(a x b / 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


Variable = expression;
Variable is any valid C variable name. When the statement is encountered, the expression is
evaluated first and then replaces the previous value of the variable on the left hand side. All variables
used in the expression must be assigned values before evaluation is attempted. Example of evaluation
statements are
x = a * b c; y = b / c * a; z = a b / c + d;

Precedence in Arithmetic Operators


An arithmetic expression without parenthesis will be evaluated from left to right using the rules of
precedence of operators. There are two distinct priority levels of arithmetic operators in C.
High priority * / %

Low priority + -

Rules for evaluation of expression

First parenthesized sub expression left to right are evaluated.

If parentheses are nested, the evaluation begins with the innermost sub expression.

The precedence rule is applied in determining the order of application of operators in


evaluating sub expressions.
9
ST. JOSEPHS COLLEGE OF ENGINEERING & TECHNOLOGY PALAI
Affiliated to APJ Abdul Kalam Technological University, Approved by AICTE & All Four Courses Originally Started Accredited by NBA
Managed by Diocese of Palai An ISO 9001:2008 Certified Institute
Choondacherry P.O, Palai-686 579,Kerala
E-mail: sjcet@sancharnet.in Website: www.sjcetpalai.ac.in Phone: 04822-239301, 239302

The associability rule is applied when two or more operators of the same precedence level
appear in the sub expression.

Arithmetic expressions are evaluated from left to right using the rules of precedence.

When Parenthesis are used, the expressions within parenthesis assume highest priority.

Operators in C Language

C language supports a rich set of built-in operators. An operator is a symbol that tells the
compiler to perform certain mathematical or logical manipulations. Operators are used in
program to manipulate data and variables.
C operators can be classified into following types,

Arithmetic operators
Relation operators

Logical operators

Bitwise operators

Assignment operators

Conditional operators

Special operators

1. Arithmetic operators
C supports all the basic arithmetic operators. The following table shows all the basic arithmetic
operators.

Operator Description

10
ST. JOSEPHS COLLEGE OF ENGINEERING & TECHNOLOGY PALAI
Affiliated to APJ Abdul Kalam Technological University, Approved by AICTE & All Four Courses Originally Started Accredited by NBA
Managed by Diocese of Palai An ISO 9001:2008 Certified Institute
Choondacherry P.O, Palai-686 579,Kerala
E-mail: sjcet@sancharnet.in Website: www.sjcetpalai.ac.in Phone: 04822-239301, 239302

+ adds two operands

- subtract second operands from first

* multiply two operand

/ divide numerator by denumerator

% remainder of division

++ Increment operator increases integer value by one

-- Decrement operator decreases integer value by one

2. Relation operators
The following table shows all relation operators supported by C.

Operator Description

== Check if two operand are equal

!= Check if two operand are not equal.

> Check if operand on the left is greater than operand on the right

< Check operand on the left is smaller than right operand

>= check left operand is greater than or equal to right operand

11
ST. JOSEPHS COLLEGE OF ENGINEERING & TECHNOLOGY PALAI
Affiliated to APJ Abdul Kalam Technological University, Approved by AICTE & All Four Courses Originally Started Accredited by NBA
Managed by Diocese of Palai An ISO 9001:2008 Certified Institute
Choondacherry P.O, Palai-686 579,Kerala
E-mail: sjcet@sancharnet.in Website: www.sjcetpalai.ac.in Phone: 04822-239301, 239302

<= Check if operand on left is smaller than or equal to right operand

3. Logical operators
C language supports following 3 logical operators. Suppose a=1 and b=0,

Operator Description Example

&& Logical AND (a && b) is false

|| Logical OR (a || b) is true

! Logical NOT (!a) is false

4. Bitwise operators
Bitwise operators perform manipulations of data at bit level. These operators also perform shifting of
bits from right to left. Bitwise operators are not applied to float or double.

Operator Description

& Bitwise AND

| Bitwise OR

^ Bitwise exclusive OR

<< left shift

>> right shift

Now lets see truth table for bitwise &, | and ^

12
ST. JOSEPHS COLLEGE OF ENGINEERING & TECHNOLOGY PALAI
Affiliated to APJ Abdul Kalam Technological University, Approved by AICTE & All Four Courses Originally Started Accredited by NBA
Managed by Diocese of Palai An ISO 9001:2008 Certified Institute
Choondacherry P.O, Palai-686 579,Kerala
E-mail: sjcet@sancharnet.in Website: www.sjcetpalai.ac.in Phone: 04822-239301, 239302

a b a&b a|b a^b

0 0 0 0 0

0 1 0 1 1

1 0 0 1 1

1 1 1 1 0

The bitwise shift operators shifts the bit value. The left operand specifies the value to be shifted and the right
operand specifies the number of positions that the bits in the value are to be shifted. Both operands have the
same precedence.
Example :
a = 0001000

b= 2

a << b = 0100000

a >> b = 0000010

5. Assignment Operators
Assignment operators supported by C language are as follows.

Operator Description Example

= assigns values from right side operands to left side operand a=b

+= adds right operand to the left operand and assign the result to left a+=b is same as a=a+b

13
ST. JOSEPHS COLLEGE OF ENGINEERING & TECHNOLOGY PALAI
Affiliated to APJ Abdul Kalam Technological University, Approved by AICTE & All Four Courses Originally Started Accredited by NBA
Managed by Diocese of Palai An ISO 9001:2008 Certified Institute
Choondacherry P.O, Palai-686 579,Kerala
E-mail: sjcet@sancharnet.in Website: www.sjcetpalai.ac.in Phone: 04822-239301, 239302

-= subtracts right operand from the left operand and assign the result to left operand a-=b is same as a=a-b

*= mutiply left operand with the right operand and assign the result to left operand a*=b is same as a=a*b

/= divides left operand with the right operand and assign the result to left operand a/=b is same as a=a/b

%= calculate modulus using two operands and assign the result to left operand a%=b is same as a=a%b

6. Conditional operator
It is also known as ternary operator and used to evaluate conditional expression.
epr1 ? expr2 : expr3

If epr1 Condition is true ? Then value expr2 : Otherwise value expr3

Eg: r = (m>n) ? m : n
If m is greater than n then r=m otherwise r=n

7. Special operator

Operator Description Example

sizeof Returns the size of an variable sizeof(x) return size of the variable x

& Returns the address of an variable &x ; return address of the variable x

* Pointer to a variable *x ; will be pointer to a variable x

14
ST. JOSEPHS COLLEGE OF ENGINEERING & TECHNOLOGY PALAI
Affiliated to APJ Abdul Kalam Technological University, Approved by AICTE & All Four Courses Originally Started Accredited by NBA
Managed by Diocese of Palai An ISO 9001:2008 Certified Institute
Choondacherry P.O, Palai-686 579,Kerala
E-mail: sjcet@sancharnet.in Website: www.sjcetpalai.ac.in Phone: 04822-239301, 239302

DATA INPUT AND OUTPUT STATEMENTS

In any programming language, the interface forms a very important part. It deals with
taking data from the user and displaying back the output. For this purpose, we require the input-
output operations. Since this is an important concept for any programming language, I would like
to take it in parts rather than as a long single article. So this article deals with the basics of input
operations.

Reading ,processing ,and writing of data are the three essential functions of a computer program .
Most programs take some data as input and display the processed data , often known as
information or results, on a suitable medium.

Unlike other high-level languages , C does not have any built-in input/output statements as part
of its syntax . All input / output operations are carried out through function calls such as printf
and scanf. There exist several functions that have more or less become standard for input and
output operations in C. These functions are collectively known as the standard I/O library.
Each program that uses a standard input/output function must contain the statement

#include <stdio.h>

at the beginning. However, there might be exceptions. For example, this is not necessary for the
functions printf and scanf which have been defined as part of the C language.
The file name stdio.h is an abbreviation for standard input -output header file. The instruction
#include <stdio.h> tells the compiler to search for a file named stdio.h and place its contents at
this point in the program. The contents of the header file become part of the source code when it
is compiled.

Single character input output:

The simplest of all input/output operations is reading a character from the standard input unit
(usually the keyboard) and writing it to the standard output unit (usually the screen). Reading a

15
ST. JOSEPHS COLLEGE OF ENGINEERING & TECHNOLOGY PALAI
Affiliated to APJ Abdul Kalam Technological University, Approved by AICTE & All Four Courses Originally Started Accredited by NBA
Managed by Diocese of Palai An ISO 9001:2008 Certified Institute
Choondacherry P.O, Palai-686 579,Kerala
E-mail: sjcet@sancharnet.in Website: www.sjcetpalai.ac.in Phone: 04822-239301, 239302

single character can be done by using the function getchar. The getchar takes the following
form:
variable_name = getchar();

variable_name is a valid C name that has been declared as char type. When this statement is
encountered , the computer waits until a key is pressed and then assigns this character as a value
to getchar function . Since getchar is used on the right-hand side of an assignment statement ,
the character value of getchar is in turn assigned to the variable name on the left.

For example

char name;
name = getchar();

will assign the character 'H' to the variable name when we press the key H on the keyboard .
Since getchar is a function ,it requires a set of parentheses as shown.
The putchar function which in analogus to getchar function can be used for writing characters
one at a time to the output terminal. The general form is

putchar (variable name);

Where variable is a valid C type variable that has already been declared

Ex:-
putchar ( c);

Displays the value stored in variable C to the standard screen.

Program shows the use of getchar function in an interactive environment.

#include < stdio.h > // Inserts stdio.h header file into the Pgm
void main ( ) // Beginning of main function.
{

16
ST. JOSEPHS COLLEGE OF ENGINEERING & TECHNOLOGY PALAI
Affiliated to APJ Abdul Kalam Technological University, Approved by AICTE & All Four Courses Originally Started Accredited by NBA
Managed by Diocese of Palai An ISO 9001:2008 Certified Institute
Choondacherry P.O, Palai-686 579,Kerala
E-mail: sjcet@sancharnet.in Website: www.sjcetpalai.ac.in Phone: 04822-239301, 239302

char in; // character declaration of variable in.


printf ( please enter one character); // message to user
in = getchar ( ) ; // assign the keyboard input value to in.
putchar (in); // out put in value to standard screen.
}

C supports testing of the character keyed in by the user by including the file ctype.h & the
functions which can be used after including this file are

isalnum(c) Is c an alphanumeric character?


isalpha(c) Is c an alphabetic character?
isdigit(c) Is c a digit?
islower(c)Is c a lower case character?
isprint(c)Is c a printable character?
ispunct(c)Is c a punctuation mark?
isspace(c)Is c a white space character?
isupper(c) Is c a upper case character?

String input and output:

The gets function relieves the string from standard input device while put S outputs the string to
the standard output device. A strong is an array or set of characters.

The function gets accepts the name of the string as a parameter, and fills the string with
characters that are input from the keyboard till newline character is encountered. (That is till we
press the enter key). All the end function gets appends a null terminator as must be done to any
string and returns.

The puts function displays the contents stored in its parameter on the standard screen.
The standard form of the gets function is

17
ST. JOSEPHS COLLEGE OF ENGINEERING & TECHNOLOGY PALAI
Affiliated to APJ Abdul Kalam Technological University, Approved by AICTE & All Four Courses Originally Started Accredited by NBA
Managed by Diocese of Palai An ISO 9001:2008 Certified Institute
Choondacherry P.O, Palai-686 579,Kerala
E-mail: sjcet@sancharnet.in Website: www.sjcetpalai.ac.in Phone: 04822-239301, 239302

gets (str) Here str is a string variable.

The standard form for the puts character is

puts (str) Where str is a string variable.

Eample program (Involving both gets and puts)

# include < stdio.h >


Void main ( )
{
char s [80];
printf (Type a string less than 80 characters:);
gets (s);
printf (The string types is:);
puts(s);
}

Formatted Input

Formatted input refers to an input data that has been arranged in a particular format . For
example, consider the following data:
15.73 123 John
This line contains three pieces of data, arranged in a particular form. Such data has to be read
conforming to the format of its appearance. For example, the first part of the data should be read
into a variable float, the second into int, and the third part into char. This is possible in C using
the scanf function .
The general form of scanf is

scanf("control string", arg1, arg2,......argn);

18
ST. JOSEPHS COLLEGE OF ENGINEERING & TECHNOLOGY PALAI
Affiliated to APJ Abdul Kalam Technological University, Approved by AICTE & All Four Courses Originally Started Accredited by NBA
Managed by Diocese of Palai An ISO 9001:2008 Certified Institute
Choondacherry P.O, Palai-686 579,Kerala
E-mail: sjcet@sancharnet.in Website: www.sjcetpalai.ac.in Phone: 04822-239301, 239302

The control string specifies the field format in which the data is to be entered and the arguments
arg1 ,arg2, .....argn specify the address of locations where the data is stored . Control string and
arguments are seperated by commas.
scanf Format Codes:

%c reads a single character


%d read a decimal integer
%e read a floating point value
%f read a floating point value
%g read a floating point value
%h read a short integer
%i read a decimal, hexadecimal, or octal integer
% o read an octal integer
%s read a string
%u read an unsigned decimal integer
%x read a hexadecimal integer
%[..] read a string of word(s)

Printing One Line:

printf();

The most simple output statement can be produced in C Language by using printf statement. It allows
you to display information required to the user and also prints the variables we can also format the output
and provide text labels. The simple statement such as

Printf (Enter 2 numbers);

Prompts the message enclosed in the quotation to be displayed.

Syntax

printf (conversion string, variable list);

19
ST. JOSEPHS COLLEGE OF ENGINEERING & TECHNOLOGY PALAI
Affiliated to APJ Abdul Kalam Technological University, Approved by AICTE & All Four Courses Originally Started Accredited by NBA
Managed by Diocese of Palai An ISO 9001:2008 Certified Institute
Choondacherry P.O, Palai-686 579,Kerala
E-mail: sjcet@sancharnet.in Website: www.sjcetpalai.ac.in Phone: 04822-239301, 239302

The conversion string includes all the text labels, escape character and conversion specifiers
required for the desired output. The variable includes all the variable to be printed in order they
are to be printed. There must be a conversion specifies after each variable.

CONTROL STATEMENTS
C provides two sytles of flow control:
Branching
Looping

Branching is deciding what actions to take and looping is deciding how many times to
take a certain action.

BRANCHING :
Branching is so called because the program chooses to follow one branch or another.

IF_ELSE

This lesson will show you how to:

Use an if statement

Use an else statement

Use an else if statement

IF STATEMENT

The if statement is used to conditionally execute a block of code based on whether a test condition is
true. If the condition is true the block of code is executed, otherwise it is skipped.

SYNTAX
if (condition)

true_statements ;

20
ST. JOSEPHS COLLEGE OF ENGINEERING & TECHNOLOGY PALAI
Affiliated to APJ Abdul Kalam Technological University, Approved by AICTE & All Four Courses Originally Started Accredited by NBA
Managed by Diocese of Palai An ISO 9001:2008 Certified Institute
Choondacherry P.O, Palai-686 579,Kerala
E-mail: sjcet@sancharnet.in Website: www.sjcetpalai.ac.in Phone: 04822-239301, 239302
OR

if (condition)

true_statement ;

OR

if (condition)

true_statements ;

else

false_statements ;

PROGRAM FLOW

1. First, the boolean expression condition is evaluated.

2. If condition evaluates to true, the true_statement(s) are executed.

3. If condition evaluates to false and an else clause exists, the false_statement(s) are executed.

4. Flow exits the if-else structure.

EXAMPLE

#include <stdio.h>
int main(void)
{
int number = 75;
int mark;
printf("Your examination mark\n");
printf("Enter your score, please\n");

21
ST. JOSEPHS COLLEGE OF ENGINEERING & TECHNOLOGY PALAI
Affiliated to APJ Abdul Kalam Technological University, Approved by AICTE & All Four Courses Originally Started Accredited by NBA
Managed by Diocese of Palai An ISO 9001:2008 Certified Institute
Choondacherry P.O, Palai-686 579,Kerala
E-mail: sjcet@sancharnet.in Website: www.sjcetpalai.ac.in Phone: 04822-239301, 239302
scanf("%d",&mark);
if (mark >= number)
{
printf("Incredible, you passed with a merit\n");
}
return 0;
}

The "==" is called a relational operator. Relational operators, ==, !=, >, >=, <, and <=, are used to
compare two values.

Else Statement

The else statement provides a way to execute one block of code if a condition is true, another if it is
false.
Example:
#include <stdio.h>
int main(void)
{
int number = 75;
int mark;
printf("Your examination mark\n");

printf("Enter your score, please\n");

scanf("%d",&mark);

if (mark >= number)

{
printf("Incredible, you have passed with a merit\n");
}
else
{
printf("You failed, unlucky\n");
}

22
ST. JOSEPHS COLLEGE OF ENGINEERING & TECHNOLOGY PALAI
Affiliated to APJ Abdul Kalam Technological University, Approved by AICTE & All Four Courses Originally Started Accredited by NBA
Managed by Diocese of Palai An ISO 9001:2008 Certified Institute
Choondacherry P.O, Palai-686 579,Kerala
E-mail: sjcet@sancharnet.in Website: www.sjcetpalai.ac.in Phone: 04822-239301, 239302
return 0;
}

LOOPING :

A) FOR LOOP
SYNTAX
for (initialization ; test ; increment)

statements ;

OR

for (initialization ; test ; increment)

statement ;

PROGRAM FLOW

1. The initialization is first executed. This is typically something like int i=0, which creates a
new variable with initial value 0, to act as a counter. Variables that you declare in this part
of the for loop cease to exist after the execution of the loop is completed. Multiple,
comma separated, expressions are allowed in the initialization section. But declaration
expressions may not be mixed with other expressions.

2. The boolean expression test is then evaluated. This is typically something like i<10.
Multiple, comma separated, expressions are not allowed. If test evaluates to true, flow
contiues to step 3. Otherwise the loop exits.

3. The statement(s) are executed.

4. Then the statement increment is executed. It is typically something like i++ , which
increments i by one or i+=2 , which increments i by two. Multiple, comma separated,
expressions are allowed in the increment section.

5. Flow returns to step 2.


23
ST. JOSEPHS COLLEGE OF ENGINEERING & TECHNOLOGY PALAI
Affiliated to APJ Abdul Kalam Technological University, Approved by AICTE & All Four Courses Originally Started Accredited by NBA
Managed by Diocese of Palai An ISO 9001:2008 Certified Institute
Choondacherry P.O, Palai-686 579,Kerala
E-mail: sjcet@sancharnet.in Website: www.sjcetpalai.ac.in Phone: 04822-239301, 239302

EXAMPLE

The following code will print hello ten times:

for (t=0; t<10; t++)


printf("Hello\n");

B) WHILE STATEMENT

The simplest of all the c looping structures in C is the while statement . The while statement is an
entry -controlled loop statement. The test condition is evaluated and if the condition is true then the
body of the loop is executed . After the execution of the body the test condition is once again
evaluated and if it is true ,the body is executed once again. This process of repeated execution of the
body is continued until the test condition becomes false and the control is transferred out of the loop.
On exit the program is continued with the statement after the body of the loop.
The body of the loop may have one or more statements. The braces are needed only if the body
contains two or more statements.

The format of while statement is

while (test condition)


{
body of the loop
}

Example of while statement


/*******************************************************/
/* Program to compute x to the power n using while loop */
/*******************************************************/

# include<stdio.h>
main()
{
24
ST. JOSEPHS COLLEGE OF ENGINEERING & TECHNOLOGY PALAI
Affiliated to APJ Abdul Kalam Technological University, Approved by AICTE & All Four Courses Originally Started Accredited by NBA
Managed by Diocese of Palai An ISO 9001:2008 Certified Institute
Choondacherry P.O, Palai-686 579,Kerala
E-mail: sjcet@sancharnet.in Website: www.sjcetpalai.ac.in Phone: 04822-239301, 239302
int count,n;
float x,y;
printf(Enter the values of x and n:);
scanf(%f %d, &x, &n);
y= 1.0;
count = 1;
/* LOOP BEGINS*/
while(count<= n)
{
y = y * n;
count ++;
}
/*End of loop*/
printf( x = %f ; n = %d ; to power n = %f n , x , n, y);
}

3) DO-WHILE STATEMENT
In while statement there is a chance of skipping the entire loop without execution if the value is
not satisfying the condition . To avoid such a condition we use do while statement. In do .. while
statement the body of the loop will be executed at least once . On reaching the do statement , the
program proceeds to evaluate the body first . At the end of the loop the test condition in the in the
while statement is evaluated if the condition is true the program continues to evaluate the body
of the loop once again . This process continues as long as the condition is true . When the
condition becomes false , the loop will be terminated and the control of the program goes to the
statement that appears after the while statement .

Since the test-condition is evaluated at the bottom of the loop , the do construct provides an exit-
controlled loop and therefore the body of the loop is always executed once.

The format of do while statement is as follows


do

25
ST. JOSEPHS COLLEGE OF ENGINEERING & TECHNOLOGY PALAI
Affiliated to APJ Abdul Kalam Technological University, Approved by AICTE & All Four Courses Originally Started Accredited by NBA
Managed by Diocese of Palai An ISO 9001:2008 Certified Institute
Choondacherry P.O, Palai-686 579,Kerala
E-mail: sjcet@sancharnet.in Website: www.sjcetpalai.ac.in Phone: 04822-239301, 239302
{

body of the loop

while (test condition);

Example for do while statement

/* Printing of multiplication table */


#define colmax 10

#define rowmax 12

main()

int row,column,y;

row = 1;

printf( MULTIPLICATION TABLE \n);

printf(_________________________________\n);

/* OUTER LOOP BEGINS */

do {

column = 1;

/* INNER LOOP BEGINS */

do

column = 1;

do

y = row * column;

26
ST. JOSEPHS COLLEGE OF ENGINEERING & TECHNOLOGY PALAI
Affiliated to APJ Abdul Kalam Technological University, Approved by AICTE & All Four Courses Originally Started Accredited by NBA
Managed by Diocese of Palai An ISO 9001:2008 Certified Institute
Choondacherry P.O, Palai-686 579,Kerala
E-mail: sjcet@sancharnet.in Website: www.sjcetpalai.ac.in Phone: 04822-239301, 239302

printf(%4d,y);

column = column +1;

while (column <= COLMAX);

/* INNER LOOP BEGINS */

printf(\n);

row = row + 1;

while( row <=ROWMAX);

/* OUTER LOOP ENDS */

printf(_______________________________________)

27
ST. JOSEPHS COLLEGE OF ENGINEERING & TECHNOLOGY PALAI
Affiliated to APJ Abdul Kalam Technological University, Approved by AICTE & All Four Courses Originally Started Accredited by NBA
Managed by Diocese of Palai An ISO 9001:2008 Certified Institute
Choondacherry P.O, Palai-686 579,Kerala
E-mail: sjcet@sancharnet.in Website: www.sjcetpalai.ac.in Phone: 04822-239301, 239302

SWITCH STATEMENT
The switch statement is another form of the multi way decision. It is well structured, but can
only be used in certain cases where;

Only one variable is tested, All branches must depend on the value of that variable.
The variable must be an integral type.(int long, short or char).

Each possible value of the variable can control a single branch. A final ,catch all
default branch may optionally be used to trap all unspecified cases.

Syntax

Switch(expression)

case value-1:

block-1

break;

case value-2:

block-2

break;

default:

default-block

break;

Hopefully an example will clarify things. This is a program which accepts four mathematical
symbols + , - , * , / .Then the program accepts two integers a & b & displays the output as the
value of a + b , a b , a * b or a / b depending upon the symbol entered.

#include<stdio.h>
28
ST. JOSEPHS COLLEGE OF ENGINEERING & TECHNOLOGY PALAI
Affiliated to APJ Abdul Kalam Technological University, Approved by AICTE & All Four Courses Originally Started Accredited by NBA
Managed by Diocese of Palai An ISO 9001:2008 Certified Institute
Choondacherry P.O, Palai-686 579,Kerala
E-mail: sjcet@sancharnet.in Website: www.sjcetpalai.ac.in Phone: 04822-239301, 239302

main()

int a,b;

char c;

printf(Enter the symbol \n);

scanf(%c,&c);
switch(c)

case + : printf(Enter the values for a & b\n);

scanf(%d %d,&a,&b);

printf(a + b = %d\n,a+b);

break;

case - : printf(Enter the values for a & b\n);

scanf(%d %d,&a,&b);

printf(a - b = %d\n,a-b);

break;

case * : printf(Enter the values for a & b\n);

scanf(%d %d,&a,&b);

printf(a * b = %d\n,a*b);

break;

case / : printf(Enter the values for a & b\n);

scanf(%d %d,&a,&b);
29
ST. JOSEPHS COLLEGE OF ENGINEERING & TECHNOLOGY PALAI
Affiliated to APJ Abdul Kalam Technological University, Approved by AICTE & All Four Courses Originally Started Accredited by NBA
Managed by Diocese of Palai An ISO 9001:2008 Certified Institute
Choondacherry P.O, Palai-686 579,Kerala
E-mail: sjcet@sancharnet.in Website: www.sjcetpalai.ac.in Phone: 04822-239301, 239302

printf(a / b = %d\n,a/b);

break;

default : printf(Invalid operator\n);

Here, each interesting case is listed with a corresponding action. The control passes to the
statement whose case constant- expression matches the value of switch (expression). The
switch statement can include any number of case instances, but no two case constants within the
same switch statement can have the same value. Execution of the statement body begins at the at
the selected statement and proceeds until the end of the body or until a break statement transfers
control out of the body. The break statement prevents any further statements from being
executed by leaving the switch. The default statement is executed if no case constant-expression
is equal to the value of switch(expression). If the default statement is omitted and no case match
is found, none of the statements in the switch body are executed. There can be at most one
default statement. The default statement need not come at the end, it can appear anywhere in the
body of the switch statement. A case or default label can only appear inside a switch statement.
Switch statement can be nested. A single statement can carry multiple case labels.

BREAK and CONTINUE statements

BREAK

Break forces a loop to exit immediately. Here's an example:

int markerpos=-1;
for (index=0 ;index < 10;index++ )
{
if (values[index] ==-999 )
{
markerpos = index;

30
ST. JOSEPHS COLLEGE OF ENGINEERING & TECHNOLOGY PALAI
Affiliated to APJ Abdul Kalam Technological University, Approved by AICTE & All Four Courses Originally Started Accredited by NBA
Managed by Diocese of Palai An ISO 9001:2008 Certified Institute
Choondacherry P.O, Palai-686 579,Kerala
E-mail: sjcet@sancharnet.in Website: www.sjcetpalai.ac.in Phone: 04822-239301, 239302

break;
}
}
if (markerpos== 999)
printf("-1 Not located in array";
else
printf("-1 Found at index %i\n\r",markerpos) ;

That's a more complicated example. It searches the 10 element array values looking for a 999
value. The variable markerpos holds the position if a 999 is found. It is initialized to -1 and after
the search this value is examined to see if a 999 was found.

CONTINUE

This does the opposite of break; Instead of terminating the loop, it immediately loops again,
skipping the rest of the code. So lets sum that integer array again, but this time we'll leave out
elements with an index of 4 and 5.

int value =0;


for (index=0 ;index < 10;index++ )
{
if (index==4 || index==5)
continue;
value += numbers[index];
}
printf("Value = %i",value) ;

You probably won't use continue very often but it's useful on the odd occasion.

NESTED LOOP

31
ST. JOSEPHS COLLEGE OF ENGINEERING & TECHNOLOGY PALAI
Affiliated to APJ Abdul Kalam Technological University, Approved by AICTE & All Four Courses Originally Started Accredited by NBA
Managed by Diocese of Palai An ISO 9001:2008 Certified Institute
Choondacherry P.O, Palai-686 579,Kerala
E-mail: sjcet@sancharnet.in Website: www.sjcetpalai.ac.in Phone: 04822-239301, 239302

These loops are the loops which contain another looping statement in a single loop. These types
of loops are used to create matrix. Any loop can contain a number of loop statements in itself. If
we are using loop within loop that is called nested loop. In this the outer loop is used for
counting rows and the internal loop is used for counting columns

SYNTAX:-

for (initializing ; test condition ; increment / decrement)

statement;

for (initializing ; test condition ; increment / decrement)

body of inner loop;

statement;

PROGRAM

#include

void main ( )

int i, j;

clrscr ( );

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

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

{
32
ST. JOSEPHS COLLEGE OF ENGINEERING & TECHNOLOGY PALAI
Affiliated to APJ Abdul Kalam Technological University, Approved by AICTE & All Four Courses Originally Started Accredited by NBA
Managed by Diocese of Palai An ISO 9001:2008 Certified Institute
Choondacherry P.O, Palai-686 579,Kerala
E-mail: sjcet@sancharnet.in Website: www.sjcetpalai.ac.in Phone: 04822-239301, 239302

printf (*)

printf (\n);

getch ( );

OUTPUT OF THIS PROGRAM IS

****
****
****
****

33

You might also like