Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
141 views

Programming in C

This Study material used for B.Sc CS,IT, BCA and all CS students. this material has history of C, Control Statement, Array, String

Uploaded by

lakshmi.s
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
141 views

Programming in C

This Study material used for B.Sc CS,IT, BCA and all CS students. this material has history of C, Control Statement, Array, String

Uploaded by

lakshmi.s
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 114

By

Lakshmi.S, M.C.A.,M.Phil.,
Assistant Professor, Department of Computer Science, Sri Adi
Chunchanagiri Women’s College, Cumbum.
Theni(D.t).

I
ABOUT THE BOOK

This book is intended for anyone who is learning programming for the
first time, regardless of age or institution. The material has been taught
successfully to students preparing for students at college level.
Chapter 1 gives an overview of Programming in c, Chapter 2
describes Keywords, Constants, Variables Chapter 3 explains Data types
Chapter 4 shows Operators And Expressions Chapter 5 explains
Managing Input/output Functions Chapter 6 introduces Decision Making
and Branching Chapter 7 deals Looping Chapter8 tackle the Array
Chapter 9 give the important questions.
The presentation is based on the experience that many people
have difficulty in learning programming. To try and overcome this,
we use an approach which provides clear examples, detailed
explanations of very basic concepts and numerous interesting
problems.But do not stop there.
The only way to learn programming well is to write programs
to solve new problems. The end of the chapter I give important
questions. This one very helpful for students at the examination time.
CONTENT

1. Introduction…........................................................................................1
History of C......................................................................................................1
Importance of C................................................................................................2
Uses and Features of C.....................................................................................3
Structure of C program.....................................................................................4
Executing a C program.....................................................................................9

2. Keywords, Constants, Variables


Character Set..................................................................................................13
Identifiers.......................................................................................................15
Variables........................................................................................................15
Constants........................................................................................................20
Character constant, Escape Sequence
String constant.........................................25

3. Data types.............................................................................................27
Basic Data Type.............................................................................................28
Type Casting..................................................................................................33

4. Operators And Expressions..................................................................36


Arithmetic Operator........................................................................................37
Relational Operator........................................................................................38
Logical Operator............................................................................................39
Bitwise Operator............................................................................................39
Assignment Operator.....................................................................................41
Conditional Operator.....................................................................................42
Special Operator.............................................................................................42
Arithmetic Expression....................................................................................43
Relational Expression.....................................................................................46
Logical Expression.............................................................................46
Type conversion in arithmetic expression..........................................47
Operator precedence and associativity...........................................48
5. Managing Input/Output Functions.......................................................52
Formatted Input/Output Functions.................................................................52
Formatted Input Functions - scanf( )……………………..52
Formatted Output Functions - printf( )…………………...59
Unformatted Input/Output Functions................................................65
Unformatted input functions...........................................................................65
Unformatted output functions.........................................................................67

6. Decision Manking and Branching.......................................................69


Simple If Statement........................................................................................71
If…Else Statement..........................................................................................72
Nesting Of If…..Else Statements....................................................................74
Else…If Ladder..............................................................................................76
Switch Statement............................................................................................78
The ?: Operator Conditional Operator Statement.......................81
Goto Statement...............................................................................................82
Break Statement..............................................................................................83
Continue Statement

7. Looping...............................................................................................85
While 86
Do – While.....................................................................................................88
For Loop.........................................................................................................90
Nested Loop....................................................................................................94

8. Array....................................................................................................95
One Dimensional Array..................................................................................95
Two Dimensional Array.................................................................................98
Multi Dimensional Array.............................................................................100
Working with Strings & Standard Functions…………..101
History of C Language

History of C language is interesting to know. Here we are going


to discuss brief history of c language. C language is one of the most
popular computer languages today because it is a structured, high level,
machine independent language.

C programming language was developed in 1972 by Dennis


Ritchie at bell laboratories of AT&T (American Telephone & Telegraph),
located in U.S.A. Dennis Ritchie is known as the founder of c language.

It was developed to overcome the problems of previous languages


such as B, BCPL etc.

Initially, C language was developed to be used in UNIX operating


system. It inherits many features of previous languages such as B and
BCPL.

Let's see the programming languages that were developed before C


language.

Language Year Developed By


Algol 1960 International Group
BCPL 1967 Martin Richard
B 1970 Ken Thompson
Traditional C 1972 Dennis Ritchie
K&RC 1978 Kernighan & Dennis Ritchie
ANSI C 1989 ANSI Committee
ANSI/ISO C 1990 ISO Committee

1
C99 1999 Standardization Committee

Importance of ‘C’ language :

C language is a famous programming language due to its qualities.


Some qualities are:

1. It is robust language whose rich setup of built in functions and


operator can be used to write any complex program.

2. Program written in C are efficient due to several variety of data


types and powerful operators.

3. The C compiler combines the capabilities of an assembly language


with the feature of high level language. Therefore it is well suited for
writing both system software and business package.

4. There are only 32 keywords; several standard functions are available


which can be used for developing program.

5. C is portable language; this means that C programs written for one


computer system can be run on another system, with little or no
modification.

6. C language is well suited for structured programming, this requires


user to think of a problems in terms of function or modules or block. A
collection of these modules make a program debugging and testing
easier.
7. C language has its ability to extend itself. A c program is basically a
collection of functions that are supported by the C library. We can
continuously add our own functions to the library with the availability
of the large number of functions.

8. In India and abroad mostly people use C programming


language because it is easy to learn and understand.

USES OF C PROGRAMMING LANGUAGE:


The C programming language is used for developing system
applications that forms a major portion of operating systems such as
Windows, UNIX and Linux.
Below are some examples of C being used:

 Database systems
 Graphics packages
 Word processors
 Spreadsheets
 Operating system development
 Compilers and Assemblers
 Network drivers
 Interpreters

Features of C language

 It is a robust language with rich set of built-in functions and operators


that can be used to write any complex program.
 The C compiler combines the capabilities of an assembly language
with features of a high-level language.
 Programs Written in C are efficient and fast. This is due to its
variety of data type and powerful operators.
 It is many time faster than BASIC.
 C is highly portable this means that programs once written can be
run on another machines with little or no modification.
 Another important feature of C program, is its ability to extend
itself.
 A C program is basically a collection of functions that are supported
by C library. We can also create our own function and add it to C
library.
 C language is the most widely used language in operating systems
and embedded system development today.
Structure of C program :

Documentation section
Link section
Definition section
Global declaration section
Main() Function section
{
Declaration part Executable part
}
Subprogram section
Function 1
(User defined function)
Function 2
------------------
---
-----------------
---
Function n

1. Documentation section: The documentation section consists of a


set of comment lines giving the name of the program, the author
and other details, which the programmer would like to use later.
2. Link section: The link section provides instructions to the
compiler to link functions from the system library such as using the
#include directive.
3. Definition section: The definition section defines all symbolic
constants such using the #define directive.
4. Global declaration section: There are some variables that are used
in more than one function. Such variables are called global
variables and are declared in the global declaration section that is
outside of all the functions. This section also declares all the user-
defined functions.
5. main () function section: Every C program must have one main
function section. This section contains two parts; declaration part
and executable part
1. Declaration part: The declaration part declares all the
variables used in the executable part.
2. Executable part: There is at least one statement in the
executable part. These two parts must appear between the
opening and closing braces. The program
executionbegins at the opening brace and ends at the
closing brace. The closing brace of the main function is the
logical end of the program. All statements in the declaration
and executable part end with a semicolon.
6. Subprogram section: If the program is a multi-function program
then the subprogram section contains all the user-defined
functions that are called in the main () function. User-defined
functions are generally placed immediately after the main ()
function, although they may appear in any order.
Example:

Write a program to print area of a circle. In the following example


we will find the area of a circle for a given radius 10cm.

Formula
The formula to compute the area of a circle is
πr2 where π is PI = 3.1416 (approx.) and r is the radius of the circle.
Lets write the C code to compute the area of the circle.
/**
*file: circle.c
*author : sri
*date : 2018-01-01
*description : program to find the area of a circle using the
radius r
*/
#include<stdio.h>
#define PI = 3.1416
float area(float r);
int main(void)
{
float r= 10;
printf(“Area :%.2f”,area®);
return 0;
}
float area(float r)
{
return PI * r * r;
}

The above code will give the following output. Area:

314.16

Different sections of the above code

Documentation:
This section contains a multi line comment describing the
code.

/**
*file: circle.c
*author : sri
*date : 2018-01-01
*description : program to find the area of a circle using the
radius r
*/
In C, we can create single line comment using two forward slash
// and we can create multi line comment using /*
*/
Comments are ignored by the compiler and is used to write notes
and document code.

Link :
This section includes header file.

#include<stdio.h>

We are including the stdio.h input/output header file from the C library.

Definition :
This section contains constant.

#define PI = 3.1416
In the above code we have created a constant PI and assigned
3.1416 to it.
The #define is a preprocessor compiler directive which is used to create
constants. We generally use uppercase letters to create constants. The
#define is not a statement and must not end with a ; semicolon.

Global declaration :
This section contains function declaration.

float area(float r);

We have declared an area function which takes a floating number


(i.e., number with decimal parts) as argument and returns floating
number.
main( ) function :
This section contains the main() function.

int main(void)
{
float r= 10;
printf(“Area :%.2f”,area);
return 0;
}

This is the main() function of the code. Inside this function we


have created a floating variable r and assigned 10 to it.
Then we have called the printf() function. The first argument
contains “Area: %.2f” which means we will print floating number
having only 2 decimal place. In the second argument we are calling
the area() function and passing the value of r to it.

Subprograms :
This section contains a subprogram, an area() function that is
called from the main() function.

float area(float r)
{
return PI * r * r;
}

This is the definition of the area() function. It receives the value of


radius in variable r and then returns the area of the circle using the
following formula PI*r*r.

Execution C Program - using TURBO C compiler


The following steps are followed to execute a C program using
Turbo C compiler.

(i) Creating the program


(ii) Compiling the program
(iii) Linking and running the program

(i) Creating the program


Double click the Turbo C icon present in the Window
XP desk top and open the Turbo C editor. In the editor
enter the program code and save the program.

General Form is:

filename.c

where

Filename - name of the program C


- file extension
This program is called source program

Example
#include<stdio.h>
main()
{

}
Store the program as Sample.C

(ii) Compiling the source program


Compilation is a process of converting the source program into
machine language program. Compile the created program using
compile option in Turbo C editor. If the source program is
syntax error free, the compiler translates the source program to
non- executable program called object program. The compiler
automatically names the object program.
General Form is :

filename.obj
where
filename - name of the source program obj
- file extension
Example - Sample.obj

(iii) Linking and running the object program


Linking is defined as a process of connecting other
programs and functions that are needed by our C program.
In Turbo C compiler, linking is carried out automatically
after compilation. The linking process automatically
converts the object program to an executable object
program and names the program. The general form is

filename.exe

where
filename – name of the source program exe –
file extension

Example – Sample.exe
Run the executable program using run option in TURBO C editor
to get the result for the program.
Flow Chart of the Program Execution Process:
C Tokens.

Character Set :
Its a set of characters that can be used to create values, variables,
expressions etc.
Following are the characters that we can use in C programming language.

Letters Uppercase A-Z


Lowercase a-z

Digits All decimal digits 0-9

Special Characters `~!@#$%^&*()_-+=


{}[]\:”;<>?./

White Space Blank Space, Horizontal tab,


Carriage Return, New Line,
Form feed

Token
The smallest individual unit in a program is known as
token.
Following are the tokens used in C programming language:
 Keywords
 Identifiers
 Constants
 Strings
 Special Symbols
 Operators

Keyword
Keywords are the words belonging to C-language. They have
standard predefined meaning. The users have no right to change its
meaning. Keywords should be written in lower case, and hence must not
be used as normal identifier name.

ANSI C Keywords : There are 32 keywords.

Auto break case char

Const continue default do

Double else enum extern

Float for goto if

Int long register return

Short signed sizeof static

Struct switch typedef union

unsigned void volatile while


Identifiers :
Identifiers are the fundamental building blocks of a program.
Identifiers are names given to variables, functions and arrays. These are
user defined names.
Identifiers name are user-defined and follow the following rules :

 First character of the identifier must be a letter or underscore


 Identifier names must only use letters (A-Z and a-z), digits (0-9)
and underscore _
 Can't use white spaces and keywords
 No special characters are allowed other than underscore.
 They are case sensitive. That is AA is different from aa.

Example: name, _gameStatus, is_game_over, stage99 etc.

Identifier Reason for Invalidity


AB. Special character period (.) not
9A allowed.
The first character must be an
auto
alphabet
Reserved word

Variables in C

A variable is a name of memory location. It is used to store data.


Its value can be changed and it can be reused many times.
It is a way to represent memory location through symbol so that it
can be easily identified.

General form is:

Data-type variable list;

Where,
Data-type - valid data type such as int,char etc.
Variable list - list of variables separated by comma

The example of declaring variable is given below:

1. int a;
2. float b;
3. char c;

Here, a, b, c are variables and int,float,char are data types.

We can also provide values while declaring the variables as given


below:

1. int a=10,b=20; //declaring 2 variable of integer type


2. float f=20.8;
3. char c='A';

Rules for defining variables

 A variable can have alphabets, digits and underscore.


 A variable name can start with alphabet and underscore only. It
can’t start with digit.
 No white space is allowed within variable name.
 A variable name must not be any reserved word or keyword e.g.,
int, float etc.,

Valid variable name:

1. int a;
2. int _ab;
3. int a30;

Invalid variable name:

1. int 2;
2. int a b;
3. int long;
Types of Variables in C

There are many types of variables in C

1. local variable
2. global variable
3. static variable
4. automatic variable
5. external variable

1. Local Variable:
A variable that is declared inside the function or block is called local
variable. it must be declared at the start of the block.
1. void function1() 2.
{
3. Int x=10; //local variable 4. }

You must have to initialize the local variable before it is used.

2. Global variable :
A variable that is declared outside the function or block is called
global variable. Any function can change the value of the global variable.
It is available to all the functions.It must be declared at the start of the
block.

int value=20 //global variable


void function1() 3.
{
int x=10; //local variable
}

1. Static Variable :

A variable that is declared with static keyword is called static variable.

It retains its value between multiple function calls.


void function1()
{
Int x=10; //local variable
static int y=10;//static variable
x=x+1;
y=y+1;
printf(“%d,%d”,x,y);
8. }
If you call this function many times, local variable will print the
same value for each function call e.g, 11,11,11 and so on. But static
variable will print the incremented value in each function call e.g.
11,12,13 and so on.

4. Automatic Variable :

All variables in C that is declared inside the block, are automatic


variables by default. By we can explicitly declare automatic variable using
auto keyword.

void main()
{
int x=10;//local variable (also automatic)
auto int y=20;//automatic variable
}

6. External Variable :
We can share a variable in multiple C source files by using external
variable. To declare a external variable, you need to use extern
keyword.
Myfile.h

Extern int x=10; // external variable(global)


Pgm1.c
#include “myfile.h”
#include<stdio.h>
Void printValue()
{
Printf(“Global variable : %d”, global_variable);
}

Difference between Variable and Identifier?


An Identifier is a name given to any variable, function, structure,
pointer or any other entity in a programming language. While a variable, as
we have just learned in this tutorial is a named memory location to store
data which is used in the program.

Identifier Variable

Identifier is the name given to a While, variable is used to


variable, function etc. name a memory location
which stores data.

An identifier can be a variable, but not All variable names are


all indentifiers are variables. identifiers.

Example: Example:
//avariable // int variable
int studytonight; int a;
//or, a function //float variable
int studytonight() Float a;
{

}
}

Constant :
A value that will never change throughout the execution of the
program is called a constant.
There are three types of constants:
(i) Numeric constant
(ii) Character constant
(iii) String constant
Numeric Constant:
A numeric constant is a constant made up of digits and some
special characters. There are two types of numeric constants. They are
(i) Integer or fixed point constant
(ii) Real or floating point constant
(i) Integer Constant:
Integer constant is a constant made up of digits without decimal
point. This can have values from -32768 to +32767.
Rules:
(i) An integer constant is formed with digits 0 to 9.
(ii) The constant can be preceded by + or – sign.
(iii) No special characters are allowed anywhere in the
constant.
There are three types of integer constants. They are
(i) Decimal integer constant
(ii) Octal integer constant
(iii) Hexadecimal integer constant
Decimal Integer Constant:
A decimal integer constant is made up of digits 0
to 9 in any combination. The first digit should not be zero.

Example:
1. The following are some valid decimal integer
constants:
10 -10 -5420 5743
2. The following are invalid decimal integer constants:

Consta Reason for Invalidity


5,734 Comma is not allowed
0452 The first digit should not be zero
15.03 Decimal point is not allowed
183 The sign should precede the

Octal Integer Constant:


An octal integer constant is made up of digits 0 to 7 in any
combination. To identify the constant as an octal constant it should
begin with 0.
Example:
1. The following are some valid octal integer constants: 0421
07562 0100
2. The following are invalid octal integer constants:

Consta Reason for Invalidity


5734 The first digit should be zero
082574 The digit 8 is not allowed
015.04 Decimal point is not allowed

Hexadecimal Integer Constant:


A decimal integer constant is made up of digits 0 to 9 an
alphabets A to Z in any combination. To identify
the constant as an hexadecimal integer constant it should start
with either OX or ox.

Example:
1. The following are some valid hexadecimal integer
constants:
OX532 OX1F ox1f
2. The following are invalid decimal integer constants:

Consta Reason for Invalidity


23A Should begin with OX
OX53.35C Decimal point is not allowed
OXAC23Z The character Z is not allowed

(ii) Real Constant:


Any number written with one decimal point is called
real or floating point constant.
Rules:
(i) A real constant is formed with the digits 0 to 9 and a
decimal point.
(ii) Digits before or after the decimal point can be
omitted.
(iii) A number can be preceded by + or – sign.
(iv) No special characters are used other than decimal point.
A real constant can be expressed in any one of the
following two forms
(i) Fractional form
(ii) Exponent form
Fractional form:
A number written with one decimal point is called a real
constant in fractional form.
Example:
1. The following are some valid real constants in
fractional form:
-0.157 .64 2.4
2. The following are invalid fractional real constants:

Consta Reason for Invalidity


153 No decimal point
16.47.57 Two decimal points are not
5/3 Special character is not allowed
12,543.83 Comma is not allowed

Exponent form:
Exponent form is used to represent very large and very
small real constants. The general form is

mantissa e or E exponent

Rules:
(i) The mantissa and exponent can have a positive or
negative sign.
(ii) Exponent should not have a decimal point.
(iii) Exponent must have atleast one digit.

Example:
1. The following are some valid real constants in
exponent form:
(a) 0.000002571 can be expressed as .2571e-5
(b) 3.14 can be expressed as .314E1
2. The following are invalid real constants in exponent form:

Const Reason for Invalidity


.840E.5 Exponent should not have decimal
50 Either a decimal point or an

Character constant:
There are two types of character constants. They are
(i) Direct
(ii) Escape Sequence
(i) Direct:
A direct character constant consists of a single character
enclosed with single quotation marks. This gives the integer
value of the enclosed character. This value is known as ASCII
value.
Example:

Co Value
‘A’ 65
‘0’ 48
‘%’ 37
‘a’ 97

Escape Sequence :
An escape sequence consists of more than one character within
single quotation marks. The first character These are special backslash
character constants.
Character Constant Description

'\0' null

'\n' New line

'\'' Single quote

'\"' Double quotes

'\a' Audible alert(bell)

'\b' Backspace

'\f' Form feed

'\r' Carriage return

'\t' Horizontal tab

'\v' Vertical tab

'\\' Backslash

'\/' Forward slash

Example: The following code will print "Hello World" and will move the
cursor to the next line because of the new line character '\n'.
printf(“Hello World \n”);

String constant
A string constant is a sequence of character enclosed with double
quotation marks.This can be form with digits, alphabets and special
characters.
Example
“NAGARCOIL” “13TH-MARCH” “12345” “23.567”

Difference between character constant and string constant


The character constant produces numeric value(ASCII) of the
character enclosed within single quote.
The string constant is a sequence of character enclosed within
double quotes.
Thus ‘B is not as same as “B”
Enumeration constants :

Keyword enum is used to define enumeration types.


For example:

enum color {yellow, green, black, white};

Here, color is a variable and yellow, green, black and white are the
enumeration constants having value 0, 1, 2 and 3 respectively.

3. Data Types
 C data types are defined as the data storage format that a variable can
store a data to perform a specific operation.
 Data types are used to define a variable before to use in a program.
 Size of variable, constant and array are determined by data types.
There are four data types in C language. They are,

Types Data Types

Basic data types int, char, float, double

Enumeration data type enum

Derived data type pointer, array, structure, union

Void data type void

Basic Data Types In C Language :


Integer Data Type :

 Integer data type allows a variable to store numeric values.


 The keyword “int” is used to refer integer data type.
 The storage size of int data type is 2 or 4 or 8 byte.(it’s depend
upon the processor in the CPU. if we are using 16 bit processor,
2 byte of memory will be allocated to int data type, like wise,
4byte(32 bit processor), 8 byte (64 bit processor)).
Note :

 We can’t store decimal values using int data type.


 If we use int data type to store decimal values, decimal
values will be truncated and we will get only whole number.

Character Data Type:


 Character data type allows a variable to store only one
character.
 Storage size of character data type is 1. We can store only
one character using character data type.
 “char” keyword is used to refer character data type.
 For example, ‘A’ can be stored using char datatype. You
can’t store more than one character using char data type.
FLOATING POINT DATA TYPE :
Floating point data type consists of 2 types. They are
1. Float
2. Double
1. Float :
 Float data type allows a variable to store decimal values.
 Storage size of float type is 4 byte.(it’s also varies
depend upon the processor).
 We can use up-to 6 digits after decimal using float data
type.
 For example, 10.456789 can be stored in a variable using
float type.
2. Double :
 Double data type is also same as float data type which
allows up-to 10 digits after decimal.
 The range for double data type is from 1E-37 to 1E+37.

#include <stdio.h>
#include <limits.h> int
main()
{
int a;
char b;
float c;
double d;
printf("Storage size for int data type:%d \n",sizeof(a));
printf("Storage size for char data type:%d \n",sizeof(b));
printf("Storage size for float data type:%d \n",sizeof(c));
printf("Storage size for double data type:%d\n",sizeof(d)); return 0;
}
OUTPUT :
Storage size for int data type : 4 Storage
size for char data type : 1 Storage size for
float data type : 4 Storage size for double
data type : 8

Enumeration Data Type In C Language :


 Enumeration data type consists of named integer
constants as a list.
 It start with 0 (zero) by default and value is incremented
by 1 for the sequential identifiers in the list.
 Syntax :

Enum identifier[optional{enumerator – list}];

Example :

#include<stdio.h>
int main()
{
num MONTH {Jan =0, Feb, Mar }; enum
MONTH month=Mar; if(month = = 0 )
printf(“value of Jan”); else
if(month = =1)
printf(“Month is Feb”);
if(month = = 2)
printf(“Month is Mar”);

}
e
Output :
Month is Mar

DERIVED DATA TYPE:


 Array, pointer, structure and union are called data type in
C language.

VOID DATA TYPE :


 Void is an empty data type that has no value.
 Used in Functions and Pointers.

Size and range of type on 16-bit machine

Type Size(bytes) Range

int or signed 2 -32,768 to 32767


int
unsigned 2 0 to 65535
int
short int or 1 -128 to 127
signed short
int
unsigned 1 0 to 255
short int
long int or 4 -2,147,483,648 to 2,147,483,647
signed long int
unsigned 4 0 to 4,294,967,295
long int

Float 4 3.4E-38 to 3.4E+38

double 8 1.7E-308 to 1.7E+308

long double 10 3.4E-4932 to 1.1E+4932

char or 1 -128 to 127


signed char

unsigned 1 1 to 255
char

Type casting :

Type casting is a way to convert a variable from one data type to


another data type. For example, if we want to store a long value into a
simple integer then we can typecast long to int. we can convert values
from one type to another explicitly using the cast operator. New data type
should be mentioned before the variable name or value in brackets which
to be typecast.

Example For Typecasting :

In the following program, 7/5 alone will produce integer value as


1. So, type cast is done before division to retain float value(1.4).
#include <stdio.h> int
main ()
{
float x;

x = (float) 7/5;

printf(“%f”,x);

Output :
1.400000

Type conversion in c can be classified into the following two types:


1. Implicit Type Conversion
2. Explicit Type Conversion

Implicit Type Conversion:


When the type conversion is performed automatically by
the compiler without programmers intervention, such type of
conversion is known as implicit type conversion or type
promotion.
Example :

int x; for(x=97;x<=122;x+
+)
{
Printf(“%c”,x); /* implicit casting from int to char
thanks to %c */
}
Explicit Type Conversion :
The type conversion performed by the programmer by posing the
data type of the expression of specific type is known as explicit
type conversion. The explicit type conversion is also known as
type casting.

General form of Type casting in C is:

(data_type)expression;

where,

data_type - any valid C data type, expression -

constant, variable or expression. For

example,

int x; for(x=97;x<=122;x+

+)

Printf(“%c”,(char)x); /* Explicit casting from

int to char */

The following rules have to be followed while converting the


expression from one type to another to avoid the loss of information:

1. All integer types to be converted to float.


2. All float types to be converted to double.
3. All character types to be converted to integer.
Example :

int x=7,y=5;

float z;

z=x/y; /* Here the value of z is 1 */

if we want to get the exact value of 7/5 then we need explicit


casting from int to float:

int x=7,y=5;

float z;

z=(float)x/(float)y; /* Here the value of z is 1.4 */

4. Operators
 The symbols which are used to perform logical and
mathematical operations in a C program are called C
operators.

 These C operators join individual constants and variables


to form expressions.

 Operators, functions, constants and variables are


combined together to form expressions.

 Consider the expression A + B * 5. where, +, * are


operators, A, B are variables, 5 is constant and A + B * 5
is an expression.
TYPES OF C OPERATORS:
C language offers many types of operators. They are,
1. Arithmetic operators
2. Relational operators
3. Logical operators
4. Bit wise operators
5. Assignment operators
6. Conditional operators (ternary operators)
7. Special operator
Arithmetic operators
Arithmetic operators are used to do arithmetic
calculations. There are two types
i) Binary operators
ii) Unary operators

(i) Binary operators


Binary operators need two operands for operations.
General form is:

Operand1 op operand2

Where,
Operand1,operand2 - valid constants or variables op
- binary operator

Different types of binary operators with example:

Operator Operation Example


+ Addition x=2+4

- Subtraction y=x-2
* Multiplication Z= 2*3
/ Division X=10/3=3 or 3.33
% (modulo Remainder after X= 7%2 = 1
operator) integer division

C supports all the basic arithmetic operators. The following table


shows all the basic arithmetic operators.

Operator Description

+ adds two operands

- subtract second operands from first

* multiply two operand

/ divide numerator by denominator

% remainder of division

++ Increment operator - increases integer value by one

-- Decrement operator - decreases integer value by one

Relational 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

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


operand

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

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(These are data
types, we will learn about them in the next tutorial).
Operator Description

& Bitwise AND

| Bitwise OR

^ Bitwise exclusive OR

<< left shift

>> right shift

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

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 operator, 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 have to be shifted. Both operands
have the same precedence.

Example :
a=0001000
b=2
a<<b=0100000
a>>b=0000010

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

Operator Description Example

= assigns values from right side a=b


operands to left side operand

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


and assign the result to left a=a+b

-= subtracts right operand from the left a-=b is same


operand and assign the result to left as a=a-b
operand

*= mutiply left operand with the right a*=b is same as


operand and assign the result to left a=a*b
operand

/= divides left operand with the right a/=b is same as


operand and assign the result to left a=a/b
operand

%= calculate modulus using two operands a%=b is


and assign the result to left operand same as
a=a%b
Conditional operator
The conditional operators in C language are known by two more
names

1. Ternary Operator
2. ? : Operator

It is actually the if condition that we use in C language decision making,


but using conditional operator, we turn the if condition statement into a
short and simple operator.
The syntax of a conditional operator is :
expression1 ? expression2: expression3

Explanation:

 The question mark "?" in the syntax represents the if part.


 The first expression (expression 1) generally returns either true or
false, based on which it is decided whether (expression 2) will be
executed or (expression 3)
 If (expression 1) returns true then the expression on the left side of
" : " i.e (expression 2) is executed.
 If (expression 1) returns false then the expression on the right
side of " : " i.e (expression 3) is executed.

Special operator

Operator Description Example

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


variable variable x

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


variable variable x

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


variable x
Expressions :
An expression is a linear combination of constants, variables and
operators. There are three types of expressions in C language. They are

(i) Arithmetic expression


(ii) Relational expression
(iii) Logical expression

Arithmetic expression :
Arithmetic expressions are formed by connecting constants or
variables by arithmetic operators.
General form is :

Constant (or) Variable Arithmetic operator Constant (or) variable

Example :
x+z, a+z-x, (x-y)/z, x+y/z, (x+y)/(Z+A)
There are three types of arithmetic expressions They are:

i. Integer expression
ii. Real expression
iii. Mixed mode expression
(i) Integer Expression
If the dat type of the variable on the left hand side of the expression
and the datatype of the variables on the right hand side of the expression
are of int type, then that expression is called integer expression
The general Form is:

int var1 = int var2 arithmetic operator int var3 arithmetic operator

Where
int - data type
var1,var2,var3 ---- - variables
arithmetic operator - +,-,*,/,%
The resultant value of the expression is of integer type.

Example
int a;
int b=10,c=20;
a=b+c The value of a is 30.

(ii) Real expression


If the data type of the variable on the left hand side of the
expression and the datatype of the variables on the right hand side of the
expression are of float type, then that expression is called real expression.
General form is:

Float var1 = float var2 arithmetic operator float var3 arithmetic operator
Where
int - data type
var1,var2,var3 ---- - variables
arithmetic operator - +,-,*,/,%
The resultant value of the expression is of real type.

Example
int a;
int b=15.5,c=19.5;
a=b+c The value of a is 35.0

(iii) Mixed mode expression


If the data type of the variable on the left hand side of the
expression and the data type of the variables on the right hand side of the
expression are of different types, then that expression is called mixed
mode expression.
The General form is:

Datatype var1 = datatype var2 arithmetic operator datatype var3

Where
int - data type
var1,var2,var3 ---- - variables
arithmetic operator - +,-,*,/,%
The resultant value of the expression is of real type.
Example

int a,h;
float c,d;
d=a+h-c;
Relational expression:
Relational expressions are formed by connecting constants or
variables or arithmetic expressions by relational operators.
General form is:

Constant (or) Constant (or)

Variable(or) Relational operator Variable(or)

Expression Expression

The value of the expression is either True or False.


Example
1. A==20 The answer is True if A equal 20 else False
2. A*A-B > C*C-D
The computer first evaluates the value of A*A-B and
then C*C-D. if the value of A*A-B is greater than C*C-
D the answer is True else False.
Logical Expression
Logical expressions are formed by connecting relational
expressions by logical operators.
The general form is:

Relational expression Logical operator Relational expression

The value of the expression is either True or False.


Example
(i) A>20 && B>25 - The result of this expression
is True if A is greater than 20 and B is greater than 25.
(ii) A>20 || B>25 - The result of this expression is True if
A is greater than 20 or B is greater than 25.

Type conversion in arithmetic expression


Type conversion is defined as a process of converting in an
expression from one dat type into another type during execution. There are
two types of convertion. They are

(i) Automatic type convertion


(ii) Explicit type convertion

(i) Automatic type convertion


If the operand in an expression are of data different data type, the
lower dat type operand(variable) is automatically converted to higher data
type before execution.This process of convertion is called automatic type
convertion.
Example

float a, b=5.7; int


c = 10;
a = b+c;
Here the value of c is automatically converted to float as 10.0 and added
to b. Therefore c=10.0+5.7=15.7
(ii) Explicit type conversion
The process of converting one data type operand into another data
type locally without affecting its data type in the
declaration is called explicit conversion.This is carried using a operator
called cast operator.
General form is:

(datatype) variable;

Where

Datatype - valid datatype called cast operator


Variable - valid user defined name
Example

(i) a = (int) 7.5;


7.5 is converted to 7

(ii) float a; int


b=10;
a=(float)b;

Here the value of b is explicitly converted to float and it is assigned to a.


But it wont affect the declaration of b. That is b remains integer. Therefore
a=10.0.
4.12 Operator precedence and associativity
The priority given to an operator in an expression during evaluation
is called operator precedence. All the operator in C has its own priority.
The operator with high priority will be evaluated first and so on.The
association of an operator with its operands is called
assocoativity.Associativity of an operator is either left to right operation
or right to left operation.
For example the associtivity of = operator is from left to right.
That is the right hand side value is assigned to left hand side variable.

Precedence levelof operator and its associativity.

Order Category Operator Operation Associativity

1 Highest ( ) Function L ? R
precedence [ ] call Left to
? Right
: :
.

2 Unary ! Logical R ? L
~ negation Right ->
+ (NOT) Left
- Bitwise
++ 1’s
- - compleme
& nt
* Unary
Size of plus
Unary
minus
Pre or
post
increment
Pre or
post
decrement

Address
Indirectio
n
Size of
operant in
bytes

3 Member .* Dereferen L?R


Access ?* ce
Dereferen
ce

4 Multiplicati * Multiply L?R


on / Divide
% Modulus

5 Additive + Binary L?R


- Plus
Binary
Minus

6 Shift << Shift Left L?R


>> Shift Right

7 Relational < Less than L ? R


<= Less than or
equal to
>
Greater than
>=
Greater than
or
equal to

8 Equality == Equal to L?R


Not Equal
!= to

9 Bitwise & Bitwise L?R


AAND AND

10 Bitwise ^ Bitwise L?R


XOR XOR

11 Bitwise OR | Bitwise L?R


OR

12 Logical && Logical L?R


AND AND

14 Conditional ?: Ternary R?L


Operator

15 Assignment = Assignme R?L


*= nt
Assign
%=
product
/= Assign
+= reminder
-= Assign
&= quotient
^= Assign sum
|= Assign
difference
<<=
>>=
Assign
bitwise
AND
Assign
bitwise
XOR
Assign
bitwise
OR
Assign left
shift
Assign
right shift

16 Comma , Evaluate L?R

5. Managing Input/Output Operations:


Input and output functions are used to transfer information
between the computer and the input,output devices such as
keyboard,monitor.
Clanguage does not contain any input and output
statements. But all input and output operations are carried through the
input and output function calls. All standard input,output functions are
present in the header file <stdio.h> and it should be included in the
program.
There are two types of input/output functions.They are:

(i) Formatted input/output functions


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

 Field (or format) specifications, consisting of conversion


character %, a data type character, and an optional number,
specifying the field width.
 Blanks, tabs, or newlines.

(a) Inputting integer numbers


The field specification for reading an integer number is

%w d
The percentage sign (%) indicates that a conversion specification
follows. w is an integer number that specifies the field width of the
number to be read and d, known as data type character, the number to be
read is in integer mode.
Consider the following example:
scanf(“%2d %5d”,&num1, &num2); Data
line:
52 31456

The value 52 is assigned to num1 and 31456 to num2. Suppose the input
data is as follows:
31456 52
The num1 will assign 31 (because %2d) and num2 will be assigned 456
(unread part of 31456). The value 50 that is unread will be assigned to
the first variable in the next scanf call. This kind of error may be
eliminated if we use the field specification without the field width. That is
the statement:

scanf(“%d %d”,&num1, &num2);


will read the data

31456 52
correctly and assign 31456 to num1 and 52 to num2.
An input field may be skipped by specifying * in the place of field
width.
For example:
scanf(“%d %*d %d”,&a, &b);
will assign data

121 456 789


As follow:
121 to a
456 skipped (because of *)
789 to b
Program

/*Reading integer numbers*/


#include<stdio.h>
#include<conio.h>
void main()
{
int a, ,b, c, x, y, z;
int p, q, r;
printf(“Enter three integer numbers \n”);
scanf(“%d %*d %d”,&a, &b, &c); printf(“%d
%d %d \n \n”,a, b, c); printf(“Enter two 4-digit
numbers \n”); scanf(“%2d %4d ”,&x, &y);
printf(“%d %d \n \n”,x, y); printf(“Enter two
integer numbers \n”); scanf(“%d %d”,&a,
&x);
printf(“%d %d \n \n”,a, x); printf(“Enter a
nine digit numbers \n”); scanf(“%3d %4d
%3d”,&p, &q, &r); printf(“%d %d %d \n
\n”,p, q, r);
printf(“Enter two three digit numbers \n”);
scanf(“%d %d”,&x, &y);
printf(“%d %d \n \n”,x, y);
}
Output
Enter three integer numbers 1 2
3
1 3 –3577
Enter two 4-digit numbers
6789 4321
67 89
Enter two integer numbers 44
66
4321 44
Enter a nine digit numbers
123456789
66 1234 567
Enter two three digit numbers 123
456
89 123
(b) Inputting Real Numbers
Unlike integer numbers, the field width of real numbers is not to be
specified and therefore scanf reads real numbers using simple specification
%f for both the notations, namely, decimal point notation and exponential
notation.
For example the statement:
scanf(“%f %f %f”, &x, &y, &z);
with the input data
435.25 42.31E-1 687
Will assign the value 435.25 to x, 4.231to y, and 687.0 to z.
If the number to be read is of double type, then the
specification should be %lf instead of simple %f.
(c) Inputting Character Strings
Following are the specifications for reading character strings:
%ws or %wc
Some versions of scanf support the following conversion
specifications for strings:
%[characters] and %[^characters]
The specification %[characters] means that only the characters
specified within the brackets are permissible in the input string. If the input
string contains any other character, the string will be terminated at the first
encounter of such a character. The specification %[^characters]does
exactly the reverse. That is, the characters specified after the circumflex
(^) are not permitted in the input string.

(d) Reading Mixed Data Types


It is possible to use one scanf statement to input a data line
containing mixed mode data. In such cases, it should be ensured that
the input data items match the control
specifications in order and type.for example:
scanf(“%d %c %f %s”,&count, &code, &ratio,
&name);
Table 5.1 will show some of the commonly used
scanf formatted codes:

Table 5.1 commanly used Scanf Format Codes

Code Meaning

%c Read 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)

Points To Remember while using scanf

 All function arguments, except the control string, must be pointers


to variables (use &).
 Format specifications contained in the control string should
match the arguments in order.
 Input data items must be separated by spaces and must match the
variables receiving the input in the same order.
 The reading will be terminated, when scanf encounters an ‘invalid
mismatch’ of data or a character that is not valid for the value
being read.
 When searching for a value, scanf ignores line boundaries
and simply looks for the next appropriate character.
 Any unread data items in a line will be considered as a part of
the data input line to the next scanf call.
 When the field width specifier w is used, it should be large
enough to contain the input data size.
FORMATTED OUTPUT
The printf statement provides certain features that can be
effectively exploited to control the alignment and spacing of print-outs on
the screen. The general form of printf statement is
printf(“control string”,arg1, arg2…argn);
Control string consists of three types of items:
 Characters that will be printed on the screen as they appear.
 Format specifications that define the output format for display
of each item.
 Escape sequence characters such as \n, \t and \b
The control string indicates how many argument follows and what their
types are. The arguments arg1, arg2, …, argn are the variables whose
values are formatted and printed according to the specification of the
control string. The arguments should match in number, order and type with
the format specifications.
A simple formate specification has the following form:
% w.p type-spcifier
where w is an integer number that specifies the total number of columns
for the output value and p is another integer number that specifies number
of digits to right of the decimal point for real number. Both w and p are
optional.
(a) Output of Integer Numbers
The format specification for printing an integer number is
%w d

where w specifies the minimum field width for the output.


However, if the number is greater than the specified field width, it will be
printed in full, overriding the minimum specification. d specifies the
value to be printed is an integer. The number is right-justified in the given
field width. Leading blanks will appear as necessary. The following
example will output the number 6789 under different formats:
Format Output

printf(“%d”,6789);

6 7 8 9

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

printf(“%2d”,6789);
6 7 8 9

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

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

(b) Output of Real Numbers


The output of real numbers may be displayed in decimal notation
using the following format specification:
%w.p f
The integer w indicates the minimum number of positions that are
to be used for the display of the value and the integer p indicates the
number of digits to be displayed after the decimal point.
We can also display real numbers in exponential notation by using the
specification:
%w.p e
The following example will illustrate the output of the number y =
56.4567 under different format specification:

Format Output

printf(“%7.4f”,y);
5 6 . 4 5 6 7

printf(“%7.2f”,y);
5 6 . 4 6

printf(“%-7.2f”,y); 5 6 . 4 6

5 6 . 4 5 6 7
printf(“%f”,y);

5 . 6 4 E + 0 1
printf(“%10.2e”,y);

printf(“%11.4 e”,- y); - 5 . 6 4 5 6 E + 0 1


printf(“%-
10.2e”,y); 5 . 6 4 E + 0 1

printf(“%e”,y);
5 . 6 4 5 6 7 0 E + 0 1

(c) Printing of Single Character:


A single character can be displayed in a desired position using the
format:
%wc
The character will be displayed right-justified in the field of w columns.
We can make the display left-justified by placing a minus sign before the
integer w. The default value for w is 1.
(d) Printing of Strings
The format specification for outputting strings is of the form:
%w.ps
where w specifies the field width for the display and p indicates that only
first p characters of the string are to be displayed. The display is right-
justified.
(e) Mixed Data Output
It is permitted to mix data types in one printf statements. For example
the statement of the following type
printf(“%d %f %s %c”,a, b, c, d);
is valid. As printf uses its control string to decide how many variables to
be printed and what their types are. Therefore, the formate specification
should match the variable in number, order and type.
Table 5.1 will show some of the commonly used
printf formatted codes:
Table 5.1 commanly used Printf Format Codes

Code Meaning

%c Print a single character

%d Print a decimal integer

%e Print a floating point value in exponent form

%f Print a floating point value without exponent

%g Print a floating point value either e-type or f-type

%i Print a signed decimal integer

%o Print an octal integer, without leading zero

%s Print a string

%u Print an unsigned decimal integer

%x Print a hexadecimal integer

The following letters may be used as prefix for certain


conversion characters.
h for short integer
l for long integer or double
L for long double
Table 5.3 will show some of the commonly used
output formatted flags:
Table 5.3 commanly used output Format flags

Flag Meaning

Output is left justified with in the field.


- Remaining field will be blank.

+ + or – will precede the sign numeric item.

Causes octal and hex items to be presented by O and


#(with o or x) Ox, respectib\vely.

Causes the decimal point to be presented in all floating


point numbers, even if it is whole number. Also
#(with e, f or g)
prevents the truncation of trailing zero in g-type
conversion.

Unformatted input/output function


Unformatted input functions:
The following are the commonly used unformatted input
functions

i. getchar()
ii. gets()
(i) getchar()
Reading a single character can be done using the function
getchar(). This can also be done with the help of the scanf function.
The getchar takes the following form:

variable_name = getchar();

variable_name is valid C name that has been declared as char


type. When this statement is encountered, the computer will waits untill a
key is pressed and then assigns the character as a value to getchar
function. Since getchar is used on right hand side of assignment
statement, the character value of getchar is in turn assigned to the
variable on the left. For

example:
char ch;
ch = getchar();
will assign “g” to the variable ch when we press the key g on the
keyboard.
The getchar function may be called successively to read the characters in a
line of text. For example, the following program segment reads characters
from keyboard one after the another until the return key is pressed

----------
----------
----------
char ch;
ch=’ ‘;
while(ch!= ‘\n’)
{
ch = getchar();
}
----------
----------
----------
(ii) gets()
This function is used to read a string of characters until a
new line character ‘\n’ is entered (return key).The general form is:

gets(variable-name);
where
variable name - valid C variable
Rules

1. Variable name present inside the parantheses should be declared


previously.
2. Variable name should be of array of character type.
3. get() function is a part of input/output library.so the header file
stdio.h should be included in the program.
4.

Example
char name[15];
gets(name);
if the input string is - SRI UMAIYAL
The whole string will be read into the memory and is shown below

S R I U M A I Y A L \0

Unformatted output functions:


The following are the commonly used unformatted output
functions.
(i) putchar()
(ii)puts()
i. putchar()

Like getchar, there is a function called putchar for writing a


character one at a time to the screen, it takes the form as shown
below:
putchar(variable_name)
where variable_name is a type char variable containing character.
This statement display the character contained in variable_name at
the screen. For example the statements:
ans = ‘y’;
putchar(ans);
will display the character Y on the screen. The statement
putchar(‘\n’) would cause the curser on the screen to move to the
beginning of the next line.
ii. puts()

puts() function is used to display strings on the terminal.


The general form is:

puts(variablename);

where

variablename - valid C variable


Rules
(i) A string value should be assigned to the array of
character variable name inside the paranthessis.
(ii) puts() function is a part of input/output library.So the
header file stdio.h should be included in the program.

Example
char name[4];
gets(name); // give the input as Rani. puts(name);
The output is Rani.

68
DECISION MAKING AND BRANCHING
6. Control Statements
Control statements enable us to specify the flow of
program control; ie, the order in which the instructions in a program must
be executed. They make it possible to make decisions, to perform tasks
repeatedly or to jump from one section of code to another. In other words
in some situations we may have to change the order of execution of
statements based on certain conditions , or repeat a group of statements
until certain specified conditions are met. For these situation C provides
decision making statements also know as control statements.
C language supports the following statements known
as control or decision making statements.
1. if statement
2. switch statement
3. Conditional operator statement
4. goto statement

CONDITIONAL STATEMENTS
IF Statement
The if statement is used to control the flow of execution of
statements.
Syntax :

if(test expression)

It allows the computer to evaluate the expression first and then,


depending on whether the value of the expression is ‘true’ or ‘false’, it
transfers the control to a particular statement.

69
Example:
if(bank balance is zero)
Borrow money
The if statement may be implemented in different forms depending
on the complexity of conditions to be tested.
1. Simple if statement
2. if…..else statement
3. Nested if…..else statement
4. elseif ladder
SIMPLE IF Statement
Simple if statement is used to execute or skip one statement
or group of statements for a particular condition.

The general form is:

70
If(test exprn)
{
statement-block;
}
statement-x;

The general form of a simple if statement is The ‘statement- block’ may


be a single statement or a group of statement. If the test expression is true,
the statement-block will be executed; otherwise the statement-block will
be skipped and the execution will jump to the statement-x.
Example:
if(category = = SPORTS)
{
marks = marks + bonus_marks;
}
printf(“%f “,marks);
……….
……….
IF…ELSE Statement
The if….else statement is an extension of simple if
statement.if…..else statement is used to execute one group of statements if
the test condition is true or other group if the test condition is false.
The general form is

71
72
if(test expression)
{
True-block statement(s);
}
else
{
False-block statement(s);

If the test expression is true, then the true block statements are executed
and the control is transferred to statement-x; if the value is false, the false
block statement will be executed and the control is transferred to
statement-x.

72
Example:
………
……… if(code
==1) boy = boy
+ 1; if(code ==
2) girl =girl + 1;

………
………
NESTING OF IF…..ELSE STATEMENTS
When a series of decisions are involved, we may have to use more
than one if….else
statements, in nested form as follows.

If(test condition 1)
{
if(test condition 2)
{
statement-1;
}
else
{
statement-2;
}
}
else
{
statement-3;

73
When this statement is executed, the computer first evaluates value of test
condition1. If it is false control will be the transferred to statement-3. If it is
true test condition2 is evaluated. If it is true statement-1 is executed and control
is transferred to statement-x else statement-2 is executed and control is
transferred to statement-x.

Program
/*Selecting the largest of three values*/ void
main()
{
float A, B, C;
printf(“Enter three values \n”);
scanf(“%f %f %f ”,&A, &B, &C);
printf(“\nLargest value is:”);
if(A > B)
{
if(A > C)
printf(“%f \n”,A);
else
printf(“%f \n”,C);
}
else
{
if(C > B)
printf(“%f \n”,C);
else
printf(“%f \n”,B);
}
}
OUTPUT
Enter three values:
5 8 24
Largest value is 2

ELSE….IF LADDER
else……if ladder statement is used to take multiway decision.This
statement is formed by joining if…..else statements in which each
else contains another if…..else.
The general form is

If(condn 1) Statement-1; else if (condn 2) statement-2; else if (condn 3) statement-3;


……….
……….
else if (condn n) statement-n; else
default statement;

Computer execute these statements from top to bottom. If a true test


condition is found, the statement block associated with its executed. Then
the control is transferred to the next statement. When all the test conditions
are false, then the final else containing the default statement will be
executed.
Program
/*Use of else if ladder*/
void main()
{
int units, cno;
float charges;
printf(“Enter customer no. and units consumed \n”);
scanf(“%d %d”,&cno, &units );
if(units <= 200) charges = 0.5 * units; else if(units <= 400)
charges = 100+ 0.65 * (units – 200) else
if (units <= 600)
charges = 230 + 0.8 * (units – 400)
else
charges = 390 + (units – 600);
printf(“\n \ncustomer no =%d,charges =%.2f \n”,cno,charges);
}

OUTPUT
Enter customer no. and units consumed 101 150
Customer no=101 charges = 75.00

SWITCH STATEMENT
Switch statement is an extension of if..else statement. It permits
any number of branches. When this statement is executed the
computer, first evaluates the value of the expression in the keyword
switch. This value is successively compared with the case label1,
label2 … labeln.

If a case label matches with the value, the statement block


associated with the case label is executed. Then the control is
transferred to the next statement. if none of the case matches with the
value the default statement block is executed.
The general form of switch statement is:

switch ( integer expression )


{
case constant 1 : do this ;
case constant 2 : do this ;
case constant 3 : do this ;
default :

Rules:
 The expression should be placed in parentheses.
 The value of the expression should be an integer.
 The body of the switch statement should be enclosed within {}
brackets.
 Case label should terminate with a colon.
 Break statement is a must and causes immediate exit from switch
statement.if it is not included the statements below the matched
case will be executed.
Example

………
………
index = marks / 10;
switch(index)
{
case 10:
case 9:
case 8:
grade = “Honours”;
break;
case 7:

case 6:
grade = “first division”;
break;
case 5:
grade = “second division”;
break;
case 4:
grade = “third division”;
break;
default:
grade = “first division”; break; }
printf(“%s \n”,grade);
THE ?: OPERATOR
The C language has an unusual operator, useful for making
two-way decisions. This operator is a combination of ? and : and
takes three operands. It is of the form:

exp1 ? exp2 : exp 3

Here exp1 is evaluated first. If it is true then the expression exp2 is


evaluated and becomes the value of the expression. If exp1 is false then
exp3 is evaluated and its value becomes the value of the expression. For
example:
if(x < 0)
flag = 0;
else

flag = 1;
can be written as:
flag = (x < 0)? 0 : 1;

THE GOTO STATEMENT

C supports the goto statement to branch unconditionally from one


point of the program to nother. The goto requires a label in order to
identify the place where the branch is to be made. A label is any valid
variable name and must be followed by a colon.
The general from is:

gotolabel;
label : statements;

Rules

 Label is valid C identifier


 A colon should follow label
 No need to declare labels

Note: A label can be anywhere in the program, either before or after the
goto label;statement.
Example of goto label statement: void
main()
{

double x, y;
read:
scanf(“%f”,&x);
if(x < 0)
goto read; y
= sqrt(x);
printf(“%f %f \n”,x, y);
goto read;
}
Break statement
Break statement is used to exit from a loop while the test condition
is true. This statement can be used within a for, while, do-while or switch
statement.
The general form is

break;
When the break statement is executed inside a loop,the execution of the
loop is terminated and the program continues with the statement following
the loop.
Example

While(condition)
{
…….
…….
If(condition)
{
……..
…….
break;
}
………
}
Next statement

Continue statement
The statements after the keyword continue will be skipped and the
control is transferred to the beginning of the loop.The general form is

continue;
Example
for(i=1;a<=100;++i)
{
scanf(“%f”, &a);
if(a<0)
{
prints(“Error”);
continue;
}
………………
………………
Statements;
…………..
…………..
}
During execution if the value of a negative, the statements below the
keyword continue is skipped and the control is transferred to the beginning
of the loop.

7. Looping statements
The versatility of the computer lies in its ability to perform a set of
instructions repeatedly. This involves repeating some portion of the
program either a specified number of times or until a particular condition
is being satisfied. This repetitive operation is done through a loop control
instruction.
There are three methods by way of which we can repeat a part of a
program. They are:

 while statement
 do-while statement
 for statement

A program loop therefore consists of two segments:

 Body of the loop


 control statement
The control statement tests certain conditions and then directs the
repeated execution of the statements contained in the body of the loop.
In looping process in general would include the following four
steps:

 Setting and initialization of a counter


 Execution of the statements in the loop
 Test for a specified conditions for the execution of the loop
 Incrementing the counter

While Statement(Entry Controll Loop)


When in a program a single statement or a group of statements are
to be executed repeatedly depending upon certain test condition, then
while statement is used.
The syntax is as follows:

while (test condition)


{
body_of_the_loop;
}

When this statement is executed, the computer first evaluates the


test condition. If the value is false, the control is transferred to next
statement. If the value is true, then the body of the loop is executed
repeatedly until the test condition becomes false. when the test condition
becomes false the control is transferred to next statement.
The while loop statement
Write a program to calculate the factorial of a given input natural
number.
/* Program to calculate factorial of given number */
#include <stdio.h>
#include <math.h>
#include <stdio.h>
void main( )
{
int x;
long int fact = 1;
printf(“Enter any number to find factorial:\n”); /*read the
number*/
scanf(“%d”,&x);
while (x > 0)
{
fact = fact * x; /* factorial calculation*/ x=x-
1;
}

printf(“Factorial is %ld”,fact);
}

The do...while Loop(Exit Control Loop)


There is another loop control structure which is very similar to the
while statement – called as the do.. while statement. The only difference is
that the expression which determines whether to carry on looping is
evaluated at the end of each loop.
The syntax is as follows:

do
{
statement(s);
} while(test condition);

In do-while loop, the body of loop is executed at least once before


the condition is evaluated. Then the loop repeats body as long as condition
is true. However, in while loop, the
statement doesn’t execute the body of the loop even once the condition is
false. That is why do-while loop is also called exit- control loop.

The do…while statement


Write a program to print first ten even natural numbers.
/* Program to print first ten even natural numbers */
#include <stdio.h>
void main()

{
int i=0;
int j=2;
do
{
printf(“%d”,j);
j =j+2;
i=i+1;
} while (i<10);
}
OUTPUT
2 4 6 8 10 12 14 16 18 20

The for Loop(Entry Control Loop)


for statement makes it more convenient to count iterations of a loop
and works well where the number of iterations of the loop is known before
the loop is entered.

The syntax is as follows:

for (initialization; test condition; increment or decrement)


{
Statement(s);
}

Where
Control variable - to control the loop
Test condition - to check the control variable.
according to this the loop is executed or not.
Increment/decrement - to change the value of the
control variable.
When the for statement is executed the value of the control variable
is initialized and tested with the test condition. if the value of the test
condition is true, the body of the loop will be executed and the control
variable is incremented or decremented. When the test condition becomes
false the control is transferred to the next statement. The body of the loop
is executed repeatedly as long as the test value is true.

The for statement


Let us consider a program to illustrate for loop, Write a program to print first n
natural numbers.

/* Program to print first n natural numbers */


#include <stdio.h>
void main( )
{
int i,n;
printf(“Enter value of n \n”);
scanf(“%d”,&n);
printf(“\nThe first %d natural numbers are :\n”, n); for
(i=1;i<=n;++i)
{
printf(“%d”,i);
}
}
OUTPUT
Enter value of n 6
The first 6 natural numbers are:
123456
The three statements inside the braces of a for loop usually meant
for one activity each, however any of them can be left blank also. More
than one control variables can be initialized but should be separated by
comma.
Various forms of loop statements can be:
(a). for(; condition; increment/decrement) body;
A blank first statement will mean no initialization.
(b). for (initialization;condition;)
body;
A blank last statement will mean no running
increment/decrement.
(c). for (initialization;;increment/decrement) body;
A blank second conditional statement means no test condition to control
the exit from the loop. So, in the absence of second statement, it is
required to test the condition inside the loop otherwise it results in an
infinite loop where the control never exits from the loop.
(d). for (;;increment/decrement)
body;
Initialization is required to be done before the loop and test condition
is checked inside the loop.
(e). for (initialization;;)
body;
Test condition and control variable increment/decrement is to be done
inside the body of the loop.
(f). for (;condition;)
body;
Initialization is required to be done before the loop and control variable
increment/decrement is to be done inside the body of the loop.
(g). for (;;;)
body;
Initialization is required to be done before the loop, test condition and
control variable increment/decrement is to be done inside the body of
the loop.
The Nested Loops
C allows loops to be nested, that is, one loop may be inside
another. The program given below illustrates the nesting of loops.
Let us consider a program to illustrate nested loops,
Write a program to generate the following pattern given below: 1
12
123
1234
12345
/* Program to print the pattern */
#include <stdio.h>
void main( )
{
int i,j;
for (i=1;i<=4;++i)
{
printf("%d\n",i);
for(j=1;j<=i;++j)
{
printf("%d\t",j); }}}

Here, an inner for loop is written inside the outer for loop. For every
value of i, j takes the value from 1 to i and then value of i is incremented
and next iteration of outer loop starts ranging j value from 1 to i.
8. Arrays in C
An array is defined as a group of related data items stored in a
single variable name.
Example where arrays are used,

 to store list of Employee or Student names,


 to store marks of students,
 or to store list of numbers or characters etc.
One Dimensional Arrays
An array name with only one subscript is known as one
dimensional array. General form of array declaration is,

Example :

data-type array-name[subscript]

Subscript - an integer from 0 to n. int arr[10];

Here int is the data type, arr is the name of the array and 10 is the
size of array. It means array arr can only contain 10 elements of int type.
Index of an array starts from 0 to size-1 i.e first element of arr
array will be stored at arr[0] address and the last element will occupy
arr[9].
Rules
i) The subscript is always an integer
ii) The subscript value cannot be negative
iii) The subscript must be given within square brackets
after the array name.
iv) If there are more than one subscript each should be
given in separate square brackets.
v) Subscripts can be integer variables or
expressions that give integers.
Array initialization
After an array is declared it must be initialized. Otherwise, it will
contain garbage value(any random value). An array can be initialized at
either compile time or at runtime.
The process of assigning initial values to 1-D arrays during
declaration is called array initialliation.The general form is

Static data-type array-name[size]={ list of values};

Where
Static - keyword
Data-type - type of data found in the array. e.g
int,float etc.
Array-name - valid C variable name
Size - Number of contiguous locations in
the memory to be reserved.
List of values - initial values to be given to the
array.This value should be separated
by Commas.
Example
i) Static int age[2]={10,20};

age[0]= 10;
age[1]= 20;

ii) Static int age[4] = {10,20};

age[0]=10;
age[1]=20;
age[2]=0;
age[3]=0;

Example for One dimensional array(for reading and writing)


Sorting values program:

……………..
………………
int a[10];
Reading
for(i=0;i<10;i++)
{
scanf(“%d”, &a[i]);
}
…………….
…………….

for(i=0;i<10;i++)
{
Writing
Printf(“%d”, a[i]);
}
…………..
……………
Two dimensional Arrays
C language supports multidimensional arrays also. The simplest
form of a multidimensional array is the two-dimensional array. Both
the row's and column's index begins from 0. In other words an array
with two subscripts is known as two dimensional array. The general
form is

array-name[subscript1] [subscript2]

Where

subscript1 - row number.


subscript2 - column number.
Example :

int arr[10][20];
arr is an integer array containing 10 rows and 20 columns.
Rules
i) Array name should be a valid C-variable.
ii) Array name should be unique.
iii) The elements in the array should be of same type.
That is if an array is declared as integer, it cannot
contain elements that are not integer.
vi) The size of the array is got by multiplying the row size
and column size.
Example:
int mark[3][2]
mark is a two dimensional array with 3 rows and 2 columns. It has a
total of 6 (3 x 2) locations.
(a)1
0 mark[0][0] mark[0][1]

1 mark[1][0] mark[1][1]
2 mark[2][0] mark[2][1]

Example for Two dimensional array(for reading and writing)


Sorting values program:
……………..
……………… int
a[10][10];
for(i=0;i<10;i++)
{
for(j=0;j<10;j++)
Reading
{
scanf(“%d”, &a[i][j]);
}
}
……………..
……………… int
a[10][10];
for(i=0;i<10;i++)
{
for(j=0;j<10;j++)
Writing
{
printf(“%d”, a[i][j]);
}
}
Multidimensional Array:
Multidimensional arrays are arrays with three or more
dimensions. The general form is

data-type array-name[s1][ s2] [ s3]…[si];

Where
si – size of the ith dimension.

Example:
int mark[2][3][4];
This declares mark as a three dimensional integer array containing 24 (2 x
3 x 4) elements of integer type.

Strings:

A string is a sequence of characters enclosed within double


quotes. A string is terminated by a null character ‘\0’.

Declaring string variable

A string variable should be declared as a character array.

The general form is

char variablename[size];

Where
char – datatype
size – maximum number of characters in the string including
‘\0’.
Example:
char city[10];

This declares city as a string variable having maximum of 10


characters including the last character ‘\0’.

Initializing string variable: The


general form is

static char variablename[size] = string;

Where
static - keyword or storage class
char - data type variable
name - valid C variable
size - maximum number of characters plus
one.
string - valid string

Example:

static char city[7] = “CUMBUM”;

This declares city as a string variable having 7 characters and is stored as


shown below.

city[0] city[1] city[2]


city[3] city[4] city[5]
city[6]

C U M
B U M \0
Reading strings

We can read a character or strings using following


functions:
i) scanf
ii) getchar()
iii) gets()

scanf function :
format conversion ”%s” can be used in scanf for reading
strings not containing white spaces The general form is:

scanf("%s", variablename)

Where

% -convertion specification indicator s -


type specifier
variablename - valid C variable

Example
char name[15];
scanf(“%s”, name);
Input is : Sri Umaiyal
The string Sri only read into memory,because of the
blankspace after the word Sri. Here, the input string is treated as two
strings namely Sri and Umaiyal.
getchar function
This is a predefined function in C language which is available in
stdio.h header file. Using this function we can read a single character
from keyboard and store in character variable. When we want to read a
number of character form keyboard the store all the data in a character
array.
The general form is:
char variablename;
variablename=getch();
Note: getchar function has no any parameters.

gets

This is a predefined function in C language which is


available in stdio.h header file. This function is used to read a single
string from keyboard until a new line character ‘\n’ is entered.
The general form is :
gets(variable);
Example
char name[15];
gets(name); Input
string is :
“Sri Umaiyal”
The whole string will be read into the memory and is shown below

S r i U M A I Y A L \0
Writing strings

We can write or display a character or strings using


following functions:
i) printf
ii) putchar()
iii) puts()

printf function

format conversion ”%s” can be used in printf for display strings


on the terminal. The general form is:

printf("%s", variablename)

Where

% - convertion specification indicator


s - type specifier
variablename - valid C variable

putchar

putchar function is a same as getchar but this function is used for


display a character value of screen or console. This function must be
take one parameters.
Example
char ch=’A’;
putchar(ch);
putchar is equivalent to printf("%c",ch);

puts

puts is same as gets function but this is used to display a


string on screen or console. This function takes single arguments.
The general form is:

Where puts(variable);

variable - valid C variable

Standard String Handling Functions:

The standard string handling functions are:

1. strlen() :
This function is used to find out the number of characters in the
given string. The syntax is

n = strlen(string);

Where
n - integer variable which receives the
length of the string.

string - valid string variable or constant.


The counting ends at the terminator ‘\0’.

Example:

strlen(“COLLEGE”) = 7

2. strcpy() :

This function is used to copy the content of one string


into another string. The syntax is

strcpy(string1, string2);

Where
string1, string2 - valid strings.

When this function is executed the contents of string2 are copied


into string1.

Example:
string2 = “COLLEGE”;
strcpy(string1, string2);
The output is
string1 = “COLLEGE”

3. strcat() :
This function is used to join two strings. The syntax
is
strcat(string1, string2);

Where

string1, string2 - valid strings.

When this function is executed the contents of string2 are


joined with string1 and the character ‘\0’ is placed at the end of the
new string string1.

Example:
string1 = “ARTS” string2 =
“COLLEGE”;
strcat(string1, string2);

The output is
string1 = “ARTSCOLLEGE”
string2 = “COLLEGE”

4. strcmp() :
This function is used to compare two strings. The syntax
is

strcmp(string1, string2);
Where
string1, string2 - valid strings.

If the two strings are equal the value of the function will be
zero. If string1 is greater tan string2, the value will be positive else
negative.

Example:
string1 = “LION”
string2 = “TIGER”;
strcmp(string1, string2);

The output is
-1 (i.e. string2 is greater than string1)

5. strrev() :
This function is used to reverse a string. The syntax
is
n = strrev(string);

Where
n - string variable to hold the reversed string. string
- valid string variable which contains the
string to be reversed.

Example:
n = strrev(“COLLEGE”);
The output is
n = “EGELLOC”
2 MARKS:

1. Write the structure of a c program.


2. What is static variable?
3. What is meaning of void?
4. How many bytes does double occupies?
5. What is the symbol for bitwise operator?
6. List out the logical operators in C.
7. Explain any two keywords with example
8. Define constant.Give example
9. What are the three basic data types
10.Explain the increment operator
11.Explain the syntax of IF…. ELSE statement 12.What is the
use of goto statement?
13. What is a string?
14. What is the use of break statement
15.Metion the relational operators in C.
16.Write the syntax of scanf and printf.
17.Syntax of putchar() and getchar().
18.What is character set?
19.What is Identifiers?
20.What is the function used to read a single character? 21.What is
conditional operatot?
22.Any four mathematical function. 23.What is
formatting an output?
24.Write the rules for defining real constants. 25.Write down
the user defined data types in C. 26.Write the syntax of switch
statement.
27. Write down the limitations of using getchar and scanf function
for reading strings?
28. Write the syntax of if…else statement with example. 29.List
out any two features of C.
30.What is meant by typecasting? 31.What is
the use of break statement? 32.What are
enumerated data types?
5 MARKS
1. Discuss the arithmetic operators in C.
2. Briefly explain the syntax of putch and getch
3. List the character set of C.
4. Discuss any four basic data types.
5. Explain IF and IF…Else IF statements.
6. Discuss control characters in detail.
7. Explain the structure of a C program. Give the Example.
8. Write down the variable naming rules with eg.
9. Explain the SWITCH …. CASE statements. 10.Write a short
notes on Enumerated Data types. 11.Write a program to compute
the factorial of a given
number.
12. Explain about C tokens in details.
13. Explain precedence of operators with example.
14.What is the purpose of GOTO statements?
15.Write a about short note on scanf() function. 16.Explain the
various forms of IF statements with suitable
example.
17. Write a C program to find the area and circumference of a circle.
18. Explain about constants and variables with examples.
19.Write a C program to find the sum of first 10 natural
numbers(1+2+-------+10).
20.Write a C program to find the area of a triangle. 21.Explain the
use of break and continue statements with
example.
22. Write a C program to find whether the given string is
palindrome or not.
23. Describe the limitations of using getchar() and scanf()
functions for reading strings.
24. Write a C program to read a string and display its content
character by character.
25. Write a C program to calculate the area of a circle. 26.List
out the features of C program.
27.Explain the functions Putchar() and getchar() 28.Explain the
functions scanf() and printf() with example. 29.Write down the rules
for identifiers and keyboards.
30. Write a C program to reverse the given digits of a number.
31. Write a C program to generates Fibonacci series. 32.Write a
short note on escape sequence with examples. 33.When we use
standard input & output ?
34.Explain C preprocessor. 35.What is a
header file? Explain?
36.Describe about the Labels and Goto statements 37.Discuss
the data types in C.Give examplels.
38.Write a ‘C’ program to print a biggest number of three numbers.

10 MARKS
1. Explain the C Tokens in detail?
2. Explain the constants and variables with relevant
example?
3. Write a C program to calculate the roots of an equation ?
4. Discuss the operator in C in detail?
5. Explain about Formatted Input and Formatted Output with
example?
6. Explain the various forms of If statement witj suitanle example?
7. Write a program to solve the quadratic equation?
8. Explain about C data types.
9. When we use getc, putc, undef, ifdef, goto?Explain it? 10.Write a
C program to sort an array of integers in
ascending order.

You might also like