Vous êtes sur la page 1sur 279

C-language

S.No

Topic

Page
No.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22

Introduction to software
Introductin to C
Variables and Identifiers
Datatypes
Operators
Control Statements
Functions
Arrays
Strings
Structures
Unions
Pointers
Dynamic memory allocation
Input and Output in C
Files
Preprocessor
Storage classes
Command line arguments
Typedef
Enumeration
Process memory layout
Graphics

INDEX

ASHOKA RAO
THUMUCHERLA

C-language

ASHOKA RAO
THUMUCHERLA

C-language

INTRODUCTION TO SOFTWARE
What is a Computer?
A computer is a programmable machine. The two principal characteristics of a
computer are: it responds to a specific set of instructions in a well-defined manner and it
can execute a prerecorded list of instructions (a program).

All general-purpose computers require the following hardware components:


Memory: enables a computer to store, at least temporarily, data and programs.
Mass storage device: allows a computer to permanently retain large amounts of data.
Common mass storage devices include disk drives and tape drives.
Input device: usually a keyboard and mouse, the input device is the conduit through
which data and instructions enter a computer.
Output device: a display screen, printer, or other device that lets you see what the
computer has accomplished.
Central processing unit (CPU): the heart of the computer, this is the component that
actually executes instructions.

The basic components of a computer are:

ASHOKA RAO
THUMUCHERLA

C-language

Input Unit
Output Unit
Memory / Storage Unit
Arithmetic Logic Unit
Control Unit
Central Processing Unit

When a computer is asked to do a job, it handles the task in a very special way:

It accepts the information from the user. This is called input.


It stored the information until it is ready for use. The computer has memory chips,
which are designed to hold information until it is needed.
It processes the information. The computer has an electronic brain called the
Central Processing Unit, which is responsible for processing all data and instructions
given to the computer.
It then returns the processed information to the user. This is called output.

Input Unit
Input Unit accepts the instructions and data from the outside world. Then it converts
these instructions and data in computer acceptable form. After that it supplies the
converted instructions and data to the computer system for further processing.
Output Unit
The output unit is just reverse of the input unit. it accepts the result produced by
computer, which are in coded form and can't be easily understood by us. Then it converts
this coded result into human readable form. After that it supplies the converted results to
the outside world.

ASHOKA RAO
THUMUCHERLA

C-language

Memory Unit
The Memory Unit is the part of the computer that holds data and instructions for
processing. Although it is closely associated with the CPU, in actual fact it is separate from
it. Memory associated with the CPU is also called primary storage, primary memory, main
storage, internal storage and main memory. When we load software from a floppy disk,
hard disk or CD-ROM, it is stored in the Main Memory.
There are two types of computer memory inside the computer:
Primary Memory
Secondary Memory
Primary Memory
Primary storage, presently known as main memory, is the only one directly
accessible to the CPU. The CPU continuously reads instructions stored there and executes
them as required. Any data actively operated on is also stored there in uniform manner.
However, the primary memory can hold information only while the computer system is ON.
As soon as the computer system is switched off or rest, the information hold in primary
memory disappears. Also it has limited storage capacity because it is very expensive. It is
made up of semiconductor devices.
Secondary Memory
Secondary storage, sometimes called auxiliary storage, is all data storage that is
not currently in a computer's primary storage or memory. This is computer memory that is
not directly accessible to the processor but uses the I/O channels. It is for storing data not
in active use and preserves data even without power, meaning it is non-volatile. In a
personal computer, secondary storage typically consists of storage on the hard disk and
on any removable media, if present, such as a CD or DVD.
Arithmetic Logical Unit
An arithmetic logic unit (ALU) is a digital circuit that performs arithmetic and logical
operations. The ALU is a fundamental building block of the central processing unit (CPU) of
a computer, and even the simplest microprocessors contain one for purposes such as
maintaining timers. The processors found inside modern CPUs and graphics processing
units (GPUs) accommodate very powerful and very complex ALUs; a single component
may contain a number of ALUs. Most ALUs can perform the following operations:
Integer arithmetic operations (addition, subtraction, and sometimes multiplication
and division).
Bitwise logic operations (AND, NOT, OR, XOR)
Bit-shifting operations (shifting or rotating a word by a specified number of bits to
the left or right, with or without sign extension). Shifts can be interpreted as
multiplications by 2 and divisions by 2.
Control Unit

ASHOKA RAO
THUMUCHERLA

C-language
The control unit (often called a control system or central controller) directs the various
components of a computer. It reads and interprets (decodes) instructions in the program
one by one. The control system decodes each instruction and turns it into a series of
control signals that operate the other parts of the computer. Control systems in advanced
computers may change the order of some instructions so as to improve performance. Its
functions are:

Read the code for the next instruction from the cell indicated by the program
counter.
Decode the numerical code for the instruction into a set of commands or signals for
each of the other systems.
Increment the program counter so it points to the next instruction.
Read whatever data the instruction requires from cells in memory (or perhaps from
an input device). The location of this required data is typically stored within the
instruction code.
Provide the necessary data to an ALU or register.
If the instruction requires an ALU or specialized hardware to complete, instruct the
hardware to perform the requested operation.
Write the result from the ALU back to a memory location or to a register or perhaps
an output device.

Central Processing Unit


The control unit and ALU of a computer system are jointly known as the CPU. The CPU is
the brain of computer system. It takes all calculations and comparisons in a computer
systems and it s also responsible for activating and controlling the operations of other
units of computer system.
Types of computer languages
As we human beings communicate with each others in different language such as Urdu,
French, Punjabi and Arabic etc. Similarly to communicate with the computers we have to
use specific languages and for this purpose hundreds of languages have been develop in
which few of them has gained international reputation. C language is one of them. For this
purpose, different languages are developed for performing different types of work on the
computer.

Basically, languages are divided into two categories according to their interpretation.
1. Low Level Languages.
2. High Level Languages.
Low Level Languages

ASHOKA RAO
THUMUCHERLA

C-language
Low level computer languages are machine codes or close to it. Computer cannot
understand instructions given in high level languages or in English. It can only understand
and execute instructions given in the form of machine language i.e. language of 0 and 1.
There are two types of low level languages:

Machine Language.

Assembly Language

Machine Language: It is the lowest and most elementary level of Programming language
and was the first type of programming language to be developed. Machine Language is
basically the only language which computer can understand. In fact, a manufacturer
designs a computer to obey just one Language, its machine code, which is represented
inside the computer by a String of binary digits (bits) 0 and 1. The symbol 0 stands for the
absence of Electric pulse and 1 for the presence of an electric pulse. Since a computer is
Capable of recognizing electric signals, therefore, it understands machine Language.
Advantages of Machine Language

It makes fast and efficient use of the computer.


It requires no translator to translate the code i.e. Directly understood by the
computer

Disadvantages of Machine Language:

All operation codes have to be remembered


All memory addresses have to be remembered.
It is hard to amend or find errors in a program written In the machine language
These languages are machine dependent i.e. a particular Machine language can be
used on only one type of computer

Assembly Language:
It was developed to overcome some of the many inconveniences of machine
language. This is another low level but a very important language in which operation
codes and operands are given in the form of alphanumeric symbols instead of 0s and 1s.
These alphanumeric symbols will be known as mnemonic codes and can have maximum
up to 5 letter combination e.g. ADD for addition, SUB for subtraction, START, LABEL etc.
Because of this feature it is also known as Symbolic Programming Language.

Advantages of Assembly Language

It is easier to understand and use as compared to machine language.


It is easy to locate and correct errors.
It is modified easily

ASHOKA RAO
THUMUCHERLA

C-language
Disadvantages of Assembly Language

Like machine language it is also machine dependent.


Since it is machine dependent therefore programmer Should have the knowledge of
the hardware also.

High Level Languages:


High level computer languages give formats close to English language and the
purpose of developing high level languages is to enable people to write programs easily
and in their own native language environment (English). High-level languages are basically
symbolic languages that use English words and/or mathematical symbols rather than
mnemonic codes. Each instruction in the high level language is translated into many
machine language instructions thus showing one-to-many translation
Types of High Level Languages
Many languages have been developed for achieving different variety of tasks, some
are fairly specialized others are quite general purpose.
These are categorized according to their use as
a) Algebraic Formula-Type Processing. These languages are oriented towards the
computational procedures for solving mathematical and statistical problem
Examples are

BASIC (Beginners All Purpose Symbolic Instruction Code).


FORTRAN (Formula Translation).
PL/I (Programming Language, Version 1).
ALGOL (Algorithmic Language).
APL (A Programming Language).

b) Business Data Processing:


These languages emphasize their capabilities for maintaining data processing procedures
and files handling problems. Examples are:

COBOL (Common Business Oriented Language).


RPG (Report Program Generator

c) String and List Processing: These are used for string manipulation including search
for patterns, inserting and deleting characters. Examples are:

LISP (List Processing).


Prolog (Program in Logic).

d)Object Oriented Programming Language


In OOP, the computer program is divided into objects. Examples are:

C++

ASHOKA RAO
THUMUCHERLA

C-language

Java

e) Visual programming language: these are designed for building Windows-based


applications Examples are:
Visual Basic
Visual Java
Visual C
Advantages of High Level Language

User-friendly
Similar to English with vocabulary of words and symbols
Therefore it is easier to learn.
They require less time to write.
They are easier to maintain.
Problem oriented rather than 'machine' based.
Program written in a high-level language can be translated into many machine
language and therefore can run on any computer for which there exists an
appropriate translator.
It is independent of the machine on which it is used i.e. Programs developed in high
level language can be run on any Computer
Disadvantages of High Level Language

A high-level language has to be translated into the machine language by a


translator and thus a price in computer time is paid.
The object code generated by a translator might be inefficient Compared to an
equivalent assembly language program

Note: High-level languages would be significantly less efficient than assembly


languages; modern compilers do an excellent job of converting high-level
languages into fast executables. Sometimes, they even do a better job than
human coders can do in assembly language.be significantly less efficient than
assembly languages; modern compilers do an excellent job of converting highlevel languages into fast executables. Sometimes, they even do a better job than

An interpreter is a program that reads code and essentially compiles and executes
(interprets) your program as it is run.

ASHOKA RAO
THUMUCHERLA

C-language

One advantage of interpreters is that they are much easier to write than compilers,
because they can be written in a high-level language themselves.
However, they tend to be less efficient when running programs because the
compiling needs to be done every time the program is run. Furthermore, the
interpreter is needed every time the program is run.

Software:
Software is a general term for the various kinds of programs used to
operate computers and related devices. (The term hardware describes the physical
aspects of computers and related devices.)
Software can be thought of as the variable part of a computer and hardware the
invariable part. Software is often divided into application software (programs that do work
users are directly interested in) and system software (which includes operating systems
and any program that supports application software).

Systems software

Set of programs that coordinates activities and functions of the hardware and
various other programs
Is an interface between application software and hardware

ASHOKA RAO
THUMUCHERLA

C-language

Controls the computer hardware and acts as an interface with applications


programs

Application software
Application software, also known as an application or an app, is computer
software designed to help the user to perform specific tasks. Examples include enterprise
software, accounting software, office suites, graphics software and media players. Many
application programs deal principally with documents.

Operating System:
An operating system (OS) is a collection of software that manages computer
hardware resources and provides common services for computer programs. The operating
system is a vital component of the system software in a computer system. Application
programs usually require an operating system to function.
Operating System Functions

Perform common computer hardware functions


Provide a user interface
Provide a degree of hardware independence

ASHOKA RAO
THUMUCHERLA

C-language

Manage system memory


Manage processing tasks
Provide networking capability
Control access to system resources
Manage files

User interface
CUI (Character User Interface):

A function of the operating system that allows individuals to access and command
the computer
Command-based user interface
A particular user interface that requires text commands be given to the computer to
perform basic activities
E.g., Unix, DOS

GUI (Graphical User Interface):

A user interface that uses pictures (icons) and menus displayed on the screen to
send commands to the computer system
E.g. Windows, MAC OS

INTRODUCTION TO C
Programming language is any language that computer system can understand directly or
indirectly to perform the actions asked by the programmer as set of instructions in form of
a computer program.
C is a general purpose programming language developed in 1972 by Dennis Ritchie at Bell
Labs.
C language is the extension for ALGOL and B languages.
Initially, there was no formal specification of C language.
The book "The C Programming Language" by Brian Kernighan and Dennis Ritchie published
in 1978 served as the informal specification for the first version of C language.
In 1989, American National Standards Institute (ANSI) established a standard specification
of C language called: "ANSI X3.159-1989 - Programming Language C".
In 1999, a major revision of ANSI C specification was published by the International
Organization for Standardization (ISO), "ISO/IEC 9899:1999 - Programming Languages - C".

ASHOKA RAO
THUMUCHERLA

C-language
C ended up being so efficient and flexible that in 1973, Ritchie and Ken Thompson rewrote
most of the UNIX operating system using C.
Many previous operating systems had been written in assembly. Unlike assembly, which
ties a program to a specific CPU, Cs excellent portability allowed UNIX to be recompiled
on many different types of computers, speeding its adoption.
C and UNIX had their fortunes tied together, and Cs popularity was in part tied to the
success of UNIX as an operating system.
C is often used for "system programming", including implementing operating systems and
embedded system applications, due to a combination of desirable characteristics such as
code portability and efficiency, ability to access specific hardware addresses, ability to pun
types to match externally imposed data access requirements, and low run-time demand
on system resources.

C is a platform dependent language, by which we can mainly develop desktop


applications.

Platform dependency means where you can develop (on which platform for ex.
WINDOWS) the application, there only you can run that application.

It typically refers to applications that run under only one operating system and run
in only one series of computers (one operating environment).

Platform dependency:
Platform means operating system. To develop one application we need one platform
for example window, linux etc. platform dependency means the application which was
developed using one platform can run on the same platform only, other platform cannot
understand the instructions of program to execute.

ASHOKA RAO
THUMUCHERLA

C-language

But C can also be used for website programming using CGI as a "gateway" for information
between the Web application, the server, and the browser
Note: By using C language we can develop desktop level applications only that mean the
application runs on a particular platform. If we want to develop any system independent
application (web apps), we can go for platform independent languages such as java or
.net.

CGI (Common Gateway Interface)


CGI is an ANSI C-language library for the creation of CGI-based World Wide Web
applications. For basic information about the CGI standard, means we are using C, C++
language to produce CGI script that can supports other web application to run.
Any program or script that will run on your Web server, can be used as a CGI
program
Most people use Perl to write their CGI scripts, but other languages include C and C++ ,
Tcl, and UNIX shell scripts.

Main features of C language:

C is a procedural programming language, not an object-oriented programming


language. C programs are organized as modules and functions.

ASHOKA RAO
THUMUCHERLA

C-language

C supports low-level access to memory using address pointers. This makes C


language a choice for implementing system software.

C supports array data structure with two ways to access array elements, indexes
and pointers.

C supports dynamic memory allocation, which helps to reduce the size of object file
generated by the compiler, and allow arrays to be declared with sizes determined at
runtime.

C supports a large number of library routines for input/output operations, string


manipulations, mathematical functions, etc.

C uses a header file to share declarations of variables and functions of a program


module with other modules.

Structure of a C program:
C application is a combination of one or more functions.
Function is nothing but a set of instructions that performs a particular task.
Every C program at least contains one function called main ().
Execution of a C program starts from main function only.
C is a case sensitive language, so that all the instructions of a program should be in
small case only except some pre defined names (which were defined in upper case).
Functions is of two types
o Pre-defined functions
o User defined functions
The most useful functions for any kind of applications were already developed along
with the language and placed in some libraries such as printf(), scanf()
As like pre-defined functions programmer can also develop their own functions
according to their requirement called as user defined functions.
Any requirement of pre-defined function in user application just includes that library
with the help of pre processer directives to work with that corresponding library
function.

Application life cycle in C:

ASHOKA RAO
THUMUCHERLA

C-language

ASHOKA RAO
THUMUCHERLA

C-language

Preprocessing - Using a Preprocessor program to convert C source code in


expanded source code. "#includes" and "#defines" statements will be processed
and replaced actually source codes in this step.

Compilation - Using a Compiler program to convert C expanded source to


assembly source code.

Assembly - Using a Assembler program to convert assembly source code to object


code.

Linking - Using a Linker program to convert object code to executable code.


Multiple units of object codes are linked to together in this step.

Loading - Using a Loader program to load the executable code into CPU for
execution.

First C-application:

Requirement of our first application is to print a simple message (Hello world) on the
output device (monitor).
To print the data on the output device in C there is a pre-defined function called
printf().
Execution of a C-program starts from main function only. And once the control
reaches the end of main function, program execution over.
So that the total program code we should write inside the main function only

ASHOKA RAO
THUMUCHERLA

C-language

clrscr () function is a pre-defined function available in conio(console input output)


library. It can clear the output area to print the current program output in an
efficient manner.
Working with pre-defined functions is only possible by including them into the user
application with the help of pre-processor directive (#).
Pre-processor directives executes before the source code passes to the compiler.
Pre-processor directives replace the pre-defined code with the corresponding
statement in the user application before compilation.

VARIABLES & IDENTIFIERS


VARIABLE:
Variable is a named memory location in the computer to store the data.
(Or)
Variable is a data name to a data value.
Note: Assigning names to the data is useful for further usage in the application. It is only
possible to work with same kind of data when it is having unique names.
For example
int a=10, b=10;
The Programming language C has two main variable types
Local Variables
Global Variables
Local Variables

If we declare any variable within the block or function called as local variable.
Local variables scope is confined within the block or function where it is defined.
Local variables must always be defined at the top of a block.
When a local variable is defined - it is not initialized by the system, you must
initialize it yourself.
When execution of the block starts the variable is available, and when the block
ends the variable 'dies'.

Global Variables

If we declare any variable to outside of all the functions comes under global
variable.
Global variable is defined at the top of the program file and it can be visible and
modified by any function that may reference (scope) it.
Global variables are initialized automatically with some default values according to
its type at the time of compilation.

ASHOKA RAO
THUMUCHERLA

C-language

Data Type

Default Value

int

char

'\0'

float

0.000000

#include<stdio.h>
#include<conio.h>
int a,b;
float f;
char ch;
void main()
{
int c=10,d=20;
clrscr();
printf("a=%d\nb=%d\nf=%f\nch=%c\nc=%d\nf=%d",a,b,f,ch,c,d);
}
Rules for constructing variable names

A Variable name consists of any combination of alphabets, digits and underscores.


The length of identifier may be up to 31 characters but only the first 8 characters
are significant by compiler.
(Note: Some compilers allow variable names whose length may be up to 247
characters. But, it is recommended to use maximum 31 characters in variable
name. Large variable name leads to occur errors.)
The first character of the variable name must either be alphabet or underscore. It
should not start with the digit.
No commas and blanks are allowed in the variable name.
No special symbols other than underscore are allowed in the variable name.
We need to declare the type of the variable name before making use of that name
in the program.
Lower case variables and upper case variables of same name treat differently (case
sensitive).
Variable name should not match with a keyword, because keywords are the
reserved words to do their own tasks such as do, while, int, for.

C Identifiers
"Identifiers" or "symbols" are the names you supply for variables, types, functions,
and labels in your program.
Identifier names must differ in spelling and case from any keywords.
You cannot use keywords as identifiers; they are reserved for special use.

ASHOKA RAO
THUMUCHERLA

C-language

A special kind of identifier, called a statement label, can be used in goto


statements.
The first character of an identifier name must be a non-digit.

Keywords:

Keywords are the system defined identifiers.


All keywords have fixed meanings that do not change.
White spaces are not allowed in keywords.
Keyword may not be used as user definer identifier.
It is strongly recommended that keywords should be in lower case letters.
There are totally 32(Thirty Two) keywords used in a C programming.
int

float

double

long

short

signed

unsigned

const

if

else

switch

break

default

do

while

for

register

extern

static

struct

typedef

enum

return

sizeof

goto

union

auto

case

void

char

continue

volatile

Escape Sequence Characters (Backslash Character Constants) in C:


C supports some special escape sequence characters that are used to do special
tasks.
Some of the escape sequence characters are as follow:
Character Constant
\n
\b
\t
\f
\a
\r
\v
\?
\'
\''
\\
\0

Meaning
New line (Line break)
Backspace
Horizontal Tab
Form feed
Alert (alerts a bell)
Carriage Return
Vertical Tab
Question Mark
Single Quote
Double Quote
Backslash
Null

Example codes on escape sequences:


void main()

ASHOKA RAO
THUMUCHERLA

C-language
{
clrscr();
printf("%d%d\b\b%d",1,2,3);
getch();
}
void main()
{
char str[20]="naresh tech";
clrscr();
printf("%s\r%c",str,'N');
getch();
}

Data types
Objectives:

Introduction
List of data types
Primitive data types in c
user defined of data types in c
Size of data types in c
Range of data types in c
Easy way to remember limit of data types in c
Memory representation of data types
Overflow value of data type in c

Introduction:

C supports different types of data, each of which may be represented differently


within a computer's memory.
Data type is used to determine what type of value a variable or a constant can
contain throughout the program.
Data types were already pre-defined and we have to choose one data type among
all according to the size of the data and type of the data that what you are going to
work with.
A data type is used to identify the type of a variable when the variable is declared,
to identify the type of the return value of a function and to identify the type of a
parameter expected by a function
When the compiler encounters a declaration for a variable, it sets up a memory
location for it.

ASHOKA RAO
THUMUCHERLA

C-language

An operator used on a variable or variables is legal only if the operator is defined in


that programming language for a variable of that type.
The variable or variables involved with the operator are of the same or compatible
types
In C language, different variables contain different data types e.g. Roll No contains
an 'integer' value whereas percentage contains a 'float' value.
C language offers a number of variations for the same data type like integer data
type can be long int and short int.
The intention of providing these variations is to provide integers with different
ranges possible.
Many people believe that a programmer working in C language is provided with a
very tiny set of data types but Dennis Ritchie has made available to the C
programmers a feature that allows them to derive their own data types from the
existing one.
This way a programmer can decide which data type is to be used depending on
these 2 factors:

Uses:
Economize the memory space.
Improve the speed of execution of program.
In C language, it is compulsory to declare variables with their data type before using them
in any statement. Mainly data types are categorized into 3 categories: Primitive Data Types
Derived Data Types
User Defined Data Types

Data type
primitive

Derived

User defined

int

Function

structure

float

Pointer

typedef

double

Array

Enum
Union

char
void

ASHOKA RAO
THUMUCHERLA

C-language

Integer types:

C provides several standard integer types, from small magnitude to large


magnitude numbers: char, short int, int, long int.
Each type can be signed or unsigned.
Signed types can represent positive and negative numbers while unsigned can
represent zero and positive numbers.
The short int is a signed small integer.
C allows abbreviated or longer names for the same type: short, signed short, signed
short int. For the unsigned version use one of these: unsigned short, unsigned short
int.
A signed integer may be declared as: int, signed, signed int.
An unsigned integer may be declared as: unsigned, unsigned int.
A signed long int may be declared using one of these names: long, signed long, long
int, signed long int.
An unsigned version may be declared as: unsigned long, unsigned long int.

The following table represents limits of data types:


Type
signed char
unsigned char
Short
unsigned short
Int
unsigned int
Long
unsigned long
signed long long
unsigned long
long
Float
double

size
1
1
2
2
2
2
4
4
8
8

Minimum Value
-127
0
-32767
0
-32767
0
-2147483647
0
-9223372036854775807
0

Maximum Value
127
255
32767
65535
32767
65535
2147483647
4294967295
9223372036854775807
18446744073709551615

4
8

1.175494351 E 38
2.2250738585072014 E 308

long double

10

Same as double(more
precision)

3.402823466 E + 38
1.7976931348623158 E
+ 308
same as double

Void main()
{

ASHOKA RAO
THUMUCHERLA

C-language
int sum;
float money;
char letter;
double pi;
sum = 10;
money = 2.21;
letter = 'A';
pi = 2.01E6;
printf("value of
printf("value of
printf("value of
printf("value of
}

/* assign integer value */


/* assign float value */
/* assign character value */
/* assign a double value */
sum = %d\n", sum );
money = %f\n", money );
letter = %c\n", letter );
pi = %e\n", pi );

Note: If you want to know the actual minimum and maximum values, an
implementation uses they are defined in the limits.h header file. It defines various
constants like SCHAR_MIN, SCHAR_MAX, etc. that give the values for this
implementation of C. The following example shows the limits of this implementation:
#include <stdio.h>
#include <limits.h>
void main()
{
printf("Signed char minimum value: %d\n", SCHAR_MIN );
printf("Signed char maximum value: %d\n", SCHAR_MAX );
printf("Unsigned char minimum value: %d\n", 0 );
printf("Unsigned char maximum value: %d\n", UCHAR_MAX );
printf("Char minimum value: %d\n", CHAR_MIN );
printf("Char maximum value: %d\n", CHAR_MAX );
printf("Signed short minimum value: %d\n", SHRT_MIN );
printf("Signed short maximum value: %d\n", SHRT_MAX );
printf("Unsigned short minimum value: %d\n", 0 );
printf("Unsigned short maximum value: %d\n", USHRT_MAX );
printf("Signed int minimum value: %d\n", INT_MIN );
printf("Signed int maximum value: %d\n", INT_MAX );
printf("Unsigned int minimum value: %u\n", 0 );
printf("Unsigned int maximum value: %u\n", UINT_MAX );
printf("Signed long minimum value: %ld\n", LONG_MIN );
printf("Signed long maximum value: %ld\n", LONG_MAX );
printf("Unsigned long minimum value: %lu\n", 0 );
printf("Unsigned long maximum value: %lu\n", ULONG_MAX );
}

sizeof():

Returns the size of the expression or type.


Keyword sizeof is, in fact, an operator. It returns the size, in bytes, of the given
expression or type (as type size_t).
Its argument may be an expression of a type name:

ASHOKA RAO
THUMUCHERLA

C-language
sizeof expression
sizeof (type)
code1:
void main()
{
int a,c;
long f;
c=sizeof(a+f);
printf("%d",c);
}
Code2:
int main()
{
printf("sizeof(char) == %d\n", sizeof(char));
printf("sizeof(short) == %d\n", sizeof(short));
printf("sizeof(int) == %d\n", sizeof(int));
printf("sizeof(long) == %d\n", sizeof(long));
printf("sizeof(long long) == %d\n", sizeof(long long));
return 0;
}
code3:
#include<stdio.h>
int main(){
int size;
size=sizeof(void);
printf("%d",size);
return 0;
}
Code4:
void main()
{
int a=10,b=32767,c=32768,d=32768;
printf(%d\n%d\n%d\n%u,a,b,c,d);
}
Code5:
void main()
{
int a=65;
char ch=a;
printf(%d%d%c%c,a,ch,a,ch);
}

ASHOKA RAO
THUMUCHERLA

C-language

Code6:
void main(){
char i=250;
printf(%d,i);
}
Code7:
void main()
{
unsigned int=-1;
printf(%d%u%u,i,j,i*-1);
}
Code8:
void main()
{
unsigned short a=-1;
unsigned char b=a;
printf(%d%d,a,b);
}

Code9:
void main()
{
unsigned short a=-1;
unsigned char b=a;
printf(%u%d,a,b);
}

Float types:

A floating point type variable is a variable that can hold a real number, such as
4.0, 2.5, 3.33, or 0.1226.
There are three different floating point data types: float, double, and long double.
A float is usually 4 bytes and a double 8 bytes, but these are not strict
requirements, so sizes may vary.
Long doubles were added to the language after its release for architectures that
support even larger floating point numbers.
These can have positive or negative values:

Float: The basic floating-point type for the system; it can represent at least six significant
figures accurately.
Double: A (possibly) larger unit for holding floating-point numbers. It may allow more
significant figures (at least 10, typically more) and perhaps larger exponents than float.

ASHOKA RAO
THUMUCHERLA

C-language
Long double: A (possibly) even larger unit for holding floating-point numbers. It may
allow more significant figures and perhaps larger exponents than double.
void main()
{
float me = 1.1;
double you = 1.1;
if(me==you)
printf("both are same");
else
printf("both are different");
}
Answer: both are different
Note: For floating point numbers (float, double, long double) the values cannot be
predicted exactly. Depending on the number of bytes, the precession with of the
value represented varies. Float takes 4 bytes and double takes 10 bytes. So float
stores 0.9 with less precision than long double.

In scientific notation, numbers are represented as decimal number times powers of 10.
Here are some examples.
Number
Scientific Notation
Exponential Notation
1,000,000,000

= 1.0x109

= 1.0e9
5

123,000

= 1.23x10

= 1.23e5

322.56

= 3.2256x102

= 3.2256e2

0.000056

= 5.6x10-5

= 5.6e5

Floating-Point Constants
There are many choices open to you when you write a floating-point constant.
The basic form of a floating-point constant is a signed series of digits, including a
decimal point, followed by an e or E, followed by a signed exponent indicating the
power of 10 used.
Here are two valid floating-point constants:
-1.56E+12
2.87e-3
You can leave out positive signs.
You can do without a decimal point (2E5) or an exponential part (19.28), but not
both simultaneously.
You can omit a fractional part (3.E16) or an integer part (.45E6), but not both (that
wouldn't leave much!).
Here are some more valid floating-point constants:

ASHOKA RAO
THUMUCHERLA

C-language

3.14159
.2
4e16
.8E-5
100.
Don't use spaces in a floating-point constant.
Wrong:
1.56 E+12

#include <stdio.h>
int main(void)
{
float aboat = 32000.0;
double abet = 2.14e9;
double dip = 5.32e-5;
printf("%f can be written %e\n", aboat, aboat);
printf("%f can be written %e\n", abet, abet);
printf("%f can be written %e\n", dip, dip);
return 0;
}

Floating-Point Round-off Errors


Take a number, add 1 to it, and subtract the original number. What do you get?
You get 1. But a floating-point calculation, such as the following, may give another
answer:
/* round-off error */
#include <stdio.h>
int main(void)
{
float a,b;
b = 2.0e20 + 1.0;
a = b - 2.0e20;
printf("%f \n", a);
return 0;
}

The reason for these odd results is that the computer doesn't keep track of enough
decimal places to do the operation correctly.
The number 2.0e20 is 2 followed by 20 zeros and, by adding 1, you are trying to
change the 21st digit.
To do this correctly, the program would need to be able to store a 21-digit number.
A float number is typically just six or seven digits scaled to bigger or smaller
numbers with an exponent.

ASHOKA RAO
THUMUCHERLA

C-language

On the other hand, if you used 2.0e4 instead of 2.0e20, you would get the correct
answer because you are trying to change the fifth digit, and float numbers are
precise enough for that.

#include <stdio.h>
int main(void)
{
float a,b;
b = 2.0e4 + 1.0;
a = b - 2.0e4;
printf("%f \n", a);
return 0;
}
#include <stdio.h>
int main(void)
{
int f = 4;
int g = 5;
float h = 5.0f;
printf("%d\n", f, g); /* too many arguments */
printf("%d %d\n",f);
/* too few arguments */
printf("%d %f\n", h, g); /* wrong kind of values */
return 0;
}
#include <stdio.h>
int main(void){
char ch;
printf("Please enter a character.\n");
scanf("%c", &ch); /* user inputs character */
printf("The code for %c is %d.\n", ch, ch);
return 0;
}
#include<stdio.h>
main(){
double num=1.2;
int var=5;
clrscr();
printf("%f\n",!num);
printf("%d\n",!var);
printf("%d\t",sizeof(!num));
printf("%d\t",sizeof(15/2));
printf("%d",var);
getch();
}

ASHOKA RAO
THUMUCHERLA

C-language
Consider on following declaration:
(i)
short i=10;
(ii)
static i=10;
(iii) unsigned i=10;
(iv)
const i=10;
Ans: Choose correct one: All are correct declaration. Default data type of above
all declaration is int
#include<stdio.h>
int main(){
int a=-5;
unsigned int b=-5u;
if(a==b)
printf("Avatar");
else
printf("Alien");
return 0;
}
o/p: Avatar
Explanation:
int a=-5;
Here variable a is by default signed int.
unsigned int b=-5u;
Constant -5u will convert into unsigned int. Its corresponding unsigned int value will be :
65536 5 + 1= 65532
So, b = 65532
In any binary operation of dissimilar data type for example: a == b
Lower data type operand always automatically type casted into the operand of
higher data type before performing the operation and result will be higher data
type.
In c signed int is higher data type than unsigned int. So variable b will automatically
type casted into signed int.
So corresponding signed value of 65532 is -5
Hence, a==b
What will be the output of the program?
#include<stdio.h>
int main()
{
float a=0.7;
if(a < 0.7)
printf("C\n");
else
printf("C++\n");
return 0;
}
o/p:C

ASHOKA RAO
THUMUCHERLA

C-language

Explanation:
if(a < 0.7) here a is a float variable and 0.7 is a double constant. The float variable a is
less than double constant 0.7. Hence the if condition is satisfied and it prints 'C'
Arithmetic Conversions
Sometimes values within expressions are converted to another type, this is done to
preserve information. For example, it is permitted to add a double to an int, the int value
will be converted to a double before the addition takes place rather than vice versa. For
every binary operator in an expression the following rules are used:
if either operand is long double convert the other operand to long double
otherwise, if either operand is double convert the other operand to double
otherwise, if either operand is float convert the other operand to float
otherwise perform integral promotions on both operands, and then:
if either operand is unsigned long int convert the other to unsigned long int
otherwise, if one operand is long int and the other is unsigned int then:
if a long int can represent all values of unsigned int then convert unsigned int
operand to long int
if a long int cannot represent all the values of unsigned int, then convert both
operands to unsigned long int
otherwise, if either operand is long int then convert the other to long int
otherwise, if either operand is unsigned int then convert the other to unsigned int
otherwise, both operands are of type int

Number System(Decimal, Binary, Octal, Hexadecimal)


Decimal Numeral System (Base-10):
Our number system, the decimal system, uses ten symbols. Therefore, decimal is
said to be Base Ten. These are the regular numbers that we use.
Example:
253810 = 2103+5102+3101+8100
Written another way, you could view decimal numbers like this:
10^3

10^2

10^1 10^1

thousand hundred
tens
s
s

ones

1000

100

10

Convert From Decimal to Other Numeral Systems


To convert a number from decimal to any other numeral system, we divide the
integer part of a number with the base number of the system.

ASHOKA RAO
THUMUCHERLA

C-language

For instance, to convert a number from decimal to binary (base 2), we divide that
number with 2.
While we make each division, the remainder of the division is the rightmost digit of
the resulting number in binary and the result of the division gets re divided with 2
till we reach the division where the result is 0.
If the number has a fractional part, this gets multiplied by two.
The integer part of the number after the multiplication is held.
It will be the leftmost digit of our new fractional number in the binary system, right
after the comma.
The result of the multiplication of 2 with the fractional part of the number gets
subtracted of the integer part used for the creation of the fractional number in the
binary system.
This new number gets multiplied with 2 again and then the previous procedure is
executed again and again, till the new fractional number becomes 0.
If the new fractional number is periodic, we cut and round the resulting number.
This may sound a bit confusing, so these are some example conversions:

Convert from decimal to binary (10)->(2)


Integer part:
45(10)->(2)
Div Quotient
Remainder
45 / 2
22
1
22 / 2
11
0
11 / 2
5
1
5/2
2
1
2/2
1
0
1/2
0
1
45(10)->101101(2)

Binary Number ()
1
01
101
1101
01101
101101

Fractional Part:
0,182(10) -> (2)
Div
Product
Remainder
Binary Number ()
0,182 * 2
0,364
0
0,0
0,364 * 2
0,728
0
0,00
0,728 * 2
1,456
1
0,001
0,456 * 2
0,912
0
0,0010
0,912 * 2
1,824
1
0,00101
0,824 * 2
1,648
1
0,001011
0,182(10)->0,0010111(2) (After we round and cut the number)
Convert from decimal to octal (10)->(8)
Integer part:
45(10) ->X (8)
Div Quotient Remainder
45 / 8
5
5

Octal Number ()
5

ASHOKA RAO
THUMUCHERLA

C-language
5/8

55

45(10) ->55(8)
Fractional Part:
0,182(10) -> (8)
Mul
Product
Integer
0,182 * 8
1,456
0,456 * 8
3,648
0,648 * 8
5,184
0,184 * 8
1,472
0,472 * 8
3,776
0,776 * 8
6,208
0,182(10)->0,135136(8) (After we round and cut the

Binary Number ()
1
0,1
3
0,13
5
0,135
1
0,1351
3
0,13513
6
0,135136
number)

Convert from decimal to hexadecimal (10)->(16)


Integer part:
45(10)->X(16)
Div Quotient Remainder
Hex Number ()
45 / 16
2
13
D (Since 13 decimal is D in
hexadecimal)
2 / 16
0
2
2D
(See the table)
45(10)->2D(16)
Fractional part:
0,182(10)->(16)
Mul
Product
Integer
Binary Number ()
0,182 * 16
2,912
2
0,2
0,912 * 16
14,592
14
0,2
0,592 * 16
9,472
9
0,29
0,472 * 16
7,552
7
0,297
0,552 * 16
8,832
8
0,2978
0,182(10)->0,2E97816) (After we round and cut the number)
Binary Numeral System - Base-2
The word binary comes from "Bi-" meaning two. We see "bi-" in words such as
"bicycle" (two wheels) or "binocular" (two eyes). Binary numbers uses only 0 and 1 digits.
Examples:
101012 = 10101B = 124+023+122+021+120 = 16+4+1= 21
101112 = 10111B = 124+023+122+121+120 = 16+4+2+1= 23
1000112 = 100011B = 125+024+023+022+121+120 =32+2+1= 35
Convert from binary to decimal (2)->(10) :

ASHOKA RAO
THUMUCHERLA

C-language

This is 18 + 14 + 02 + 1 +
1(1/2) + 0(1/4) + 1(1/8)
= 13.625 in Decimal
Binary to Octal Conversion
An easy way to convert from binary to octal is to group binary digits into sets of
three, starting with the least significant (rightmost) digits.
Binary: 11100101 =

11 100 101
011 100 101

Pad the most significant digits with zeros if


necessary to complete a group of three.

Then, look up each group in a table:


Binar
y:
Octal
:
Binary
Octal

=
=

000

001

010

011

100

101

110

111

100
4

101
5

011
3

= 345 oct

Binary to Hexadecimal Conversion:


Drop any leading zeros or pad with leading zeros to get groups of four binary digits
(bits):
Binary 011100101 = 1110 0101
Then, look up the groups in a table to convert to hexadecimal
Binary:
0000 0001 0010 0011 0100
Hexadecimal 0
1
2
3
4
:
Binary:
1000 1001 1010 1011 1100
Hexadecimal 8
9
A
B
C
:
Binary

digits.
0101
5

0110
6

0111
7

1101
D

1110
E

1111
F

1110 0101

ASHOKA RAO
THUMUCHERLA

C-language
Hexadecimal

= E5 hex

Octal to Binary Conversion:


In order to get the equivalent Binary number for the given octal number, write the
individual octal digit in its equivalent binary numbers from the below conversion table that
yields you the binary number equivalent. The below example lets you understand the hex
to binary conversion clear
Example: Convert Hexadecimal number (536)8 to its binary equivalent

Convert from octal to decimal (8)->(10)


55. 135136(8)->(10)
Index the digits of the number
5150. 1-13-25-31-43-56-6
We multiply each digit
=5 * 81 + 5 * 80 + 1 * 8-1 + 3 * 8-2 + 5 * 8-3 + 1 * 8-4 + 3 * 8-5 + 6 * 8-6
=40 + 5 + 0,125 + 0,03125 + 0,009766 + 0,000244 + 0,0001 + 0,0000229
= 45,1663829(10)
Examples:
278 = 281+780 = 16+7 = 23
308 = 381+080 = 24
43078 = 483+382+081+780 = 2247
Convert from octal to hexadecimal
When converting from octal to hexadecimal, it is often easier to first convert the
octal number into binary and then from binary into hexadecimal. For example, to convert
345 octal into hex:
(from the previous example)
Octal
=
Binary
=

011

100

101

= 011100101
binary

Hexadecimal Numeral System - Base-16


To represent the value 202 requires eight binary digits
When dealing with large values, binary numbers quickly become too unwieldy.

ASHOKA RAO
THUMUCHERLA

C-language

The hexadecimal (base 16) numbering system solves these problems.


hex numbers are very compact
It is easy to convert from hex to binary and binary to hex.
The Hexadecimal Number System uses base 16 includes only the digits 0 through 9
and the letters A, B, C, D, E, and F

Examples:
2816 = 28H = 2161+8160 = 40
2F16 = 2FH = 2161+15160 = 47
BC1216 = BC12H = 11163+12162+1161+2160 = 48146
Numeral Systems Conversion Table
Decima
Hexadecim
l
Binary Octal
Decimal
al
BaseBase-2 Base-8
Base-10
Base-16
10

Binary
Base-2

Octal
Base-8

Hexadeci
mal
Base-16

16

10000

20

10

17

10001

21

11

10

18

10010

22

12

11

19

10011

23

13

100

20

10100

24

14

101

21

10101

25

15

110

22

10110

26

16

111

23

10111

27

17

1000

10

24

11000

30

18

1001

11

25

11001

31

19

10

1010

12

26

11010

32

1A

11

1011

13

27

11011

33

1B

12

1100

14

28

11100

34

1C

13

1101

15

29

11101

35

1D

14

1110

16

30

11110

36

1E

15

1111

17

31

11111

37

1F

Convert from hexadecimal to decimal (16)->(10)


2D,2E978D(16)->(10)
Index the digits of the number
21130,2-114-29-37-48-513-6
We multiply each digit
=2 * 161 + 13 * 160 + 2 * 16-1 + 14 * 16-2 + 9 * 16-3 + 7 * 16-4 + 8 * 16-5 + 13 * 16-6

ASHOKA RAO
THUMUCHERLA

C-language
=32 + 13 + 0,125 + 0,0546875 + 0,00219727 + 0,00010681 + 0,00000762 +
0,00000077
= 45,18199997(10)
Some more examples:

What is the decimal value of the hexadecimal number "D1CE"

= 53,248 + 256 + 192 + 14


= 53,710
Example: 2E6.A3

This is 21616 + 1416 + 6 + 10/16 + 3/(1616)


Make some exercises yourself, if you want some more.
int main(void)
{
int i = 0;
int j = 0;
int k = 0;
int n = 0;
printf("Input:\n");

ASHOKA RAO
THUMUCHERLA

C-language
n = scanf(" %d %x %o", &i , &j, &k );
printf("\nOutput:\n");
printf("%d values read.", n);
printf("\ni = %d j = %d k = %d\n", i, j, k );
/* Alternative to statement above
printf("\ni = %x j = %X k = %d\n", i, j, k );
*/
return 0;
}
1's and 2's complement of the binary numbers(positive and negative):
Property
Two's complement representation allows the use of binary arithmetic operations on
signed integers, yielding the correct 2's complement results.
Positive Numbers
Positive 2's complement numbers are represented as the simple binary.
Negative Numbers
Negative 2's complement numbers are represented as the binary number that when
added to a positive number of the same magnitude equals zero.
Integer
Unsigned

Signed
5
4
3
2
1
0
-1
-2
-3
-4
-5

2's Complement
5
4
3
2
1
0
255
254
253
252
251

0000
0000
0000
0000
0000
0000
1111
1111
1111
1111
1111

0101
0100
0011
0010
0001
0000
1111
1110
1101
1100
1011

Note: The most significant (leftmost) bit indicates the sign of the integer; therefore it is
sometimes called the sign bit.
If the sign bit is zero, then the number is greater than or equal to zero, or
positive.
If the sign bit is one, then the number is less than zero, or negative.

ASHOKA RAO
THUMUCHERLA

C-language

Calculation of 2's Complement:


To calculate the 2's complement of an integer, invert the binary equivalent of the
number by changing all of the ones to zeroes and all of the zeroes to ones (also called 1's
complement), and then add one.
For example,
0001 0001(binary 17)

1110 1111(two's complement -17)

Step1: NOT(0001 0001)


=
Step2: 1110 1110 + 0000 0001=

1110 1110 (Invert bits)


1110 1111 (Add 1)

2's Complement Addition:


Two's complement addition follows the same rules as binary addition.
For example,
5 + (-3) = 2
0000 0101 =
+ 1111 1101

+5
=

0000 0010

+2

-3

2's Complement Subtraction


Two's complement subtraction is the binary addition of the minuend to the 2's
complement of the subtrahend (adding a negative number is the same as subtracting a
positive one).
For example,
7 - 12 = (-5)
0000 0111 =
+ 1111 0100
1111 1011

+7
=
=

-12
-5

2's Complement Multiplication


Two's complement multiplication follows the same rules as binary multiplication.
For example,
(-4) 4 = (-16)
1111 1100 =
0000 0100

-4
=

+4

ASHOKA RAO
THUMUCHERLA

C-language

1111 0000

-16

Datatype overview chart:

Summary:

We can use different variations of the primary/fundamental data types like signed,
unsigned, short, long, double and long double.
The maximum value a variable can hold depends upon the number of bytes it
occupies in the memory.
By default, all the variables are signed but a variable can be declared as unsigned,
if you want to increase the range of the data type to accommodate greater value
without increasing the bytes occupied.
While designing a program, a programmer must consider the 2 main factors
First one, the program is efficient and economizes the memory space consumed,
also referred to as space complexity.
Second one, the program is executed in the least possible time, also referred to as
time complexity.

ASHOKA RAO
THUMUCHERLA

C-language

OPERATORS
Objectives:

What is an operator?
Unary operators?
Binary operators?
Ternary operators?
Precedence of operators?

Introduction:
An operator is a symbol that performs an operation. An operator acts on some
variables called operands to get the desired result.
Operand: It is the value on which operators are worked. We can supply the required value
to the operator either by using literal, or variable or expression or non-void method.
i.e. An operator performs operations on operands.
Operator

a
Operand

b
operand

Types of operators:
1) Assignment operators(BINARY)
2) Arithmetic operators(BINARY)
3) Conditional operator (? :)(TERNARY OPERATOR)
4) Modifying operators (increment and decrement)(UNARY OPERATORS)
5) Relational operators(BINARY)
6) Logical operators(BINARY)
7) Bitwise operators(BINARY)
8) Shift operators(BINARY)
9) Compound assignment operators(BINARY)
10)
Address and Pointer operator(UNARY)
11)
Sizeof() operator(UNARY)
1. Assignment Operator:
An assignment operation assigns the value of the right-hand operand to the storage
location named by the left-hand operand.
The left-hand operand of an assignment operation must be a modifiable l-value.

ASHOKA RAO
THUMUCHERLA

C-language

The right side data to the assignment operator may be a value, a constant
expression or a method call.

#include <stdio.h>
#include <conio.h>
void main()
{
int a,b;
clrscr();
a = 53;
printf("\n\t Value of A : %d",a);
// 53
b = a; // assigning the value through a variable
printf("\n\n\t Value of B : %d",b); // 53
getch();
}
2. Arithmetic Operators:

Arithmetic operator is used to perform arithmetical operations.


These operators operate on two operands. So that it is also called as 'Binary
operator'.
Arithmetic operators include the familiar addition (+), subtraction (-), multiplication
(*) and division (/) operations.
In addition there is the modulus operator (%) which gives the remainder left over
from a division operation.

Note: A Modulus operator gives the remainder value. The result of x%y is obtained
by (x-(x/y)*y). This operator is applied only to integral operands and cannot be
applied to float or double.
#include <stdio.h>
#include <conio.h>
void main(){
int a,b,c,d,e,f,g;
clrscr();
printf("\n\t Enter First Number :"); // 5
scanf("%d",&a);
printf("\n\t Enter Second Number :"); // 2
scanf("%d",&b);
c = a + b;
printf("\n\n\t Addition is : %d",c); // 7
d = a - b;
printf("\n\n\t Subtraction is : %d",d); // 3
e = a * b;
printf("\n\n\t Multiplication is : %d",e); // 10
f = a / b;
printf("\n\n\t Division is : %d",f); // 2
g = a % b;

ASHOKA RAO
THUMUCHERLA

C-language
printf("\n\n\t Modulus is : %d",g); // 1
getch();
}
#include<stdio.h>
void main(){
int a=3,b=5;c=2,d=7,e;
clrscr();
e=d-b%(a+c)-d+(b/a)-c+a-b;
printf(e=%d,e);
}
3. Conditional Operator:
Conditional operator is also called as 'ternary operator'.
It is widely used to execute condition in true part or in false part.
It operates on three operands called as ternary operator.
The logical or relational operator can be used to check conditions.
Code1:
#include <stdio.h>
#include <conio.h>
void main(){
int a, b=3;
clrscr();
a = 5;
printf("\n\n A is less than B ? ");
a<b?printf(yes):printf(No); //prints No
}
Code2:
#include <stdio.h>
int x, y;
int main(){
printf ("\n Enter two numbers");
scanf("%d %d", &x, &y);
printf("\n\n %d is bigger\n", ((x>y)?x:y));
return 0;
}
Code3:
#include <stdio.h>
void main() {
int y;
clrscr();
print f ("enter a year");
scan f ("%d",&y)
(y%100==0)&&(y%400==0)||(y%100!=0)&&(y%4==0)?print f("% d is leap year",y):print
f("%d is not leap year",y);

ASHOKA RAO
THUMUCHERLA

C-language
getch();
}
Code4:
#include<stdio.h>
int main(){
int a,b,c,big;
printf("\nEnter 3 numbers:");
scanf("%d %d %d",&a,&b,&c);
big=(a>b&&a>c?a:b>c?b:c);
printf("\nThe biggest number is: %d",big);
return 0;
}
4. Unary Operators:(modifying operators):

It operates on a single operand. Therefore, this operator is called as 'unary


operator.'
These are also called increment and decrement operators.
Increment operators are again divided into pre-increment operators and postincrement operators. Decrement operators are also categorized into pre-decrement
and post-decrement operators.
Increment operators (either pre-incre or post-incre) increase the value of a variable
by 1only but when pre-increment operators increase the value and post-increment
increases the value matters.
Decrement operators (either pre-decre or post-decre) decrease the value of a
variable by 1.

ASHOKA RAO
THUMUCHERLA

C-language
Difference between pre-increment and post-increment variable:
They both increment the variable. But the value returned by the pre-increment
operator is the value of the variable after it has been incremented, while the value
returned by the post-increment operator is the value before it has been incremented.
For example:
int a = 1;
int b = ++a;
// Now a is 2 and b is also 2.

Code1:
#include <stdio.h>
#include <conio.h>
void main()
{
int a=4, b;
clrscr();
printf("\n\n Value
a++; // Post
printf("\n\n Value
++a; // Pre
printf("\n\n Value
b=--a;
printf("\n\n Value
printf("\n\n Value
b=a++;
printf("\n\n Value
printf("\n\n Value
b++;
printf("\n\n Value
getch();
}

int a = 1;
int b = a++;
// Now a is 2 but b is 1.

of A : %d",a); // 4
of A : %d",a); // 5
of A : %d",a); // 6
of A : %d",a); // 5
of B : %d",b); // 5
of A : %d",a); // 6
of B : %d",b); // 5
of B : %d",b); // 6

Code2:
void main()
{
int x=10, y=20,z;
z = x++ * y++;
printf(%d,%d,%d,x,y,z);
}
Code3:
void main()
{

ASHOKA RAO
THUMUCHERLA

C-language
int a=5,b;
b = a++ + ++a + ++a;
printf(%d,%da,b);
}
Code4:
void main()
{
int x=20,y=35;
x = y++ + x++;
y = ++y + ++x;
printf(%d%d,x,y);
}
Code5:
void main(){
int x=2, y=7,z;
z = x++ * y--;
x = x-- + ++z;
y = y++ - x++;
z = z-- + y++;
x = x++ + ++x;
printf(%d,%d,%d,x,y,z);
}
Code6:
void main()
{
int i=7;
printf(%d,%d,%d,%d,i++,--i,i--,++i);
}
Code7:
void main(){
int i;
i=1;
i=i+2*i++;
printf(%d,i);
}
ans: 4
Code8:
void main(){
int i = 10;
printf(" %d %d %d \n", ++i, i++, ++i);
}
ans: 13 11 11

ASHOKA RAO
THUMUCHERLA

C-language

Code9:
void main(){
int c=5;
c=c/0.5;
printf(%d",c);
}
How we can add two numbers without using + symbol?
#include<stdio.h>
int main(){
int num1,num2;
int result;
printf("enter nos :");
scanf("%d%d",&num1,&num2);
result=num1 - (~(num2-1));
printf("%d",result);
return 0;
}
Explanation:
Consider num1=5, num2=3;
Step1: num2=3 ---------> 0000 0011(binary value of 3) (consider int occupies 1 byte)
Step2: (num2-1)=2-----> 0000 0010(binary value 0f 2)
Step3: ~(num2-1)------> 1111 1101------>(253=is the value of -3)(0 to 255 range of I byte)
Step4: num1-(-3)
Step5: 5-(-3)
Step6:8
5. Relational Operators
The relational operators compare two operands and determine the validity of a
relationship.
The relational operator returns 1 if condition is true else return 0.
Operator
Greater than

Symb
ol
>

Less than

<

Greater than or
equals

>=

Less than or
equals

<=

Equality

==

For
m
x>
y
x<
y
x
>=
y
x
<=
y
x
==

Operation
true if x is greater than y, false otherwise
true if x is less than y, false otherwise
true if x is greater than or equal to y, false
otherwise
true if x is less than or equal to y, false
otherwise
true if x equals y, false otherwise

ASHOKA RAO
THUMUCHERLA

C-language
y
Inequality

!=

x !=
y

true if x does not equal y, false otherwise

Code1:
#include <stdio.h>
#include <conio.h>
void main(){
int a=6, b=2;
clrscr();
printf("\n\n A<=B : %d",(a<=b)); // 0 - False
printf("\n\n A>B : %d",(a>b)); // 1 - True
printf("\n\n A!=B : %d",(a!=b)); // 1 - True
}
Code2:
#include<stdio.h>
int main(){
int a=5,b=3,c=2,d;
d = a++ >= b-- == ++c <=a;
printf("[%d][%d][%d][%d]",a,b,c,d);
return 0;
}
Code3:
void main(){
int a=5, b=3,c=7,d=5,e,f,g,h;
clrscr();
e = a++ != d--;
f = ++b == d++;
g = c-- >= ++d;
h = ++d >= ++a;
printf(%d,%d,%d,%d,%d,%d,%d,%da,b,c,d,e,f,g,h);
}

6. Logical Operators
It is the operator which is primarily used to check more than one condition.
These operator returns 1 if condition is true else return 0.
The operators are &&,||,!
Operator
&&
||

Description
Called Logical AND operator. If both the operands are non zero
then condition becomes true.
Called Logical OR Operator. If any of the two operands is non

ASHOKA RAO
THUMUCHERLA

C-language
zero then condition becomes true.
!

Called Logical NOT Operator. Use to reverses the logical state of


its operand. If a condition is true then Logical NOT operator will
make false.

The below table represents the truth table of logical operators:


When A is
T
F
T
F

When B is
T
T
F
F

A&&B is
T
F
F
F

A||B is
T
T
T
F

!A is
F
T
F
T

!B is
F
F
T
T

Note the followings:


C Generally denotes 1 for True and 0 for False. (While dealing with conditions )
The operands(conditions) of logical-AND and logical-OR expressions are evaluated
from left to right. If the value of the first operand(condition) is sufficient to
determine the result of the operation, the second operand is not evaluated. This is a
very important point to remember in our minds.
If the first operand of a logical-AND operation is equal to 0 (FALSE), the second
operand is not evaluated.
If the first operand of a logical-OR operation is equal to 1 (TRUE), the second
operand is not evaluated.
#include <stdio.h>
#include <conio.h>
void main(){
int no1=2, no2=5;
clrscr();
printf("%d",(no1 && no2));
printf("%d",(no1 || no2));
}
#include<stdio.h>
int main(){
int a=5,b=3,c=2,d=3,e,f,g,h;
e = (b++ == ++c) || (--b != d--);
f = (b-- != d++) && (--c <= --a);
g = (c++ >= --d) || (++b != --c);
h = (e++ <= --f) && (++g != --c);
printf("[%d][%d][%d][%d][%d][%d][%d][%d]",a,b,c,d,e,f,g,h);
return 0;
}
7. compound assignment Operators:

ASHOKA RAO
THUMUCHERLA

C-language

Compound assignment operator can reduce the size of an expression in the


application.
It is used to perform mathematical operations at which the result or output can
affect on operands.
= assign
+= assign with add
-= assign with subtract
*= assign with multiply
/= assign with divide
%= assign with remainder
>>= assign with right shift
<<= assign with left shift
&= assign with bitwise AND (see 3.8)
^= assign with bitwise XOR
|= assign with bitwise OR

All but the first assignment operator are shorthand methods of modifying a variable
or
object. For example, the following two statements are equivalent:
a = a + 17;
---> a += 17;
#include <stdio.h>
int main()
{
int a=18,b=4;
printf("Value of A : %d\n",a);
printf("Using of B : %d\n",b);
b += a ;
printf("Using += (i.e b=b+a): %d",b);
// Change the operator as -=, *=, /=, %=
return 0;
}

8. Bitwise Operators:

Bitwise operators are used for manipulation of data at a bit level.


They can be directly applied to char, short int and long.
The operators are &, |, ^.
These operators first convert the data into corresponding binary form and then
perform the operations according to truth table.

Truth table:

ASHOKA RAO
THUMUCHERLA

C-language

a
0
0
1
1

b
0
1
0
1

a&b
0
0
0
1

a|b
0
1
1
1

a^b
0
1
1
0

~a
1
1
0
0

~b
1
0
1
0

Code1:
#include<stdio.h>
int main()
{
int a=15,b=8,c,d,e;
c=a&b;
d=a|b;
e=a^b;
printf("[%d][%d][%d]",c,d,e);
return 0;
}
Code2:
#include<stdio.h>
int main(){
int i=32, j=0x20, k, l, m;
k=i|j;
l=i&j;
m=k^l;
printf("%d, %d, %d, %d, %d\n", i, j, k, l, m);
return 0;
}

Code3:
#include<stdio.h>
int main(){
int i=4, j=8;
printf("%d, %d, %d\n", i|j&j|i, i|j&&j|i, i^j);
return 0;
}

9. Shift Operators

The bitwise shift operators move the bit values of a binary object.
The left operand specifies the value to be shifted.
The right operand specifies the number of positions that the bits in the value are to
be shifted.
The bit shift operators take two arguments, and looks like:
x << n
x >> n

ASHOKA RAO
THUMUCHERLA

C-language
Where x can be any kind of int variable or char variable and n can be any kind of int
variable.
#include<stdio.h>
int main()
{
int a=8,b,c;
b = a << 2 ;
c = a >> 2 ;
printf("[%d][%d]",b,c);
return 0;
}
Theoretical formulas:
There are some theoretical formulas to shift the bits either to right side or to left side.
For right shifting : n/2s
For left shifting
: n*2s
Where n is the data that you are going to shift
s is the number of shifting bits
Code1:
void main(){
char ch='a';
int i;
i=ch<<1;
printf("%c",i);
getch();
}
Code2:
#include<stdio.h>
int main(){
printf("%d >> %d %d >> %d\n", 4 >> 1, 8 >> 1);
return 0;
}

o/p:2 >> 4 Garbage value >> Garbage value


code3:
#include<stdio.h>
int main(){
printf("%d %d\n", 32<<1, 32<<0);
printf("%d %d\n", 32<<-1, 32<<-0);
printf("%d %d\n", 32>>1, 32>>0);
printf("%d %d\n", 32>>-1, 32>>-0);
return 0;

ASHOKA RAO
THUMUCHERLA

C-language
}

Code4:
#include<stdio.h>
int main(){
unsigned int res;
res = (64 >>(2+1-2)) & (~(1<<2));
printf("%d\n", res);
return 0;
}

Code5:
#include<stdio.h>
int main(){
unsigned char i = 0x80;
printf("%d\n", i<<1);
return 0;
}

Type Conversion

When an operator's operands are of different data types, C automatically converts


them to the same data type.
This can affect the results of mathematical expressions.
In C type conversion can be done by two ways, viz.

syntax:
(type_name) expression
Example
val = (int)number;
1)Automatic Conversion:
When a value is converted to a higher type, it is said to be promoted. Let's look at
the specific rules that govern the evaluation of mathematical expressions.
Rule 1: chars, shorts, unsigned shorts are automatically promoted to int.
Rule 2: When an operator works with two values of different data types, the lower data
type is promoted to a higher data type.
2)Type Casting:
Type casting means to convert a higher data type to a lower data type.
For the purpose of type casting we require to use the type case operator, which lets
you manually promote or demote a value.
It is a unary operator which appears as the data type name followed by the operand
inside a set of parentheses.
Consider the following example where the cast operator causes the division of one
integer variable by another to be performed as a floating-point operation:

ASHOKA RAO
THUMUCHERLA

C-language

#include <stdio.h>
main()
{
int sum = 17, count = 5;
double mean;
mean = (double) sum / count;
printf("Value of mean : %f\n", mean );
}
Note: It should be noted here that the cast operator has precedence over division,
so the value of sum is first converted to type double and finally it gets divided by
count yielding a double value. Type conversions can be implicit which is performed
by the compiler automatically, or it can be specified explicitly through the use of the
cast operator. It is considered good programming practice to use the cast operator
whenever type conversions are necessary.
Integer Promotion
Integer promotion is the process by which values of integer type "smaller" than int
or unsigned int are converted either to int or unsigned int. Consider an example of adding
a character in an int:

#include <stdio.h>
main()
{
int i = 17;
char c = 'c'; /* ascii value is 99 */
int sum;
sum = i + c;
printf("Value of sum : %d\n", sum );

ASHOKA RAO
THUMUCHERLA

C-language
}
Note: Here value of sum is coming as 116 because compiler is doing integer promotion
and converting the value of 'c' to ascii before performing actual addition operation.
Usual Arithmetic Conversion
The usual arithmetic conversions are implicitly performed to cast their values in a
common type. Compiler first performs integer promotion, if operands still have different
types then they are converted to the type that appears highest in the following hierarchy:
#include <stdio.h>
main()
{
int i = 17;
char c = 'c'; /* ascii value is 99 */
float sum;
sum = i + c;
printf("Value of sum : %f\n", sum );
}
Value of sum : 116.000000
NOTE: Here it is simple to understand that first c gets converted to integer but because
final value is double, so usual arithmetic conversion applies and compiler convert i and c
into float and add them yielding a float result.

Operator Precedence Table


This page lists C operators in order of precedence (highest to lowest).
Their associativity indicates in what order operators of equal precedence in an expression
are applied.
Operator

Description

Associativity

ASHOKA RAO
THUMUCHERLA

C-language
()
[]
.
->
++ -++ -+!~
(type)
*
&
sizeof

Parentheses (function call) (see Note 1)


Brackets (array subscript)
Member selection via object name
Member selection via pointer
Postfix increment/decrement (see Note 2)
Prefix increment/decrement
Unary plus/minus
Logical negation/bitwise complement
Cast (convert value to temporary value of type)
Dereference
Address (of operand)
Determine size in bytes on this implementation

left-to-right

right-to-left

* / %
Multiplication/division/modulus
left-to-right
+ Addition/subtraction
left-to-right
<< >>
Bitwise shift left, Bitwise shift right
left-to-right
< <=
Relational less than/less than or equal to
left-to-right
> >=
Relational greater than/greater than or equal to
== !=
Relational is equal to/is not equal to
left-to-right
&
Bitwise AND
left-to-right
^
Bitwise exclusive OR
left-to-right
|
Bitwise inclusive OR
left-to-right
&&
Logical AND
left-to-right
||
Logical OR
left-to-right
?:
Ternary conditional
right-to-left
=
Assignment
right-to-left
+= -=
Addition/subtraction assignment
*= /=
Multiplication/division assignment
%= &=
Modulus/bitwise AND assignment
^= |=
Bitwise exclusive/inclusive OR assignment
<<= >>=
Bitwise shift left/right assignment
,
Comma (separate expressions)
left-to-right
Note 1: Parentheses are also used to group sub-expressions to force a different
precedence; such parenthetical expressions can be nested and are evaluated from
inner to outer.
Note 2: Postfix increment/decrement have high precedence, but the actual
increment or decrement of the operand is delayed (to be accomplished sometime
before the statement completes execution). So in the statement y = x * z++; the
current value of z is used to evaluate the expression (i.e., z++ evaluates to z)
and z only incremented after all else is done.

ASHOKA RAO
THUMUCHERLA

C-language

CONTROL STATEMENTS
OBJECTIVE:

Control structures are one of the most fundamental concepts in any programming
language you will come across. If you want to know C, and if you want to learn any
language, you must have a firm grip on the control structures of the language.
Execution of a program begins at the main () function.
Statements within the main () function are then executed from top to down style.
The first statement, then the second and so forth, until the end of the main ()
function is reached in real C/C++ program.
The order of the execution of the statements within the main () body may be
redirected, not in sequence anymore.
This concept of changing the order in which statements are executed is called
program control and is accomplished by using program control statements. This is
how we can control the program flows.

OVERVIEW:
In this chapter you will learn:
The essentials of counter-controlled repetition.
How to use the while, for and dowhile repetition statements to execute
statements in a program repeatedly.
To understand multiple selection using the switch selection statement.
To use the break and continue program control statements to alter the flow of
control.
To use the logical operators to form complex conditional expressions in control
statements.
Program Control Types: There are three types of program controls,
Sequence control structure:
Sequence instruction means executing one instruction after another, in the order in
which they occur in the source file. This is usually built into the language as a default
action, as it is with C. If an instruction is not a control statement, then the next instruction
to be executed will simply be the next one in sequence.
Selection structures:
Selection means executing different sections of code depending on a specific
condition or the value of a variable. This allows a program to take different courses of
action depending on different conditions. Those are if, if-else, nested if, ifelse if and
switch...case...break:
Repetition:

ASHOKA RAO
THUMUCHERLA

C-language
Repetition/Looping means executing the same section of code more than once. A
section of code may either be executed a fixed number of times, or while some condition
is true. Those are for, while and do...while
Terms used
Selection: consists of if and switch statements.
Iteration (Loops): consists of while and for statements.
Jump: consists of goto, break, continuo, and return switch statements.
Label: consists of case and default statements.
Expression: Built with operators and operands.
Block: code written inside the curly braces.

USES:
Operation is simple to trace
Structures are self-documenting
Structures are easy to define in flowcharts
Structured programming increases programmer productivity
Structures lead to functions
KEYWORDS:
auto
double
break
else
case
enum
char
extern
const
float
continue
for
default
goto
do
if

int

struct
long
switch
register
typedef
return
union
short
unsigned
signed
void
sizeof
volatile
static
while

Note: The words in bold print are used in control statements.


Conditional statements: These are the statements which alter the flow of execution and
provide better control to the programmer on the flow of execution of statements. We have
three types of control statements those are
1. Conditional control statements
2. Loop control statements
3. Transfer control statements

ASHOKA RAO
THUMUCHERLA

C-language

CONTROL STATEMENS

CONDITIONAL CONTROL STATEMENS

LOOP CONTROL STATEMENS


BRANCHING STATEMENS

if

do-while

If-else

while

nested-if

for

If-else ladder

nested loops

break
continue
goto
return

switch

if -else:
Syntax:
if<condition>
{
//statements
}
[else
{
//statements
}]

exit

flow chart representation:

From the above syntax we can easily understand that how it will work. If the if condition is
TRUE, then the statements written inside the if-block will be executed. If the condition is
false (if<false>), then the else-block is executed.

Note: Here else-block is completely optional. If you want to provide information


through that block then you can provide otherwise you can leave.

ASHOKA RAO
THUMUCHERLA

C-language

#include<stdio.h>
#include<conio.h>
main(){
int n;
clrscr();
printf("enter one number :");
scanf("%d",&n);
if(n%2==0){
printf("even number");
}
else{
printf("odd number");
}}
void main() {
if (1)
printf("Hai");
else
CW: unreachable code in function main
printf(bye)
}
NOTE: No need to write the statements in a block if you want to write only one
statement as if block statement. That means COMPILER will recognize that the
statement followed by the if<cond> is the that if block statement.

Void main() {
if (1)
printf("Hello World!");
printf("Hai!");
}}
NOTE: in the above program we have to write two statements inside the block,
we have to make the statements as block by using {}, otherwise COMPILER will
Example3:
thinks that the second statement is the statement that is belongs to outside the
block.
Void main() {
if (1)
printf("if block statement");
printf("outside if block");
else
//CE: misplaced else
printf("else block statement");
}}

ASHOKA RAO
THUMUCHERLA

C-language

Void main(){
if (1){
printf("Hello World!");
printf("inside if block");
}
printf("outside of if block");
else{
//CE:
printf("inside else block");
}}
NOTE: else block should be followed by if block, you should not write any
statements between these two blocks.
In computer programming, ?: is a ternary operator that is part of the syntax for a
basic conditional expression in several programming languages. It is commonly referred to
as the conditional operator or inline if (iif)
main(){
int a=20;
int b=30;
int max=a > b ? a : b;
printf(%d,max);
}
Ifelseif: The if....else statement is an extension of the simple if statement. The
general form is
if<cond>{
//statements
}
else if{
//statements
}
else{
//statements
}

Code1:
void main(){
int a=10,b=30,c=20;

ASHOKA RAO
THUMUCHERLA

C-language
if ((a>b)&&(a>c))
printf("a is big");
else if (b>c)
printf("b is big");
else
printf("c is big");
}
Code2:
Void main(){
int a=70, b=60,c=80;
int max=( a > b ) && ( a > c ) ? a : ( b > c ) ? b : c ;
printf(%d,max);
}
Nested- if: if there is a need to check one condition depend on another condition then we
can go for nested-if
Syntax:
if (<cond>)
if (<cond>)
if (<cond>)
//statements
else
//statements
else
//statements
else
//statements
Leap year program:
#include<stdio.h>
#include<conio.h>
main() {
int leap_year;
clrscr();
printf("enter one year:");
scanf("%d",&leap_year);
if(leap_year%100==0){
if(leap_year%400==0)
printf("%d is a leap year",leap_year);
else
printf("%d is not a leap year",leap_year);
}

ASHOKA RAO
THUMUCHERLA

C-language
else{
if(leap_year%4==0)
printf("%d is a leap year",leap_year);
else
printf("%d is not a leap year",leap_year);
}
getch();
}
void main()
{
int n;
clrscr();
printf("enter one year:");
scanf("%d",&n);
(n%100==0)&&(n%400==0)||(n%100!=0)&&(n%4==0)?printf("leap"):printf("not a leap");
getch();
}
Do-while: It is the loop control statement, which executes the statements written inside
this block repeatedly, as long as the condition is true.
Syntax:
do
{
//statements;
}
while (<condition>);

program:
int main()
{
int i=1;
do
{
printf("i value :%d\n",i);
i++;
}while (i<=10);
return 0;
}
NOTE: if there is a need to the programmer that the statements written inside dowhile block must be executed once even though the condition is false, then we can
go for do-while loop. That means this loop control statement will execute the
statements for the first time, then only it will check the condition, if the condition is
false, execution will be terminated. If the condition is true, then it will continue the

ASHOKA RAO
THUMUCHERLA

C-language

The following program explains the flow of execution if the condition is false for the first
time.
void main(){
int i=1;
do{
printf("i value :"+i);
i++;
}while (i>10);
}

While: This is also a loop control statement, but in while-loop, the condition is tested first
and then only the statements are executed.
Syntax:
while (<cond>)
{
//statements
}

Code1:
int main()
{
int i=1;
while (i>10)
{
printf("i value :%d\n",i);
i++;
}
return 0;
}
Code2:
Void main(){
while(1){
printf("inside while loop");
}}
Code3:
Void main(){
while(1){
printf("inside while loop");
}

ASHOKA RAO
THUMUCHERLA

C-language
printf("outside the while loop"); //CW: unreachable statement
}
Code4:
Void main(){
int b=1;
while(b){
printf("inside while loop");
}
printf("outside the while loop");
}
Code5:
Void main(){
while(0){ //CE: unreachable statement
printf("inside while loop");
}}
Code6:
Void main(){
int b=0;
while(b){
printf("inside while loop");
}
printf("outside the while loop");
}}
Code7:
void main(){
int i=0;
int j=0;
while(i<=2){
while(j<=2){
printf("inside inner while loop");
j++;
}
printf("inside outer while loop");
i++;
}
printf("outside the while loop");
}}
Code8:
Void main(){
int i=0;
while(i<=2){
int j=0;
while(j<=2){
printf("inside inner while loop");

ASHOKA RAO
THUMUCHERLA

C-language
j++;
}
printf("inside outer while loop");
i++;
}
printf("outside the while loop");
}}
Code8:
Void main(){
int i=0;
while(i++<=4){
while(i++<=4){
printf("inside inner while loop");
}
printf("inside outer while loop");
}
printf("outside the while loop");
}
Code9:
Void main(){
int i=0;
while(++i<=4){
while(++i<=4){
printf("inside inner while loop");
}
printf("inside outer while loop");
}
printf("outside the while loop");
}
Out of do-while and while, which is efficient:
In a do-while loop, the statements are executed without testing the condition, the
first time. From the second time only the condition is observed. This means that the
programmer does not have control right from the beginning of its execution. In a while
loop, the condition is tested first and then only the statements are executed. This means it
provides better control right from the beginning. Hence, while loop is more efficient than
do-while loop.

for loop: The for loop is also same as do-while or while loop, but it is more compact

(binding together) syntactically. The for loop executes a group of statements as long as a
condition is 1.
Syntax:
for(expr1;expr2;expr3)
{

ASHOKA RAO
THUMUCHERLA

C-language
//statements
}
Expr1 is the initialization expression
Expr2 is the conditional expression
Expr3 is the modifying (increment (or) decrement) expression
Code1:
Void main(){
for(int i=1;i<=10;i++){
printf("i value is :"+i);
}
printf("outside of for-loop");
}
Code2:
Voi d main(){
int I;
for( i=1;1;i++){
printf("i value is :"+i);
}
printf("outside of for-loop");//CW:unreachable statement
}
Code3:
Voi d main(){
int b=1,i;
for( i=1;b;i++){
printf("i value is :"+i);
}
printf("outside of for-loop");//CW:unreachable statement
}
Code4:
Voi d main(){
int i;
for( i=1;0;i++){
printf("i value is :"+i);
}
printf("outside of for-loop");
}
Code5:
Voi d main(){
int b=0,i;
for( i=1;b;i++){

ASHOKA RAO
THUMUCHERLA

C-language
printf(%d,i);
}
printf("outside of for-loop");
}
Code6:
Voi d main(){
for( ; ; ){
printf("inside for loop");
}}
Code7:
Voi d main(){
for( ; ; ){
printf("inside for loop");
}
printf("outside of for-loop");
}
Nested for loops:
We can also write the for-loop inside another for-loop called as nested for-loops.
Programs to print tables, patterns, matrix form..
Void main(){
int i,j;
clrscr();
for(i=1;i<=5;i++){
for(j=1;j<=5;j++)
printf("* ");
printf("\n");
}}
switch statement:
When there are several options and we have to choose only one option from the
available ones, we can use switch statement. Depending on the selected option, a
particular task can be performed. A task represents one or more statements.
Syntax:
switch(variable)
{
case value1 : statements1;
case value2 : statements2;
case value3 : statements3;
.
[default
: default statements;]
}

ASHOKA RAO
THUMUCHERLA

C-language
void main()
{
char color='g';
switch(color){
case 'r' : printf("color is red ");
case 'g' : printf("color is green ");
case 'b' : printf("color is blue ");
case 'o' : printf("color is orange ");
default :printf("no color ");
}
}

Here depending upon the value of the variable, a particular task (statements) will
be executed.
But the output of the above program is not as expected. We expected that it would
display Green, but it is displaying all colors starting from the Green color. What
might be the reason? When color value is g, it has displayed Green and after that it
has come down to execute the rest of the statements under it leading to the
preceding output.

NOTE: The solution is to come out of the switch statement, after displaying
Green. For this purpose, we can use break statement.One of the used of break
is to terminate a loop and come out of it. Another use of break statement is to
come out of the switch block.
Void main(){
char color='g';
switch(color){
case 'r' : printf("color is red ");
break;
case 'g' : printf("color is green ");
break;
case 'b' : printf("color is blue ");
break;
default :printf("no color ");
}}
break statement:
break statement ca e used in 3 ways.
1. break is used inside a loop to come out of it.
2. break is used inside the switch block to come out of the switch block.
3. break can be used in nested blocks to go to the end of a block. Nested blocks
represent a block written within another block.
Code1:
Void main(){
for(int i=1;i<=10;i++){
if(i==6)

ASHOKA RAO
THUMUCHERLA

C-language
break;
printf("%d,i);
}}
Code2:
Void main(){
for(int i=1;i<=10;i++){
break;
printf("i value is : "+i);
}}
Code3:
Void main(){
for(int i=1;i<=10;i++){
for (int j=1;j<=10 ;j++ ){
if(i==j)
break;
printf("i : "+i+"\tj: "+j);
}}}
Continue:
Continue statement is a jump statement.
The continue statement can be used only inside for loop, while loop and do-while
loop.
Execution of these statement does not cause an exit from the loop but it suspend
the execution of the loop for that iteration and transfer control back to the loop for
the next iteration.
Code1:
Void main(){
for(int i=1;i<=10;i++){
if(i==5)
continue;
printf("i value is :"+i);
}}
Code2:
Void main(){
for(int i=1;i<=10;i++){
for (int j=1;j<=10 ;j++ ){
if(i==j)
continue;
printf("i : "+i+"\tj: "+j);
}}}

ASHOKA RAO
THUMUCHERLA

C-language

goto:

C supports an unconditional control statement that is goto.


goto is used to transfer control from one point to other in a C program.
goto is a branching statement.
It requires a label.
goto is a keyword.

The syntax of goto statement is:


goto END:
................
................
................
END:
................
Void main(){
int i=0;
clrscr();
top:
printf("%d\n",i);
i++;
if(i<=10)
{
goto top;
}}
Logical programming(interview codes):
PROGRAM TO PRING SUM OF FIRST N NUMBERS
main()
{
int n,sum=0,i;
clrscr();
printf("enter the limit:");
scanf("%d",&n);
for(i=1;i<=n;i++){
sum=sum+i;
}
printf("sum of first %d numbers is :%d",n,sum);
getch();
}

ASHOKA RAO
THUMUCHERLA

C-language

PRIME NUMBER PROGRAM:


main(){
int n,i,j,count=0;
clrscr();
printf("enter one number :");
scanf("%d",&n);
for(i=1;i<=n;i++){
count=0;
for(j=1;j<=i;j++){
if(i%j==0){
count++;
}}
if(count==2)
printf("%d\t",i);
}
getch();
}
PROGRAM TO PRINT SUM OF DIGITS OF INPUT NUMBER
main(){
int n,i,temp,sum=0,r;
clrscr();
printf("enter one number :");
scanf("%d",&n);
temp=n;
while(n>0)
{
r=n%10;
sum=sum+r;
n=n/10;
}
printf("the sum of digits of %d is :%d",temp,sum);
getch();
}
PERFECT NUMBER:
main()
{
int n,i,sum=0;
clrscr();
printf("enter one number :");
scanf("%d",&n);
for(i=1;i<n;i++){
if(n%i==0){
sum=sum+i;
}}

ASHOKA RAO
THUMUCHERLA

C-language
if(n==sum){
printf("perfect number");
}
else
printf("not a perfect number");
getch();
}
FACTORIAL OF A GIVEN NUMBER:
main(){
int n,i,fact=1;
clrscr();
printf("enter one number:");
scanf("%d",&n);
for(i=1;i<=n;i++)
fact=fact*i;
printf("the factorial of %d is :%d",n,fact);
getch();
}
ARMSTRONG NUMBER:
main(){
int n,i,temp,sum=0,r;
clrscr();
printf("enter one number :");
scanf("%d",&n);
temp=n;
while(n>0)
{
r=n%10;
sum=sum+(r*r*r);
n=n/10;
}
if(temp==sum)
printf("armstrong number");
else
printf("not an armstrong number");
getch();
}
STRONG NUMBER:
main()
{
int n,i,temp,sum=0,r,fact;
clrscr();
printf("enter one number :");
scanf("%d",&n);

ASHOKA RAO
THUMUCHERLA

C-language
temp=n;
while(n>0)
{
r=n%10;
fact=1;
for(i=1;i<=r;i++)
fact=fact*I;
sum=sum+fact;
n=n/10;
}
if(temp==sum)
printf(strong number");
else
printf("not a strong number");
getch();
}
TO PRINT MATHEMETICAL TABLE
main()
{
int n,i;
clrscr();
printf("enter one number to print corresponding table:");
scanf("%d",&n);
for(i=1;i<=10;i++){
printf("%d*%d=%d\n",i,n,i*n);
}
getch();
}
TO PRINT MULTIPLE MATHEMETICAL TABLES
main(){
int i,j,n;
clrscr();
printf("enter one number(<=10):");
scanf("%d",&n);
if(n>10)
exit();
printf("the corresponding tables are :\n");
for(i=1;i<=10;i++){
for(j=1;j<=n;j++){
printf("%d*%d=%d\t",i,j,i*j);
}
printf("\n");
}
getch();
}

ASHOKA RAO
THUMUCHERLA

C-language

PALINDROME NUMBER:
main(){
int n,i,temp,sum=0,r,fact;
clrscr();
printf("enter one number :");
scanf("%d",&n);
temp=n;
while(n>0)
{
r=n%10;
sum=sum*10+r;
n=n/10;
}
if(temp==sum)
printf(palindrome number");
else
printf("not a palindrome number");
getch();
}
FIBANOCCI SERIES:
main()
{
int n,i,a=0,b=1,,sum=0;
clrscr();
printf("enter one number :");
scanf("%d",&n);
for(i=1;i<=n;i++){
printf(%d\t,a);
sum=a+b;
a=b;
b=sum;
}}
Code1:
Void main(){
int i=2;
clrscr();
while(i++<=4){
int j=2;
while(j++<=4){
printf("j=%d\n",j);
}
printf("i=%d\n",i);
}
printf("final i:%d",i);
printf("\nfinal j=%d",j);

ASHOKA RAO
THUMUCHERLA

C-language
getch();
}
Code2:
main(){
int i,j;
clrscr();
for(i=1;i<=5;i++){
for(j=1;j<=5;j++)
printf("* ");
printf("\n");
}}
Code3:
main(){
int i,j;
clrscr();
for(i=1;i<=5;i++){
for(j=1;j<=i;j++)
printf("* ");
printf("\n");
}}
Code4:
main(){
int i,j;
clrscr();
for(i=1;i<=5;i++){
for(j=1;j<=i;j++)
printf(%d ,i);
printf("\n");
}}
Code5:
main(){
int i,j;
clrscr();
for(i=1;i<=5;i++){
for(j=1;j<=i;j++)
printf("%d",j);
printf("\n");
}}
Code6:
main(){
int i,j;
clrscr();

ASHOKA RAO
THUMUCHERLA

C-language
for(i=1;i<=5;i++){
for(j=i;j<=5;j++)
printf("* ");
printf("\n");
}}
Code7:
main(){
int i,j,k;
clrscr();
for(i=1;i<=5;i++){
for(j=i;j<5;j++)
printf(" ");
for(k=1;k<=i;k++)
printf("*");
printf("\n");
}}
Code8:
int i=2,j=2;
while(i+1?i:j++)
printf(%d,i);
Code9:
int i,j;
i=j=2;
while(--i&&j++)
printf(%d%d,i,j);

Code10:
for(++i;++i;++i){
printf(%d,i);
if(i==4)
break;
}
Code11:
int i=4;
for(--i;--i;i--)
printf(%d,i);
Code12:
int i=1;
for(i=0;i=-1;i=1){
printf(%d,i);
if(i!=1)

ASHOKA RAO
THUMUCHERLA

C-language
break;
}
Code13:
for(;;)
printf(%d,10);
Code14:
int i;
for(i=0;i<=5;i++);
printf(%d,i);
Code15:
char c=125;
do{
printf(%d,c);
}while(c++);
Code16:
int x=123;
int i=printf(naresh);
for(x=0;x<=i;x++)
printf(%d,x);
Code17:
int c=0;
for(; (c=printf(hai))>=5;c++)
printf(bye);
Code18:
int c=0;
for(; (c=printf(hai))==3;c++)
printf(bye);
Code19:
for(i=2;i<=6;i=i+2)
printf(%d\t,i+1);
for(i=2;i!=11;i=i+3)
printf(%d\t,i+1);
Code20:
for(i=2;i<=6;i=i+2);
printf(%d\t,i+1);
Code21:
int i;
if(i=0)
printf(hell);
else
printf(heaven);

ASHOKA RAO
THUMUCHERLA

C-language

Code22:
int i,j;
for(i=5,j=0;i==5,j<5;i++,j++)
printf(%d%d,i,j);
Code23:
int i=3,j=5;
while(--i,--j)
printf(%d%d,i,j);
Code24:
int a=2,b=3,c=5;
if(a>b)
if(b>c)
printf(inner);
else
printf(outer);
Code25:
int x;
for(x=-1;x<=10;x++)
{
if(x<5)
continue;
else
break;
printf(%d,x);
}
Code26:
int a=10;
switch(a)
{
}
printf(c language);
Code27:
int i=10,j=15;
if(i%2=j%3)
printf(c-lang);
Code28:
int s=0;
while(s++<10)
{
if(s<4&&s<9)
continue;

ASHOKA RAO
THUMUCHERLA

C-language
printf(%d,s);
}
Code29:
#include <stdio.h>
void main(void)
{
int i = 3, j = 5;
i = i + 1;
j = j + i + 1;
printf("%d %d\n", i + 1, j - 1);
printf("%d %d\n", i, j);
}

Code30:
#include <stdio.h>
void main(void)
{
double x = 13.5, y = -23.2;
x = (x / 2) * -1 + y;
y = 13 / 2 - 2;
printf("%f %.2f\n", x, y);
}
Code31:
#include <stdio.h>
main()
{
int i = 3;
int j = 4;
float f1 = i / j;
float f2 = (float) i / j;
printf("3 / 4 == %g or %g depending on the type used.\n" , f1, f2);
}

Code32:
main()
{
int i=3;
switch(i)
{
default:printf("zero");
case 1: printf("one");
break;
case 2:printf("two");
break;
case 3: printf("three");

ASHOKA RAO
THUMUCHERLA

C-language
break;
}
}
Code33:
#include<stdio.h>
main()
{
int i=1,j=2;
switch(i)
{
case 1: printf("good");
break;
case j: printf("bad");
break;
}
}
Code34:
main()
{
int i =0;j=0;
if(i && j++)
printf("%d..%d",i++,j);
printf("%d..%d,i,j);
}
Code35:
main()
{
int x,y=2,z,a;
if(x=y%2) z=2;
a=2;
printf("%d %d ",z,x);
}
Code36:
main()
{
unsigned int i=65000;
while(i++!=0);
printf("%d",i);
}
Code37:
main()
{
int i=0;

ASHOKA RAO
THUMUCHERLA

C-language
while(+(+i--)!=0)
i-=i++;
printf("%d",i);
}
Code38:
main ( )
{ float a = 0.5, b = 0.7;
if (b < 0.8)
if (a < 0.5) printf (abcd);
else printf (pqr);
else printf (jklf);
}
Code39:
main()
{
int i=6;
switch(i)
{
default:i+=2;
case 4:i=4;
case 5:i++;
break;
}
printf(%d,i);
}
Code40:
#include<stdio.h>
main()
{
int i=0;
for(i=0;i<20;i++)
{
switch(i)
{
case 0:
case 1:
case 5:
default

i+=5;
i+=2;
i+=5;
:
i+=4;
break;

}
printf("i=%d\n",i);
}
}
Code41:

ASHOKA RAO
THUMUCHERLA

C-language

char i=0;
for(;i>=0;i++)
printf(%d\n,i);
Code42:
int num=32765;
while(num++);
printf(%d,num);
Code43:
int x=0,y=1;
if(x=y)
y=7;
else
y=2;
printf(%d,y);
Code44:
int a=10,b=5;
while(--b>=0&&++a)
{
--b;
++a;
}
printf(%d%d,a,b);
Code45:
#include <stdio.h>
Void main()
{
float f1 = 3 / 4;
float f2 = 3 / 4.0;
printf("3 / 4 == %g or %g depending on the type used.\n", f1, f2);
}
Code46:
void main()
{
int p = -200;
char c;
c=p;
printf(%d%d,c++,++c);
}
Code47:
How many times the while loop will get executed if a short int is 2 byte wide?
#include<stdio.h>

ASHOKA RAO
THUMUCHERLA

C-language
int main()
{
int j=1;
while(j <= 255)
{
printf("%c %d\n", j, j);
j++;
}
return 0;
}
Code48:
What will be the output of the program?
#include<stdio.h>
int main()
{
int i=0;
for(; i<=5; i++);
printf("%d,", i);
return 0;
}
Code49:
What will be the output of the program?
#include<stdio.h>
int main()
{
int a = 500, b = 100, c;
if(!a >= 400)
b = 300;
c = 200;
printf("b = %d c = %d\n", b, c);
return 0;
}
Code50:
What will be the output of the program, if a short int is 2 bytes wide?
#include<stdio.h>
int main()
{
short int i = 0;
for(i<=5 && i>=-1; ++i; i>0)
printf("%u,", i);
return 0;
}

ASHOKA RAO
THUMUCHERLA

C-language
Explanation:
for(i<=5 && i>=-1; ++i; i>0) so expression i<=5 && i>=-1 initializes forloop.
expression ++i is the loop condition. expression i>0 is the increment expression.
In for( i <= 5 && i >= -1; ++i; i>0) expression i<=5 && i>=-1 evaluates to one.
Loop condition always get evaluated to true. Also at this point it increases i by one.
An increment_expression i>0 has no effect on value of i.so for loop get executed till the
limit of integer (ie. 65535)
Code51:
What will be the output of the program?
#include<stdio.h>
int main()
{
char ch;
if(ch = printf(""))
printf("It matters\n");
else
printf("It doesn't matters\n");
return 0;
}
Code52:
What will be the output of the program?
#include<stdio.h>
int main()
{
unsigned int i = 65536; /* Assume 2 byte integer*/
while(i != 0)
printf("%d",++i);
printf("\n");
return 0;
}
Code53:
What will be the output of the program?
#include<stdio.h>
int main()
{
int x=1, y=1;
for(; y; printf("%d %d\n", x, y))
{
y = x++ <= 5;
}
printf("\n");
return 0;
}

ASHOKA RAO
THUMUCHERLA

C-language
Code54:
#include<stdio.h>
int main()
{
int i = 5;
while(i-- >= 0)
printf("%d,", i);
i = 5;
printf("\n");
while(i-- >= 0)
printf("%i,", i);
while(i-- >= 0)
printf("%d,", i);
return 0;
}

Code55:
What will be the output of the program?
#include<stdio.h>
int main()
{
int i=3;
switch(i)
{
case 1:
printf("Hello\n");
case 2:
printf("Hi\n");
case 3:
continue;
default:
printf("Bye\n");
}
return 0;
}

Code56:
#include<stdio.h>
int main()
{
int x = 10, y = 20;
if(!(!x) && x)
printf("x = %d\n", x);
else

ASHOKA RAO
THUMUCHERLA

C-language
printf("y = %d\n", y);
return 0;
}

Code57:
What will be the output of the program?
#include<stdio.h>
int main()
{
int i = 1;
switch(i)
{
printf("Hello\n");
case 1:
printf("Hi\n");
break;
case 2:
printf("\nBye\n");
break;
}
return 0;
}
a)the loop in which the statements within the loop are executed at least once is
called
(a) do-while (b) while
(c) for
(d) goto
b)The control automatically passes to the first statement after the loop in
(a) continue statement
(c) switch statement

(b) break statement


(d) if statement

c)The statement which is used to terminate the control from the loop is
(a) break
(b) continue (c) goto
(d) exit
d)the statement that transfers control to the beginning of the loop is called
(a) break statement
(b) exit statement
(c) continue statement
(d) goto statement

e)The way the break is used to take control out of switch and continue to take
control of the beginning of the switch?
A.Yes
B.No

ASHOKA RAO
THUMUCHERLA

C-language
Can we use a switch statement to switch on strings?
A.Yes
B.No
Fill in the blanks in each of the following statements:
a) The dowhile statement tests the loop-continuation condition executing
the loops body; therefore, the body always executes at least once.
ANS: after.
b) The .statement selects among multiple actions based on the possible
values
of an integer variable or expression.
ANS: switch.
c) The statement, when executed in a repetition statement, skips the
remaining statements in the loop body and proceeds with the next iteration of the loop.
ANS: continue.
d) The .operator can be used to ensure that two conditions are both true
before
choosing a certain path of execution.
ANS: && (conditional AND).
e) If the loop-continuation condition in a for header is initially , the program
does not execute the for statements body.
ANS: false.
f)

Every statement with if must also include else.


TRUE

FALSE

[FALSE]
g)
The controlling expression of a switch statement must have a value that is an integer
or a character.
TRUE
FALSE
[TRUE]
h)

The body of any while loop will be executed at least once.


TRUE
FALSE
[FALSE]

ASHOKA RAO
THUMUCHERLA

C-language

Summary of Control Flow Statements

A program is usually not limited to a linear sequence of instructions. During its


process it may require to repeat execution of a part of code more than once
depending upon the requirements or take decisions. For that purpose, C provides
control and looping statements. In this unit, we had seen the different looping
statements provided by C language namely while, dowhile and for.
Using break statement, we can leave a loop even if the condition for its end is not
fulfilled. It can be used to end an infinite loop, or to force it to end before its natural
end.
The continue statement causes the program to skip the rest of the loop in the
present iteration as if the end of the statement block would have reached, causing it
to jump to the following iteration.
Using the goto statement, we can make an absolute jump to another point in the
program. You should use this feature carefully since its execution ignores any type
of nesting limitation. The destination point is identified by a label, which is then
used as argument for the goto instruction. A label is made of a valid identifier
followed by a colon (:).

The if-then statement is the most basic of all the control flow statements. It tells
your program to execute a certain section of code only if a particular test evaluates
to true.

The if-then-else statement provides a secondary path of execution when an "if"


clause evaluates to false. Unlike if-then and if-then-else, the switch statement allows
for any number of possible execution paths.

The while and do-while statements continually execute a block of statements while
a particular condition is true.

The difference between do-while and while is that do-while evaluates its expression
at the bottom of the loop instead of the top. Therefore, the statements within
the do block are always executed at least once.

The for statement provides a compact way to iterate over a range of values. It has
two forms, one of which was designed for looping through arrays.

ASHOKA RAO
THUMUCHERLA

C-language

Functions
INTRODUCTION
In the earlier lessons we have already seen that C supports the use of library
functions, which are used to carry out a number of commonly used operations or
calculations. C also allows programmers to define their own functions for carrying out
various individual tasks. In this lesson we will cover the creation and utilization of such
user defined functions.
OBJECTIVES
After

going through this lesson you will be able to


Explain of function
Introduction user-defined functions
Art of modular programming using functions.
Describe access to function
Define parameters data types specification
Classification of functions
Explain function prototype
Concept of recursion.
Call by value and its limitations

MODULAR APPROACH

The use of user-defined functions allows a large program to be down into a number
of smaller, self-contained components, each of which has some unique, identifiable
purpose. Thus a C program can be modularized through the intelligent use of such
functions.
There are several advantages to this modular approach to program development.
For example many programs require a particular group of instructions to be
accessed repeatedly from several different places within a program.

ASHOKA RAO
THUMUCHERLA

C-language

The repeated instruction can be placed within a single function, which can then be
accessed whenever it is needed.
Moreover, a different set of data can be transferred to the function each time it is
accessed.
Thus, the use of a function avoids the need for redundant (repeating) programming
of the same instructions.

DEFINING A FUNCTION
Before using any function it must be defined in the program. Function definition has
three principal components: the first line, the parameter declarations and the body of the
functions. The first line of a function definition contains the data type of the information
return by the function, followed by function name, and a set of arguments or parameters,
separated by commas and enclosed in parentheses. The set of arguments may be skipped
over. The data type can be omitted if the function returns an integer or a character. An
empty pair of parentheses must follow the function name if the function definition does
not include any argument or parameters.

Function:

A function is a block of code that performs a specific task. It has a name and it is
reusable i.e. it can be executed from as many different parts in a C Program as required.
It also optionally returns a value to the calling program.
Every function has a unique name. This name is used to call function from main()
function. A function can be called from within another function.
SPECIFICATION OF DATA TYPES OF ARGUMENTS(prototype):
The calling portion of a program must contain a function declaration if a function
returns a non-integer value and the function call precedes the function definition.
Function declaration may be included in the calling portion of a program even if it is
not necessary.
It is possible to include the data types of the arguments within the function
declaration.
The compiler will then convert the value of each actual argument to the declared
data type and then compare each actual data type with its corresponding formal
argument.
Compilation error will result if the data types do not agree. We had already been
use, data types of the arguments within the function declaration.
When the argument data types are specified in a function declaration, the general
form of the function declaration can be written as
data-type function name (argument type1, argument type2,
argument type n);

Where data-type is the data type of the quantity returned by the function, function
name is the name of function, and argument type/refer to the data types of the first
argument and so on.
Argument data types can be omitted, even if situations require a function
declaration.

ASHOKA RAO
THUMUCHERLA

C-language

Most C compilers support the use of the keyword void in function definitions, as a
return data type indicating that the function does not return anything.
Function declarations may also include void for the same purpose.
In addition, void may appear in an argument list, in both function definitions and
function declarations, to indicate that a function does not require arguments.

// Function prototype
<return_type><function_name>([<parameter_list>]);
// Function Call
void main()
{
<function_name>([<arguments>]);
}
// Function definition
<return_type><function_name>([<parameter list>])
{
<function_body>;
}
Where:

<return_type> is the data type specifier of the data returned by the function.

<function_name> is the identifier by which it will be possible to call the function.

[<parameter_list>] (as many as needed): Each argument consists of a data type


specifier followed by an identifier, like any regular variable declaration (for example:
int x) and which acts within the function as a regular local variable. They allow
passing arguments to the function when it is called. The different parameters are
separated by commas.

Statements are the function's body. It is a block of statements surrounded by braces


{ }.

An example of Function:
int sum (int x, int y)
{
int result;
result = x + y;
return (result);
}
Function Header

ASHOKA RAO
THUMUCHERLA

C-language
In the first line of the above code
int sum(int x, int y)
It has

three main parts


The name of the function i.e. sum
The parameters of the function enclosed in parenthesis
Return value type i.e. int

Function Body
Whatever is written with in { } in the above example is the body of the function.
Function Prototypes
The prototype of a function provides the basic information about a function which
tells the compiler that the function is used correctly or not.
It contains the same information as the function header contains.
The prototype of the function in the above example would be like
int sum (int x, int y);

Note: The only difference between the header and the prototype is the
semicolon; there must be a semicolon at the end of the prototype.

Function Prototype and Function Definition Example

#include<stdio.h>
#include<conio.h>
void myFunction();
int add(int, int);

prototype

Calling functions
void main()
{
clrscr();
myFunction();
printf("\n\n%d",add(10,15));
myFunction() is the no arguments and no return values function.
getch();
}

void myFunction()
{
printf("This is inside function :D");
}

Called functions

Function add which returns integer value to the calling function and it takes two integers as arguments.

int add(int a, int b)


{
return a+b;
}

ASHOKA RAO
THUMUCHERLA

C-language

Points to remember:
Argument is a parameter which is used to pass into function during function call
Actual argument is a parameter which is available in calling function
Formal argument is a parameter which is available in called function/function
definition
Both actual and formal argument must be same which is declared before main
A function parameter is a variable declared in the prototype or declaration of a function:
void fun(int x); // prototype -- x is a parameter
void fun(int x) {} // declaration -- x is a parameter
An argument is the value that is passed to the function in place of a parameter:
fun(6); // 6 is the argument passed to parameter x
fun(y+1); // the value of y+1 is the argument passed to parameter x
Why we use Functions?
Two reasons
Writing functions avoids rewriting the same code over and over. Suppose that there
is a section of code in a program that calculates area of a triangle. If, later in the
program we want to calculate the area of a different triangle we wont like to write
the same instructions all over again. Instead we would prefer to jump to a section
of code that calculates area and then jump back to the place from where you left
off. This section of code is nothing but a function.

Using functions it becomes easier to write programs and keep track of what they are
doing. If the operation of a program can be divided into separate activities, and
each activity placed in a different function, then each could be written and checked
more or less independently. Separating the code in to modular functions also makes
the pro-gram easier to design and understand.

Types of Functions:
Built In Functions
User Defined Functions

1. Built in Functions: These functions are also called as 'library functions'. These
functions are provided by system. These functions are stored in library files. e.g.
scanf()
printf()
strcpy()
strlwr()

ASHOKA RAO
THUMUCHERLA

C-language

clrscr()

2. User Defined Functions: The functions which are created by user for program are
known as 'User defined functions'.
Add()
Show()
PASSING ARGUMENT TO A FUNCTION
Arguments can be passed to a function by two methods, they are called passing by
value and passing by reference.
When a single value is passed to a function via an actual argument, the value of the
actual argument is copied into the function.
Therefore, the value of the corresponding formal argument can be altered within the
function, but the value of the actual argument within the calling routine will not
change.
This procedure for passing the value of an argument to a function is known as
passing by value.
Classification of functions:
No arguments and No return values functions
With arguments and No return values functions
With arguments and With return values functions
No arguments and With return values functions
Recursion
No arguments and No return values functions: These function do not take
information from the calling function nor do they pass information to calling Program
#include <stdio.h>
#include <conio.h>
void main(){
clrscr();
printf(I am in main function);
show();
printf(I am returned to main after execution of show());
pisplay()
printf(again I am back to main);
printf(end of main(end of program));
}
void display(){
printf(I am in display);
show()
printf(I am back to display after execution of show);
}
void show(){
printf(I am in show);
}

ASHOKA RAO
THUMUCHERLA

C-language

#include <stdio.h>
#include <conio.h>
void add(){
int a, b, c;
clrscr();
printf("\n Enter Any 2 Numbers : ");
scanf("%d %d",&a,&b);
c = a + b;
printf("\n Addition is : %d",c);
}
void main(){
void add();
add();
getch();
}
With arguments and No return values functions

Function accepts argument but it does not return a value back to the calling
Program .
It is Single ( One-way) Type Communication
Generally Output is printed in the Called function

Program1:
#include <stdio.h>
#include <conio.h>
void printno(int a)
{
printf("\n Number is : %d", a);
}
void main()
{
int no;
void printno(int);
clrscr();
printf("\n Enter Number : ");
scanf("%d", &no);
printno(no);
getch();
}
Program2:
#include<stdio.h>
#include<conio.h>
void area(float rad); // Prototype Declaration

ASHOKA RAO
THUMUCHERLA

C-language
void main()
{
float rad;
printf("nEnter the radius : ");
scanf("%f",&rad);
area(rad);
getch();
}
void area(float rad)
{
float ar;
ar = 3.14 * rad * rad ;
printf("Area of Circle = %f",ar);
}
No arguments and With return values functions:

In this type of procedure we can define a function as no arguments.


But the function has to return some value to the calling function.

#include <stdio.h>
#include <conio.h>
int number()
{
int no;
printf("\n Enter Number : ");
scanf("%d",&no);
return no;
}
void main()
{
int no;
int number();
clrscr();
no = number();
printf("\n Number is : %d",no);
getch(
}
With arguments and With return values functions:

Function accepts argument and it return a value back to the calling Program.
It is Double ( Two-way) Type Communication
We can print the resultant data either in called function or in calling function by
returning the value to it.

#include <stdio.h>

ASHOKA RAO
THUMUCHERLA

C-language
#include <conio.h>
int number(int n)
{
return n;
}
void main()
{
int number(int);
int a = number(4);
clrscr();
printf("\n Number is : %d",a);
getch();
}
Recursion (Recursive Function)
Recursion is a process by which a function calls itself repeatedly, until some
specified condition has been satisfied.
The process is used for repetitive computations in which each action is stated in
terms of a precious result.
In order to solve a problem recursively, two conditions must be satisfied.
The problem must be written in a recursive form, and the problem statement must
include a stopping condition.
The best example of recursion is calculation of factorial of a integer quantity, in
which the same procedure is repeating itself.
Factorial of a given number using Recursive function:
int fact=1;
void main(){
int n,i,facto=0;
clrscr();
printf("enter one number:");
scanf("%d",&n);
facto=factorial(n);
printf("factorial of %d is:%d",n,facto);
getch();
}
int factorial(int n){
if(n==1)
return 1;
fact=n*factorial(n-1);
return fact;
}
C code to find the addition of n numbers by recursion:
#include<stdio.h>

ASHOKA RAO
THUMUCHERLA

C-language
int main(){
int n,sum;
printf("Enter the value of n: ");
scanf("%d",&n);
sum = getSum(n);
printf("Sum of n numbers: %d",sum);
return 0;
}
int getSum(n){
static int sum=0;
if(n>0){
sum = sum + n;
getSum(n-1);
}
return sum;
}
PROGRAM
#include<stdio.h>
float add(float,float);
float sub(float,float);
float mul(float,float);
float div(int,int);
void exit(int);
int main(){
int ch;
float a,b,c;
int i,j;
while(1){
printf("\n 1.addition");
printf("\n 2.substraction");
printf("\n 3.multiplication");
printf("\n 4.division");
printf("\n 5.quit");
printf("\n enter the choice :");
scanf("%d",&ch);
if(ch<=3){
printf("enter two numbers :");
scanf("%f%f",&a,&b);
}
if(ch==4){
printf("enter two numbers :");
scanf("%d%d",&i,&j);
}
switch(ch){
case 1: c=add(a,b);
printf("addition of two numbers is:%f",c);
break;

ASHOKA RAO
THUMUCHERLA

C-language

case 2: sub(a,b);
break;
case 3: mul(a,b);
break;
case 4: c=div(i,j);
printf("division of two numbers is:%f",c);
break;
case 5: exit(1);
default:printf("enter the right choice(1/2/3/4):");
}}}
float add(float x,float y){
float z=x+y;
return z;
}
float sub(float a,float b){
printf("substraction of two numbers is :%f",a-b);
}
float mul(float a,float b){
printf("multiplication of two numbers is :%f",a*b);
}
float div(int x,int y){
float z=(float)x/y;
return z;
}
Interview Codes:
Code1:
void abc()
(
++a;
}
void main()
{
int a=1;
clrscr();
printf(%d,a);
abc();
printf(%d,a);
}
Code2:
void main()
{
int a=1;
void xyz(int,int);

ASHOKA RAO
THUMUCHERLA

C-language
xyz(++a,a++);
xyz(a++,++a);
printf(%d,a);
}
xyz(int x,int y)
{
printf(%d%d,x,y);
}
Code3:
#include<stdio.h>
void xyz(int);
void abc(int);
void main()
{
abc(2);
}
void xyz(int x)
{
printf("%d",x);
if(x)
{
xyz(x-1);
}
printf("%d",x);
}
void abc(int a)
{
printf("%d",a);
xyz(a);
if(a)
{
abc(a-1);
}
printf("%d",a);
}

Code4:
void main()
{
int i=10;
f(i,i++);
}
void f(int i, int j)

ASHOKA RAO
THUMUCHERLA

C-language
{
if(i>50)
return;
i+=j;
f(i,j);
printf(%d,i);
}

Code5:
void main(){
int i,j;
i=2,j=3;
fun(i++,j++);
printf(%d%d,i,j);
}
void fun(int i,int j)
{
++i;
++j;
}

ASHOKA RAO
THUMUCHERLA

C-language
Code6:
#include<stdio.h>
int main(){
void show()
{
printf("hai");
}
show();
return 0;
}

Arrays
Objectives:
What are arrays?
How to declare an array?
How to access elements contained in an array?
How to initialize an array?
What happens if an array accesses out of its bunds?
How to pass array elements to a function?
How to sort an array?
How to search for an element in an array?
How to merge two arrays?
What are two dimensional arrays?
How to initialize to dimensional arrays?
Understand the memory map of a two dimensional array?
What are multi dimensional arrays?
Overview:
C stores lists of values in arrays. An array is a group of related memory locations.
These locations are related by the fact that they all have the same name and the
same type. To refer to a particular location or element within the array, we
specify the name of the array and the subscript.

A subscript may be an integer or an integer expression. If a program uses an


expression as a subscript, then the expression is evaluated to determine the
particular element of the array.

It is important to note the difference when referring to the seventh element of


the array as opposed to array element seven. The seventh element has a
subscript of 6, while array element seven has a subscript of 7(actually the eighth
element of the array). This is a source of "off-by-one" errors.

The elements of an array can be initialized in a definition, in assignment


statements and by inputting the values directly into the elements of the array.

If there are fewer initializes than elements in the array, C initializes the
remaining elements to zero.

ASHOKA RAO
THUMUCHERLA

C-language

C does not prevent referencing elements beyond the bounds of an array.

Apply static to a local array definition so the array is not created each time the
function is called and the array is not destroyed each time the function exits.

Arrays that are static are automatically initialized once at compile time. If the
programmer does not explicitly initialize a static array, it is initialized to zero by
the compiler.

To pass an array to a function, the name of the array is passed. To pass a single
element of an array to a function, simply pass the name of the array followed by
the subscript (contained in square brackets) of the particular element.

C passes arrays to functions by referencethe called functions can modify the


element values in the callers' original arrays.

To receive an array argument, the function's parameter list must specify that an
array will be received. The size of the array is not required (for single-subscripted
arrays) in the array brackets.

C provides the special type qualifier const to prevent modification of array values
in a function. When an array parameter is preceded by the const qualifier, the
elements of the array become constant in the function body and any attempt to
modify an element of the array in the function body results in a compile time
error.

When a function receives a single-subscripted array as an argument, the array


brackets are empty in the function's parameter list. The first subscript of a
multiple-subscripted array is not required either, but all subsequent subscripts
are required. The compiler uses these subscripts to determine the locations in
memory of elements in multiple-subscripted arrays.

To pass one row of a double-subscripted array to a function that receives a


single-subscripted array, simply pass the name of the array followed by the
subscript (in square brackets) of that row.

void main()
{
int x;
x=5;
x=10;
printf(x=%d,x);
}
When the above program is executed, 10 is printed. This is because, when the value 10 is
assigned to x, the old value of x is lost. Thus, ordinary variables are capable of holding
only one value at a time. However, there are situations in which we would want to store
more than one value at a time in a single variable. For example, arranging the aggregate
marks obtained by 100 students in ascending order. In such a case we have two options to
store these marks in memory.
a) Construct 100 variables to store aggregate marks obtained by 100 different
students i.e., each variable contains one student marks.

ASHOKA RAO
THUMUCHERLA

C-language
b) Construct one variable called array capable of storing or holding all the hundred
values.
Obviously, the second alternative is better. A simple reason for this is, it would be much
easier to handle one variable than handling 100 different variables. Moreover, there are
certain logics which cannot be dealt with, without the use of an array.

Array is a collection of same type elements under the same identifier referenced by
index number.
Arrays are widely used within programming for different purposes such as sorting,
searching and etc.
Arrays are of two types single dimension array and multi-dimension array.
Each of this array type can be of either static array or dynamic array.
Static arrays have their sizes declared from the start and the size cannot be
changed after declaration.
Dynamic arrays that allow you to dynamically change their size at runtime, but they
require more advanced techniques such as pointers and memory allocation.

Declaration of an Array
Arrays must be declared before they can be used in the program. Standard array
declaration is as,
Syntax:
Data_type arr_var_name [size];
For example
int myArray[5];
Here int specifies the type of the variable and the word myArray specifies the name of
the variable. The number 5 tells the number of elements of type int that will be in the
array and is called the dimension of the array.
Initializing Arrays
Initializing of array is very simple in c programming. The initializing values are enclosed
within the curly braces in the declaration and placed following an equal sign after the
array name.
Here is an example which declares and initializes an array of five elements of type int.
int myArray [5] = {1, 2, 3, 4, 5};
Note: The elements field within brackets [] which represents the number of elements
the array is going to hold, must be a constant value, since arrays are blocks of nondynamic memory whose size must be determined before execution. In order to create
arrays with a variable length dynamic memory is needed, which is explained in
dynamic memory allocation chapter.

ASHOKA RAO
THUMUCHERLA

C-language
Array can also be initialized after declaration.
int studentAge[4];
studentAge[0]=14;
studentAge[1]=13;
studentAge[2]=15;
studentAge[3]=16;
Array elements occupy consecutive memory locations. Whole array is stored in a
contiguous memory block.

Note: Address of the first element is called the base address and it is also the start
address of an array.
The address of the ith element is given by the following formula,

Addressi = base_address + i*size_of_element


Accessing elements of an array:
Once an array is declared, the individual elements in the array can be referred with
subscript, the number in the brackets following the array name. This number specifies the
elements position in the array. All the array elements are numbered, starting with 0. Thus
myArray[2] is not the second element of the array but the third. In the above declaration,
we use the variable i as a subscript to refer to various elements of the array. This variable
can take different values and hence can refer to the different elements in the array. This
ability to use variables as subscripts marks arrays very useful.
Read and write the data of an array:
#include <stdio.h>
#include <conio.h>
void main(){
int arr[5];
int i;
clrscr();
printf("enter 5 elements into array :\n");
for(i = 0;i<5;i++){
printf("enter element %d :",i+1);
scanf("%d",&arr[i]);
}

ASHOKA RAO
THUMUCHERLA

C-language
printf("the array elements are :\n");
for(i = 0;i<5;i++){
printf("%d\n",arr[i]);
}
}

Note: The elements of an array can be initialized in a definition, in assignment

statements and by inputting the values directly into the elements of the array. If there
are fewer initializes than elements in the array, C initializes the remaining elements
to zero.
#include<stdio.h>
int main()
{
int a[5]={1,2};
int i;
for(i=0;i<5;i++)
printf("%d\n",a[i]);
return 0;
}

Note: C does not prevent referencing elements beyond the bounds of


an array.

#include<stdio.h>
int main()
{
int a[5]={1,2};
int i;
for(i=0;i<10;i++) // accessing the elements beyond the bounds
printf("%d\n",a[i]);
return 0;
}
Write a program to find largest element of an array.
#include <stdio.h>
int main(){
int i;
float arr[10],large;
printf("Enter 10 elements to find largest among them: \n");
for(i=0;i<10;++i)
{
printf("Enter Number %d: ",i+1);
scanf("%f",&arr[i]);
}
large=arr[0];
for(i=1;i<10;++i)

ASHOKA RAO
THUMUCHERLA

C-language
{
if(large<arr[i])
large=arr[i];
}
printf("Largest element = %.2f",large);
return 0;
}
Like integers, characters etc., we can also pass arrays as an argument to a
function.
#include<stdio.h>
#include<conio.h>
void main()
{
void read(int *,int);
void display(int *,int);
int a[5],i,sum=0;
clrscr();
printf("Enter five elements for an array \n");
read(a,5);
printf("The list elements are \n");
display(a,5);
for(i=0;i<5;i++)
{
sum+=a[i];
}
printf("The sum of the elements of the array is %d\n",sum);
getch();
}
void read(int c[],int i)
{
int j;
for(j=0;j<i;j++)
scanf("%d",&c[j]);
fflush(stdin);
}
void display(int d[],int i)
{
int j;
for(j=0;j<i;j++)
printf("%d ",d[j]);
printf("\n");
}
Merging of two array elements:
#include<stdio.h>

ASHOKA RAO
THUMUCHERLA

C-language
#include<conio.h>
void main()
{
int a[10],b[10],c[20],m,n,i,j;
printf("enter the size of array a(<=10):");
scanf("%d",&m);
printf("enter the %d elements of a:",m);
for(i=0;i<m;i++)
scanf("%d",&a[i]);
printf("enter the size of array b(<=10):");
scanf("%d",&n);
printf("enter the %d elements of b:",n);
for(i=0;i<n;i++)
scanf("%d",&b[i]);
for(i=0;i<m;i++)
{
c[i]=a[i];
}
for(j=0;j<n;j++)
{
c[i+j]=b[j];
}
printf("the merged elements are:");
for(i=0;i<m+n;i++)
printf("%d\n",c[i]);
getch();
}
Write a C program to sort the array of 10 elements in descending order.
#include <stdio.h>
void Descend(int c[]);
int main(){
int c[10],i;
for(i=0;i<10;++i){
printf("Enter element %d:",i+1);
scanf("%d",&c[i]);
}
Descend(c);
printf("In descending order: ");
for(i=0;i<10;++i){
printf("%d\t",c[i]);
}
return 0;
}
Descend(int c[]){
int i,j,temp;

ASHOKA RAO
THUMUCHERLA

C-language
for(i=0;i<9;++i)
for(j=i+1;j<10;++j)
{
if(c[i]<c[j]){
temp=c[i];
c[i]=c[j];
c[j]=temp;
}
}
}

Note: C provides the special type qualifier const to prevent modification of array
values in a function. When an array parameter is preceded by the const qualifier, the
elements of the array become constant in the function body and any attempt to
modify an element of the array in the function body results in a compile time error.
#include<stdio.h>
void fun(const int[]);
int main(){
static const int a[5]={1,2};
fun(a);
return 0;
}
void fun(const int a[]){
int i=0;
/*
for(i=0;i<6;i++){
a[i]=i;
}*/
for(i=0;i<6;i++){
printf("%d\n",a[i]);
}
}
Linear search: In computer science, linear search or sequential search is a method
for finding a particular value in a list that consists of checking every one of its elements,
one at a time and in sequence, until the desired one is found.
#include<stdio.h>
#include<conio.h>
void main()
{
int a[100],n,i,key,flag=-1;
clrscr();
printf("enter the size:");
scanf("%d",&n);
printf("enter %d elements into array :",n);

ASHOKA RAO
THUMUCHERLA

C-language
for(i=0;i<n;i++)
scanf("%d",&a[i]);
printf("enter one element to be searched :");
scanf("%d",&key);
for(i=0;i<n;i++)
{
if(key==a[i])
{
printf("successful search\n");
printf("element %d found at location %d",key,i+1);
flag=0;
break;
}
}
if(flag)
printf("unsuccessful search");
getch();
}
Binary search:
A binary search or half-interval search algorithm finds the position of a specified
value (the input "key") within a sorted array. In each step, the algorithm compares the
input key value with the key value of the middle element of the array. If the keys are
match, then a matching element has been found so its index, or position, is returned.
Otherwise, if the sought key is less than the middle element's key, then the algorithm
repeats its action on the sub-array to the left of the middle element or, if the input key is
greater, on the sub-array to the right. If the remaining array to be searched is reduced to
zero, then the key cannot be found in the array and a special "Not found" indication is
returned.
#include<stdio.h>
#include<conio.h>
void main()
{
int a[100],n,i,key,flag=-1,low,mid,high;
clrscr();
printf("enter the size:");
scanf("%d",&n);
printf("enter %d elements into array :",n);
for(i=0;i<n;i++)
scanf("%d",&a[i]);
printf("enter one element to be searched :");
scanf("%d",&key);

ASHOKA RAO
THUMUCHERLA

C-language
low=0;
high=n-1;
while(low<=high)
{
mid=(low+high)/2;
if(key<a[mid])
{
high=mid-1;
}
else if(key>a[mid])
{
low=mid+1;
}
else if(key==a[mid])
{
printf("successful search\n");
printf("element %d found at location %d",key,mid+1);
flag=0;
break;
}
}
if(flag)
printf("unsuccessful search");
getch();
}

Introduction to Two-Dimensional Arrays

Two-dimensional arrays, the most common multidimensional arrays, are used to


store information that we normally represent in table form. Two-dimensional arrays, like
one-dimensional arrays, are homogeneous. This means that all of the data in a twodimensional array is of the same type. Examples of applications involving two-dimensional
arrays include: A seating plan for a room (organized by rows and columns)
Syntax:
<data-type> <array_nm> [row_subscript][column-subscript];
Example:
int arr[3][3];
Initialization of two-dimensional arrays:

Similar to the one-dimensional the two-dimensional arrays are initialized. For


example
int array[2][3] = {1,2,3,4,5,6};

In the above case elements of the first row are initialized to 1,2,3 & second row
elements are initialized to 4,5,6.

ASHOKA RAO
THUMUCHERLA

C-language

The initialization can be done row wise also, for the above example it is
int array[2][3] = {{1,2,3},{4,5,6}};

If the initialization has some missing values then they are automatically initialized to
0.
int array[2][3] = {{3,4},{5}}
3
5

4
0

0
0

In this case the first two elements of the first row are initialized to 3,4 ,while the
first element of the second row is initialized to 5 & rest all elements are initialized to
0.
char ttt[3][3] = {
{'x', 'x', 'o'},
{'o', 'o', 'x'},
{'x', 'o', ' '}
};

The memory for this array could be visualized like below,

But memory is addressed linearly; a better representation is,

Reading elements into two-dimensional array:


#include<stdio.h>
int main(){
int a[10][10],m,n,i,j;
printf("enter the dimenstion of the array :");

ASHOKA RAO
THUMUCHERLA

C-language
scanf("%d%d",&m,&n);
printf("enter %d elements into %d*%d dimension array :",m*n,m,n);
for (i = 0; i < m; i++){
for ( j = 0; j < n; j++){
scanf("%d",&a[i][j]);
}}
printf("the elements are :\n");
for (i = 0; i < m; i++){
for ( j = 0; j < n; j++){
printf("%d\t",a[i][j]);
}
printf("\n");
}
return 0;
}

/* Program to illustrate addition,substraction,and multiplication of matrix */


#include<stdio.h>
#include<conio.h>
void read_mat(int,int,int a[][]);
void print_mat(int,int,int a[][]);
void add_mat(int,int,int a[][],int b[][],int s[][]);
void sub_mat(int,int,int a[][],int b[][],int sd[][]);
void mul_mat(int,int,int,int a[][],int b[][],int mt[][]);

void read_mat(int m,int n,int a[5][5])


{
int i,j;
for(i=0;i<m;i++)
{
for(j=0;j<n;j++)
{
printf("\n Enter element :");
scanf("%d",&a[i][j]);
}
}
}
void print_mat(int m,int n,int a[5][5])
{
int i,j;

ASHOKA RAO
THUMUCHERLA

C-language
for(i=0;i<m;i++)
{
for(j=0;j<n;j++)
{
printf(" %d\t",a[i][j]);
}
printf("\n");
}
}
void add_mat(int m,int n,int a[5][5],int b[5][5],int s[5][5])
{
int i,j;
for(i=0;i<m;i++)
{
for(j=0;j<n;j++)
{
s[i][j]=a[i][j]+b[i][j];
}
}
}
void sub_mat(int m,int n,int a[5][5],int b[5][5],int sd[5][5])
{
int i,j;
for(i=0;i<m;i++)
{
for(j=0;j<n;j++)
{
sd[i][j]=a[i][j]-b[i][j];
}
}
}
void mul_mat(int m,int n,int p,int a[5][5],int b[5][5],int mt[5][5])
{
int i,j,k;
for(i=0;i<m;i++)
{
for(j=0;j<p;j++)
{
mt[i][j]=0;
for(k=0;k<n;k++)
{
mt[i][j]=mt[i][j]+a[i][k]*b[k][j];
}
}
}
}

ASHOKA RAO
THUMUCHERLA

C-language

void main()
{
int m,n,p,q,i,j,a[5][5],b[5][5],s[5][5],sd[5][5],mt[5][5];
printf("\n Enter order of first matrix :");
scanf("%d%d",&m,&n);
printf("\n Order of second matrix :");
scanf("%d%d",&p,&q);
if((m!=p)&&(n!=q))
printf("\n Matrices are imcompatable for addition and substraction");
else
{
printf("\n Read the element of first matrix ");
read_mat(m,n,a);
printf("\n Read the element of second matrix ");
read_mat(p,q,b);
printf("\n FIRST MATRIX IS ......\n");
print_mat(m,n,a);
printf("\n SECOND MATRIX IS ....\n");
print_mat(p,q,b);
add_mat(m,n,a,b,s);
printf("\n AFTER ADDITION MATRIX IS ....\n");
print_mat(m,n,s);
sub_mat(m,n,a,b,sd);
printf("\n AFTER SUBSTRACTION MATRIX IS ....\n");
print_mat(m,n,sd);
}
if(n==p)
{
mul_mat(m,n,p,a,b,mt);
printf("\n AFTER MULTIPLICATION MATRIX IS ....\n");
print_mat(m,p,mt);
}
else
printf("\n Matrices are incompatible for multiplication ");
getch();
}

Multi dimensional arrays: The elements of an array can be of any data type,
including arrays! An array of arrays is called a multidimensional array.
Three dimensional array:
The declaration form of Three-dimensional array is
Data_type
Array_name [size1][size2][size3];
For example,
Int [2][3][5];

ASHOKA RAO
THUMUCHERLA

C-language

In the above three dimensional matrix we can store 2*3*5 elements in the corresponding
locations.
Array 3D

Int*

Int**

Int

4 5

Base address (int ***)

Int*

Int

10

11 12 13 14 15

Int

16 17 18 19 20

Int

21

22 23 24 25

A three-dimensional array can be thought of as an array of arrays of arrays.


The outer array has three elements, each of which is a two-dimensional array of
four one-dimensional arrays, of two elements is constructed first.
Then four such one-dimensional arrays are placed one below the other to give a
two-dimensional array containing four rows.
Then, three such two-dimensional arrays are placed one behind the other to yield a
three-dimensional array.

Again remember that the arrangement shown above is only conceptually true. In memory
the same array elements are stored linearly as shown in below Figure

ASHOKA RAO
THUMUCHERLA

26 27 2

C-language

Note: When a function receives a single-subscripted array as an argument, the array

brackets are empty in the function's parameter list. The first subscript of a multiplesubscripted array is not required either, but all subsequent subscripts are required. The
compiler uses these subscripts to determine the locations in memory of elements in
multiple-subscripted arrays.
To pass one row of a double-subscripted array to a function that receives a singlesubscripted array, simply pass the name of the array followed by the subscript (in square
brackets) of that row.
#include <stdio.h>
void printSize (int x[][3][3])
{
printf("size of x: %d\n", sizeof(x));
return;
}
int main()
{
int i,j,k;
int p[6][3][3];
for(i=0;i<6;i++)
for(j=0;j<3;j++)
for(k=0;k<3;k++)
p[i][j][k] = i;
printf("size of p: %d\n", sizeof(p));
printSize(p);
return 0;
}

Interview codes:
Code1:
#include<stdio.h>
int main()
{
int a[5] = {5, 1, 15, 20, 25};

ASHOKA RAO
THUMUCHERLA

C-language
int i, j, m;
i = ++a[1];
j = a[1]++;
m = a[i++];
printf("%d, %d, %d", i, j, m);
return 0;
}
Code2:
#include<stdio.h>
int main()
{
int arr[5], i=0;
while(i<5)
arr[i]=++i;
for(i=0; i<5; i++)
printf("%d, ", arr[i]);
return 0;
}
Code3:
#include<stdio.h>
int main()
{
float arr[] = {12.4, 2.3, 4.5, 6.7};
printf("%d\n", sizeof(arr)/sizeof(arr[0]));
return 0;
}
Code4:
#include<stdio.h>
#define var 3
void main(){
short num[3][2]={3,6,9,12,15,18};
printf("%d %d",*(num+1)[1],**(num+2));
}
Code5:
#include<stdio.h>
void main(){
int arr[][3]={{1,2},{3,4,5},{5}};
printf("%d %d %d",sizeof(arr),arr[0][2],arr[1][2]);
}
Code6:

ASHOKA RAO
THUMUCHERLA

C-language
#include<stdio.h>
void main(){
int xxx[10]={5};
printf("%d %d",xxx[1],xxx[9]);
}
Code7:
#include<stdio.h>
void main(){
int a;
char b;
int arr[sizeof(!a+b)];
printf("%d",sizeof(arr));
}

Objectives:

STRINGS

After reading this chapter you will be familiarized with

What are strings?


What is the format specification of strings?
What are the standard string library functions?
How to manipulate string without using library functions?
Two-dimensional array of characters?

Overview:

An array of type char can be used to store a character string.


A character array can be initialized using a string literal.
All strings in C end with the null character. The character constant representing the
null character is '\0'.
Character arrays can be initialized with character constants in an initialize list.
Individual characters in a string stored in an array can be accessed directly using
array subscript notation.
A string can be input directly into a character array from the keyboard using scanf
and the conversion specifier %s.
A character array representing a string can be output with printf and the %s
conversion specifier.

ASHOKA RAO
THUMUCHERLA

C-language

Apply static to a local array definition so the array is not created each time the
function is called and the array is not destroyed each time the function exits.
Arrays that are static are automatically initialized once at compile time. If the
programmer does not explicitly initialize a static array, it is initialized to zero by the
compiler.
To pass an array to a function, the name of the array is passed. To pass a single
element of an array to a function, simply pass the name of the array followed by the
subscript (contained in square brackets) of the particular element.
C passes arrays to functions by referencethe called functions can modify the
element values in the callers' original arrays. The name of the array is actually the
address of the first element of the array. Because the starting address of the array is
passed, the called function knows precisely where the array is stored.
To receive an array argument, the function's parameter list must specify that an
array will be received. The size of the array is not required (for single-subscripted
arrays) in the array brackets.
C provides the special type qualifier const to prevent modification of array values in
a function. When an array parameter is preceded by the const qualifier, the
elements of the array become constant in the function body and any attempt to
modify an element of the array in the function body results in a compile time error.

String:

A string is a one dimensional array of characters terminated by a null character (\0).


Each character in an array occupies one byte memory and the last character is
always \0 called null character.
\0 and 0 are not same, ASCII values of \0 is 0 where as ASCII value of 0 is 48.
It also shows that the elements of the character array are stored in contiguous
memory locations

Declaration:
The string can be declared as follow:
Syntax:
char string_nm[size];
Example:
char name[50];
String Structure:
When compiler assigns string to character array then it automatically supplies null
character ('\0') at the end of string. Thus, size of string = original length of string +
1.
char name[7];
name = "TECHNO";

ASHOKA RAO
THUMUCHERLA

C-language

Read Strings:
To read a string, we can use scanf() function with format specifier %s.
char name[50];
scanf("%s",name);
NOTE: When we use %s with scanf (), we do not use the ampersand symbol. This is
because the base address of the string is same as the address of the first character
in the string.
Write Strings:
To write a string, we can use printf() function with format specifier %s.
char name[50];
scanf("%s",name);
printf("%s",name);
Note: The function scanf() is not capable of receiving multi-word strings. To receive
the multi-word strings we use the functions gets(). The usage of functions gets() and
its counterpart puts() is shown below.
Char name[50];
Puts(enter your name);
Gets(name);
Puts(the given name is :);
Puts(name);
Note: The functions puts() can display only one string at a time (so, we used two
puts() in the above program). Also, on displaying a string, unlike printf(), puts()
places the cursor on the next line. The functions gets() can receive single multi-word
string.
STRING.H:
'string.h' is a header file which includes the declarations, functions, constants of string
handling utilities. These string functions are widely used today by many programmers to
deal with string operations.
Some of the standard member functions of string.h header files are,
Name

Prototype

Strlen

int strlen(char *s);

Description
Function returns the length of the string s (the
terminating null character does not count
against strings length).

ASHOKA RAO
THUMUCHERLA

C-language

Strcpy

char *strcpy(char *t
o, char *from);

Strcat

char *strcat(char *to


, char *from);

Function copies the string from into the


string to. If copying is successful, the function
returns to.
Function appends a copy of the string from to
the string to, overwriting the null character at
the end of to. Then, a terminating null character
is added to the result.
Function locates the first occurrence of
character chr in the string ptr. The function
returns a pointer to the first occurrence of
character chr, or a null pointer if chr does not
occur in ptr.
Function compares strings s1 and s2 and
returns zero if the strings are equal, or returns a
difference between the first differing characters
(in a left-to-right evaluation).

strchr

char *strchr(char *pt


r, char chr);

strcmp

int strcmp(char *s1,


char *s2);

strncat

char *strncat(char *t
o,
char *from, int size);

strncmp

int strncmp(char *s1


,
char *s2, char len);

Function appends not more than size characters


from the string from to to. The initial character
of from overwrites the null character at the end
of to. The terminating null character is always
appended to the result.
Function lexicographically compares not more
than len characters (characters that follow the
null character are not compared) from the string
pointed by s1 to the string pointed by s2.

memchr

void *memchr(void *
p, char n, unsigned
int v);

Function locates the first occurrence of char n in


the initial v bytes of memory area starting at
the address p. The function returns the pointer
to this location or 0 if the n was not found.

memcmp

int memcmp(void *s
1, void *s2, int n);

Function compares the first n characters of


objects pointed to by s1 and s2 and returns
zero else 1.

memcpy

void *memcpy(void
*d1, void *s1, int n);

memmov
e

void *memmove(voi
d *to, void *from, int
n);

Strupr

char * strupr(char
*str);

Function copies n characters from the object


pointed to by s1 into the object pointed to
by d1. If copying takes place between objects
that overlap, the behavior is undefined. The
function returns address of the object pointed to
by d1.
Function copies n characters from the object
pointed to by from into the object pointed to
by to. Unlike memcpy, the memory
areas to and from mayoverlap. The function
returns address of the object pointed to by to.
strupr(str) coverts str to all uppercase. It
returns a pointer to the original input string str.

ASHOKA RAO
THUMUCHERLA

C-language

strlwr

char * strlwr(char
*str);

strlwr(str) coverts str to all lowercase. It returns


a pointer to the original input string str.

String length: To find string length we use strlen() function of string.h. This program
prints length of string; for example considers the string "c programming" its length is 13.
Null character is not counted when calculating string length.
C program to find string length
#include <stdio.h>
#include <string.h>
int main()
{
char str[50];
int len;
printf("\n Enter one string : ");
gets(str);
len=strlen(str);
printf("the length of %s is : %d",str,len);
return 0;
}
Copy a string:
The function copies the contents of one string into another.
The base addresses of the source and target string should be supplied to this
functions.
It is our responsibility to see to it that the target strings dimension is big enough to
hold the string being copied into it.
Thus, a string gets copied into another, character by character.
As illustrated in the following example, the first argument to the strcpy() function is
the target string and the second argument is the source string.
#include <stdio.h>
#include <string.h>
int main()
{
char s1[50],s2[50];
printf("\n Enter one string : ");
gets(s1);
strcpy(s2,s1);
printf("the copied string is :%s",s2);
return 0;
}
#include <stdio.h>
#include <string.h>
int main()

ASHOKA RAO
THUMUCHERLA

C-language
{
char s1[50],s2[50],*s3;
printf("\n Enter one string : ");
gets(s1);
s3=strcpy(s2,s1);
printf("the copied string using pointer :%s",s3);
return 0;
}
String reverse : This program reverses a string entered by the user. For example if a
user enters a string "reverse me" then on reversing the string will be "em esrever". To
reverse string the first one uses strrev library function of string.h header file
#include <stdio.h>
#include <string.h>
int main()
{
char s1[50];
printf("\n Enter one string : ");
gets(s1);
printf("the reverse string for %s is :",s1);
puts(strrev(s1));
return 0;
}
Program that describe all possible operations on string:
#include <stdio.h>
#include <conio.h>
#include <string.h>
int main()
{
char str[50],str1[50];
printf("\n Enter your name : ");
gets(str);
printf("\n\n\nLower case of string: %s",strlwr(str));
printf("\nUpper case of string: %s",strupr(str));
printf("\nReverse of string: %s",strrev(str));
printf("\nLength of String: %d",strlen(str));
printf("\nthe copied string is :%s",strcpy(str1,str));
printf("\ncomparison of two strings (str,str1) :%d",strcmp(str,str1));
printf("\nduplicate string of str2 :%s",strdup(str1));
printf("\nstring(str) after filling with '? ' is : %s\n\n",strset(str,'?'));
return 0;
}

ASHOKA RAO
THUMUCHERLA

C-language
Memchr: The memchr() function returns a pointer to the first occurrence of c in the first n
bytes of a memory area. The function returns the pointer to this location or 0 if the n was
not found.
void *memchr(void *p, char n, unsigned int v);
#include<stdio.h>
#include<string.h>
int main()
{
char str[20]="naresh technologies";
int *res;
res=memchr(str,'l',10);
printf("%d",res);
return 0;
}
Memcmp: The function memcmp() compares the first count characters of buffer1 and
buffer2.
The return values are as follows:
Value
Explanation
Less than 0
buffer1 is less than buffer2
Equal to 0
buffer1 is equal to buffer2
Greater than 0
buffer1 is greater than buffer2
#include<stdio.h>
#include<string.h>
int main()
{
char s1[20]="naresh technologies";
char s2[20]="naresh tech";
int res;
res=memcmp(s1,s2,20);
printf("%d",res);
return 0;
}
Memcpy & memmove:

memcpy() copies bytes of data between memory blocks, sometimes called buffers.
This function doesn't care about the type of data being copied--it simply makes an
exact byte-for-byte copy. The function prototype is
void *memcpy(void *dest, void *src, size_t count);

memmove() is very much like memcpy(), copying a specified number of bytes from
one memory block to another. It's more flexible, however, because it can handle
overlapping memory blocks properly. Because memmove() can do everything

ASHOKA RAO
THUMUCHERLA

C-language
memcpy() can do with the added flexibility of dealing with overlapping blocks, you
rarely, if ever, should have a reason to use memcpy(). The prototype is
void *memmove(void *dest, void *src, size_t count);
#include<stdio.h>
#include<string.h>
int main()
{
char s1[20]="suresh technologies";
char s2[20]="naresh";
char s5[30]="suresh I tech";
char *s3,*s4;
s3=memcpy(s1,s2,6);
printf("%s\n",s3);
s4=memmove(s5,s1,6);
printf("%s\n",s4);
return 0;
}

Programs to perform string manipulating operations without using library


functions
String Length Without Using Strlen() Function In C
#include<stdio.h>
#include<conio.h>
void main()
{
char a[20];
int i=0;
clrscr();
printf("Enter the string:");
scanf("%s",a);
while(a[i]!='\0')
{
i++;
}
printf("string length is:%d",i);
getch();
}
Reverse String Without Using Library Function [ Strrev ]
#include<stdio.h>
#include<string.h>

ASHOKA RAO
THUMUCHERLA

C-language
void main()
{
char s[100],temp;
int i,j=0;
printf("n Enter the string :");
gets(s);
i=0;
j=strlen(s)-1;
while(i<j)
{
temp=s[i];
s[i]=s[j];
s[j]=temp;
i++;
j--;
}
printf("nReverse string is :%s",s);
getch();
}
//C program to compare two strings without using string functions
Strcmp() function compares two string character by character until there is a
mismatch occurs or end of the one of those strings reached whichever occurs first.
If the two strings are equal, it returns 0. If two strings are not equal, it returns the
numerical ASCII difference between the two mismatching characters.
#include<stdio.h>
int stringCompare(char[],char[]);
int main(){
char str1[100],str2[100];
int compare;
printf("Enter first string: ");
gets(str1);
printf("Enter second string: ");
gets(str2);
compare = stringCompare(str1,str2);
if(compare == 1)
printf("Both strings are equal.\n");
else
{
printf("Both strings are not equal\n");
printf("the ascii difference between mismatching characters is :%d",compare);
}
return 0;
}
int stringCompare(char str1[],char str2[]){

ASHOKA RAO
THUMUCHERLA

C-language
int i=0,flag=0;
while(str1[i]!='\0' && str2[i]!='\0')
{
if(str1[i]!=str2[i])
{
flag=1;
break;
}
i++;
}
if (flag==0 && str1[i]=='\0' && str2[i]=='\0')
return 1;
else
return str1[i]-str2[i];
}
String copy without using strcpy in c programming language
#include<stdio.h>
void stringCopy(char[],char[]);
int main(){
char str1[100],str2[100];
printf("Enter any string: ");
scanf("%s",str1);
stringCopy(str1,str2);
printf("After copying: %s",str2);
return 0;
}
void stringCopy(char str2[],char str1[]){
int i=0;
while(str1[i]!='\0'){
str2[i] = str1[i];
i++;
}
str2[i]='\0';
}
String concatenation without using strcat():
This function concatenates the source string at the end of the target string.
#include<stdio.h>
void stringConcat(char str1[],char str2[]);
void main()
{
char str1[100],str2[100];

ASHOKA RAO
THUMUCHERLA

C-language
printf("enter str1:");
gets(str1);
printf("enter str2:");
gets(str2);
stringConcat(str1,str2);
}
void stringConcat(char str1[],char str2[])
{
int i=0,j=0;
char str[100];
while(str1[i]!='\0')
{
str[i]=str1[i];
i++;
}
while(str2[j]!='\0')
{
str[i+j]=str2[j];
j++;
}
str[i+j]='\0';
printf("\n the concatenated string is :%s\n",str);
}
C program to lowercase the string without using strlwr().
#include<stdio.h>
#include<conio.h>
void main()
{
char str[25];
int len,i=0;
clrscr();
printf("Enter the String: ");
gets(str);
while(str[i]!='\0')
{
if(str[i]<91&&str[i]>64)
str[i]=str[i]+32;
i++;
}
printf("\nYour String in Lowerercase %s",str);
}
Program to check whether the string is palindrome or not?
#include <stdio.h>
#include <string.h>

ASHOKA RAO
THUMUCHERLA

C-language
int main()
{
char str[20];
int i=0,j,flag=-1;
printf("enter one string :");
gets(str);
j=strlen(str)-1;
while(str[i]!='\0')
{
if(str[i]==str[j])
{
i++;
j--;
continue;
}
else
{
printf("string is not palindrome");
return;
}
}
printf("string is palindrome");
return 0;
}
Program to insert a substring into a string at specified position
#include<stdio.h>
int main()
{
char str[30],sub[10];
int pos,len1,len2,i;
printf("enter one string :");
gets(str);
printf("enter the sub string :");
gets(sub);
printf("enter the position to be inserted :");
scanf("%d",&pos);
len1=strlen(str);
len2=strlen(sub);
printf("the string is :%s\n",str);
printf("the sub string is :%s\n",sub);
for(i=len1-1;i>=pos;i--)
{
str[i+len2]=str[i];
}
i=0;

ASHOKA RAO
THUMUCHERLA

C-language
while(sub[i]!='\0')
{
str[pos+i]=sub[i];
i++;
}
str[len1+len2]='\0';
printf("\nafter insertion :%s",str);
return 0;
}

Two dimensional arrays of characters (2d strings):


A String is an array of char objects. An array of string can be declared and handled like a
2d (two dimensional) arrays.
#include <stdio.h>
#include <conio.h>
void main() {
clrscr();
char arr[3][12]= { "Rose", "India", "technologies" };
printf("Array of String is = %s,%s,%s\n", arr[0], arr[1], arr[2]);
getch();
}
Program for sorting of string in c language
#include<stdio.h>
int main(){
int i,j,n;
char str[20][20],temp[20];
puts("Enter the no. of string to be sorted");
scanf("%d",&n);
for(i=0;i<=n;i++)
gets(str[i]);
for(i=0;i<=n;i++)
for(j=i+1;j<=n;j++){
if(strcmp(str[i],str[j])>0){
strcpy(temp,str[i]);
strcpy(str[i],str[j]);
strcpy(str[j],temp);
}
}
printf("The sorted string\n");
for(i=0;i<=n;i++)
puts(str[i]);
return 0;
}
Interview codes:

ASHOKA RAO
THUMUCHERLA

C-language

Code 1:
#include<stdio.h>
void main(){
char arr[7]="Network";
printf("%s",arr);
}
Code2:
#include<stdio.h>
void main(){
char arr[11]="The African Queen";
printf("%s",arr);
}
Code3:
#include<stdio.h>
void main(){
char arr[20]="MysticRiver";
printf("%d",sizeof(arr));
}
Code4:
#include<stdio.h>
#define var 3
void main(){
char data[2][3][2]={0,1,2,3,4,5,6,7,8,9,10,11};
printf("%o",data[0][2][1]);
}
Code5:
#include<stdio.h>
#define var 3
void main(){
char *ptr="cquestionbank";
char ch='e';
printf("%d",ch);
printf("%d",-3[ptr]);
}
Code 6:
#include<stdio.h>
#include<string.h>
int main()
{
char str1[20] = "Hello", str2[20] = " World";
printf("%s\n", strcpy(str2, strcat(str1, str2)));

ASHOKA RAO
THUMUCHERLA

C-language
return 0;
}
Code7:
#include<stdio.h>
#include<string.h>
int main()
{
printf("%d\n", strlen("123456"));
return 0;
}
If the two strings are identical, then strcmp() function returns
A.
-1
B.
1
C.
0
D.
Yes
Which of the following function sets first n characters of a string to a given
character?
A.
strinit()
B.
strnset()
C.
strset()
D.
strcset()
How will you print \n on the screen?
A.
printf("\n"); B.
echo "\\n";
C.
printf('\n'); D.
printf("\\n");
Which of the following function is more appropriate for reading in a multi-word
string?
A.
printf();
B.
scanf();
C.
gets();
D.
puts();
Summary of Strings:

A string is nothing but an array of characters terminated by \0.


Being an array, all the characters of a string are stored in contiguous memory
locations.
Though scanf( ) can be used to receive multi-word strings, gets( ) can do the same
job in a cleaner way.
Both printf( ) and puts( ) can handle multi-word strings.
Strings can be operated upon using several standard library functions like strlen( ),
strcpy( ), strcat( ) and strcmp( ) which can manipulate strings. More importantly we
imitated some of these functions to learn how these standard library functions are
written.
Though in principle a 2-D array can be used to handle several strings, in practice an
array of pointers to strings is preferred since it takes less space and is efficient in
processing strings.

ASHOKA RAO
THUMUCHERLA

C-language

malloc( ) function can be used to allocate space in memory on the fly during
execution of the program.

Structures
OBJECTIVES
After going through this lesson you will be able to

Explain the basic concepts of structure


use compound data structures in programs
Process a structure
Memory management of structures
Passing structures as an argument to a function
Nested structures
Arrays in structures
Arrays of structures
Copying elements of structures

ASHOKA RAO
THUMUCHERLA

C-language

Explain the concept of unions


Difference between structure and union

Introduction:
We know that variables can hold a piece of information and arrays can hold a number of
pieces of information of same type/ these tow data types can handle a great variety of
situations. Often, we need to deal with entities that are collection of dissimilar data types.
For example, to store data about a book, we might want to store its name (a string), its
price (a float) and number of pages in it (an int). If data about three such books are to be
stored, then we can follow two approaches:
a) Construct individual arrays, ne for storing names, another for storing prices and still
another for storing number of pages.
b) Use a structure variable.

A better way of organizing the data is to create a new user-defined data type that
contains all the pieces of data organized into one structure
C provides a data structure called a struct that allows you to create new data types
Keyword 'struct' is used to declare structure.
The new data type is an organized aggregate of other data types
A struct has a name (e.g., structureName)

The variables which are declared inside the structure are called as 'members of
structure'.

A struct has members or fields, which can be any data types, such as char, int, float,
string, array, bit field, and other struct

Syntax:
struct structure_nm
{
<data-type> element 1;
<data-type> element 2;
--------------------<data-type> element n;
}struct_var;

ASHOKA RAO
THUMUCHERLA

C-language

Example :
struct emp_info
{
char emp_id[10];
char nm[100];
float sal;
};

Note:
1. Structure is always terminated with semicolon (;).
2. Structure name as emp_info can be later used to declare structure variables of its type
in a program.
Things to remember:
Declaration of Structure reserves no space.
It is nothing but the Template / Map / Shape of the structure.
Memory is created, very first time when the variable is created / Instance is created.
Syntax to create a variable for a structure:
struct structure_name <var1>, <var2>..

Ways of Declaring Structure Variable / Structure Instance:


Way 1 : Immediately after Structure Template
struct date
{
int date;
char month[20];
int year;
} today; // 'today' is name of Structure variable
Way 2 : Declare Variables using struct Keyword
struct date
{
int date;
char month[20];
int year;
};
struct date today;
/*-----------------------------------

ASHOKA RAO
THUMUCHERLA

C-language
date : Name of Structure
today : Structure Variable
---------------------------------- */
Accessing structure members: A structure contains many elements. Each elements of
a structure can be referred to / accessed by using the component selection operator
. (Dot).
Syntax:
structure_var.member;
#include <stdio.h>
#include <conio.h>
struct comp_info
{
char nm[100];
char addr[100];
}info;
void main()
{
clrscr();
printf("\n Enter Company Name : ");
gets(info.nm);
printf("\n Enter Address : ");
gets(info.addr);
printf("\n\n Company Name : %s",info.nm);
printf("\n\n Address : %s",info.addr);
getch();
}

Memory map of structure elements: The structure elements are always stored in the
contiguous locations.

ASHOKA RAO
THUMUCHERLA

C-language
Array in Structures: We can also include arrays as structure elements, but accessing
of such kind of elements is bit complex as shown below.

#include <stdio.h>
struct result{
int rno;
int mrks[5];
char name[20];
}res;
void main(){
int i,total;
total = 0;
printf("\nEnter Name and Roll Number : ");
scanf("%s%d",res.name,&res.rno);
printf("\nEnter Marks of 3 Subjects : ");
for(i=0;i<3;i++){
scanf("%d",&res.mrks[i]);
total = total + res.mrks[i];
}
printf("\nname=%s\nRoll Number : %d",res.name,res.rno);
printf("\nMarks are :");
for(i=0;i<3;i++){
printf(" \t%d",res.mrks[i]);
}
printf("\n\n\t Total is : %d",total);
}
Array of structures: To store more than one record of a structure under same name, we
can also creates an array variable to the corresponding structure. The storage of elements
in array of structures would be as follows.

#include < stdio.h >


#include < conio.h >
struct emp
{
int empno;
char name[10];
int sal;
}e1[5];
void main()
{

ASHOKA RAO
THUMUCHERLA

C-language
int i;
clrscr();
for(i=0;i < 5;i++)
{
printf("Enter the empno\n");
scanf("%d",&e1[i].empno);
printf("Enter the name\n");
flushall();
gets(e1[i].name);
printf("Enter the salary\n");
scanf("%d",&e1[i].sal);
}
printf("The record is\n");
for(i=0;i < 5;i++)
{
printf("\n %4d",e1[i].empno);
printf("%8s",e1[i].name);
printf(" %4d\n",e1[i].sal);
}
getch();
}

Copying of structure elements:


The values of a structure variable can be assigned to another structure variable of
the same type using the assignment operator. The elements of the structure can be copied
piece-meal or all at once. This is illustrated in the following example:
#include <stdio.h>
struct emp
{
int eno;
char ename[50];
float esal;
};
int main()
{
int i;
struct emp e1={1001,"naresh",50000};
struct emp e2,e3;
e2.eno=e1.eno;
strcpy(e2.ename,e1.ename);
e2.esal=e1.esal;
e3=e2;

ASHOKA RAO
THUMUCHERLA

C-language
printf("\n%d\t%s\t%f\n",e1.eno,e1.ename,e1.esal);
printf("\n%d\t%s\t%f\n",e2.eno,e2.ename,e2.esal);
printf("\n%d\t%s\t%f\n",e3.eno,e3.ename,e3.esal);
return 0;
}
Note: ability to copy the contents of all structure elements of one variable into the
corresponding elements of another structure variable is rather surprising, since C does
not allow assigning the contents of one array to another just by equating the two. As we
saw earlier, for copying arrays we have to copy the contents of the array element by
element.
Structures within Structures (Nested Structures):
Structures can be used as structures within structures. It is also called as 'nesting of
structures'. Using this facility complex data types can be created.

Syntax:
struct structure_nm
{
<data-type> element 1;
<data-type> element 2;
--------------------<data-type> element n;
struct structure_nm
{
<data-type> element 1;
<data-type> element 2;
--------------------<data-type> element n;
}inner_struct_var;
}outer_struct_var;

#include <stdio.h>
#include <conio.h>
struct stud_Res
{
int rno;
char std[10];
struct stud_Marks
{

ASHOKA RAO
THUMUCHERLA

C-language
char subj_nm[30];
int subj_mark;
}marks;
}result;
int main()
{
printf("\nEnter Roll Number : ");
scanf("%d",&result.rno);
printf("\nEnter Standard : ");
scanf("%s",result.std);
printf("\nEnter Subject Code : ");
scanf("%s",result.marks.subj_nm);
printf("\nEnter Marks : ");
scanf("%d",&result.marks.subj_mark);
printf("\n\nRoll Number : %d",result.rno);
printf("\nStandard : %s",result.std);
printf("\nSubject Code : %s",result.marks.subj_nm);
printf("\nMarks : %d",result.marks.subj_mark);
return 0;
}
Note: to access the elements of a structure that is a part of another structure, we can
use dot operator twice. The nesting process need not stop at this level. We can nest a
structure, within another, which is in still another and so on.
For example
Maruti.engine.bolt.large.qty
This clearly signifies that we are referring to the quantity of large sized bolts which fit on
an engine of a maruti car.
Structures as function arguments: (Call by value)
Like an ordinary variable, a structure variable can also be passed to a function. We
may either pass individual structure elements or the entire structure at one goes. Passing
of individual structure elements is done by using pointers, which we will discuss in the
coming chapters.
#include<stdio.h>
struct student
{
int sno;
char sname[20];
int smarks[3];
};
void show(struct student);
void main()
{

ASHOKA RAO
THUMUCHERLA

C-language
struct student s1;
int i;
printf("size of student is :%d\n",sizeof(s1));
printf("enter student no and name :\n");
scanf("%d%s",&s1.sno,s1.sname);
printf("enter student marks :\n");
for(i=0;i<3;i++)
{
scanf("%d",&s1.smarks[i]);
}
show(s1);
}
void show(struct student s)
{
int i;
printf("the student details are :\n");
printf("%d\n%s\n",s.sno,s.sname);
for(i=0;i<3;i++)
{
printf("%d\n",s.smarks[i]);
}
}
A Function that return a structure
#include <stdio.h>
#include <string.h>
struct student{
char name[20];
int id;
};
struct student read(void);
int main(void){
struct student student1;
student1 = read();
printf("Name: %s", student1.name);
printf("\nID: %d\n", student1.id);
return 0;
}
struct student read(void)
{
struct student s1;
printf("Enter name:");
scanf("%s",s1.name);
printf("Enter ID:");
scanf("%d",&s1.id);

ASHOKA RAO
THUMUCHERLA

C-language
return s1;
}

ASHOKA RAO
THUMUCHERLA

C-language

Unions
Unions were used back in the days when computer memory was at a premium. A
union basically allows a variable to have more than one type; but only one of these types
can be used.
However the members that we compose a union all share the same storage area
within the computers memory where as each member within a structure is assigned its
own unique storage area. Thus unions are used to conserve memory. They are useful for
the application involving multiple members where values need not be assigned to all the
members at any one time. Unions like structure contain members whose individual data
types may differ from one another also. Like structures union can be declared using the
keyword union as follows:
Syntax:
union [tag] { member-list } [declarators];
Tag: The type name given to the union.
Member-list: List of the types of data the union can contain. See Remarks.
Declarators: Declarator list specifying the names of the union.
Struct emp
{
Int eno;
Char ename[20];
Float esal;
} e;
The size of a union is equal to the size of its largest data member. In other words, the C
compiler allocates just enough space for the largest member. This is because only one
member can be used at a time, so the size of the largest, is the most you will need.
Here is an example:
union tag
{
char name[26];
int age;
float height;
} player;
player.name='Bhavani Shankar Kandregula';
player.age=27;
player.weight=61;
NOTE: Here 26 are the highest of all other data type variable members can occupy so
26 bytes are allocated for the whole union player. So union object can store any value
occupying up to 26 bytes and of any data type can be overlaid in the same allocated

ASHOKA RAO
THUMUCHERLA

C-language

Difference between structure and union

STRUCTURE

UNION

The keyword struct is used to define a


structure.

The keyword union is used to define a


union.

The size of the structure is equal to the sum


of the sizes of its members.

The size of the union is equal to the size of


the largest member.

Each member within a structure is assigned


a unique storage area.

Memory allocated is shared by individual


members of the union.

Individual members can be accessed at a


time.

Only one member can be accessed at a


time.

Altering the value of a member will not


affect other members of the structure.

Altering the value of any of the member will


alter other member values.

Program to find the structure using sizeof () operator:


union myunion
{
int i;
double d;
char c;
}mu;
int main()
{
printf("%d\n",sizeof(union myunion));
printf("%d\n",sizeof(mu));
printf("%d\n",sizeof(mu.i));
printf("%d\n",sizeof(mu.d));
printf("%d\n",sizeof(mu.c));
return 0;
}
Memory allocation for union elements:

Union is user defined data type used to stored data under unique variable name at
single memory location.
Union is similar to that of structure..
But the major difference between structure and union is 'storage.' In structures,
each member has its own storage location, whereas all the members of union use
the same location.

ASHOKA RAO
THUMUCHERLA

C-language

Union contains many members of different types; it can handle only one member at
a time.

#include<stdio.h>
int main()
{
union a
{
int i;
char ch[2];
};
union a u;
u.ch[0]=3;
u.ch[1]=2;
printf("%d, %d, %d\n", u.ch[0], u.ch[1], u.i);
return 0;
}
Explanation: The system will allocate 2 bytes for the union. The statements u.ch[0]=3;
u.ch[1]=2; store data in memory as given below.

#include<stdio.h>
int main()
{
union var
{
int a, b;
};
union var v;
v.a=10;

ASHOKA RAO
THUMUCHERLA

C-language
v.b=20;
printf("%d\n", v.a);
return 0;
}

Pointers
Objectives:

What is a Pointer?
What is the size of a pointer ? why ?
What is Pointer arithmetic?
Pointer casting
Use of pointers in Call by Reference
difference between array_name and &array_name?
Pointers to Functions
Pointers to Arrays
Arrays of Pointers
Pointers to strings
Pointers to structures
Pointers to array of structures.
Multidimensional arrays and pointers
Static Initialisation of Pointer Arrays
complex pointers in C Programming?

Introduction:
Pointers are used everywhere in C, and if you have a good understanding of them C should
not pose a problem. Pointers are an extremely powerful programming tool. They can make
some things much easier, help improve your program's efficiency, and even allow you to
handle unlimited amounts of data.
C uses pointers in three main ways. First, they are used to create dynamic data structures:
data structures built up from blocks of memory allocated from the heap at run-time. This is
the only visible way that Pascal uses pointers. Second, C uses pointers to handle variable
parameters passed to functions. And third, pointers in C provide an alternative means of
accessing information stored in arrays, which is especially valuable when you work with
strings. There is an intimate link between arrays and pointers in C.
Pointer is a derived data type which creates special types of variables which can hold the
address of primitive data type like char, int, float, double or user defined data type like
structure, union, enum or derived data type like array, function, pointer etc.
An integer pointer points to integer data, functional pointer points to a particular function
depends upon its prototype and so on...
All the operations performed on the pointers done through two unary operators

ASHOKA RAO
THUMUCHERLA

C-language

1) Address operator (&) returns the address of a particular variable.


2) Pointer operator (*) returns the data stored in a particular address.

To declare a pointer you have to put an * in front of its name.


Syntax:
data_type *pointer_name;
e.g.
long *ptr;
int (*ptr)();
int (*ptr)[2];
In c programming every variable keeps two type of value.
Contain of variable or value of variable.
Address of variable where it has stored in the memory.
Simple pointer declaration and definition:
int a=5;
int * ptr;
ptr=&a;
Explanation:
About variable a:
Name of variable : a
Value of variable which it keeps: 5
Address where it has stored in memory : 1025 (assume)
About variable ptr:
4. Name of variable : ptr
5. Value of variable which it keeps: 1025
6. Address where it has stored in memory : 5000 (assume)
Pictorial representation:

Note: A variable where it will be stored in memory is decided by operating


system. We cannot guess at which location a particular variable will be stored in
ASHOKA RAO
memory.

THUMUCHERLA

C-language

Pointer is of two types:


1) Typed pointer: Typed pointer always points a particular data such as int, char,
float.
2) Untyped pointer: Untyped pointer is nothing but void pointer which can points to
any king of data but initially points to unknown.
#include<stdio.h>
int main()
{
int *ptr_A;
/* A typed pointer */
void *ptr_B; /* A untyped pointer */
return 0;
}
The following example describes that in how many ways we can access a variable using
pointers without disturbing the corresponding variable.
#include<stdio.h>
int main()
{
int i=100,*ptr;
ptr=&i;
printf(%u\n%u\n%u\n%u\n%u\n%u, i , *ptr, *(&ptr), ptr, &i, &ptr);
}
What is the size of Pointer variable in C?
All data is stored in memory. But different data types occupy different amount of memory.
The sizeof() operator in C can be used to determine the number of bytes occupied by each
data type.
For example, on some machine you may have
sizeof(int) = 2
sizeof(float) = 4
sizeof(double) = 8
These numbers are Not the same for all machines. You should use the sizeof() operator
instead of assuming the value.

Size of Pointer can be evaluated by using sizeof operator

Pointer stores the address of the Variable.

ASHOKA RAO
THUMUCHERLA

C-language

Address of variable is nothing but the integer value.

In C, for storing integer value 2 bytes are required.

So Pointer variable requires 2 bytes of memory.

#include <stdio.h>
int main()
{
int a[10];
int *a1;
printf("%d\n", sizeof(a));
printf("%d\n", sizeof(a1));
getchar();
return 0;
}
/* my output
20
2
*/
#include<stdio.h>
int main()
{
int *ip;
double *dp;
float *fp;
char *cp;
printf("%d\n",sizeof(ip));
printf("%d\n",sizeof(cp));
printf("%d\n",sizeof(fp));
printf("%d\n",sizeof(dp));
return 0;
}
CALL BY VALUE & CALL BY REFERENCE:
1) Call by Value:-

While calling a Function, if we pass values as arguments to the called function


known as call by value.
So that the Arguments those are passed to that function just contains the values
from the variables but not an Actual Address of the variable.
So that generally when we call a Function then we will just pass the variables or the
Arguments and we doesnt Pass the Address of Variables ,

ASHOKA RAO
THUMUCHERLA

C-language

So that whatever happened in the called function which never effects on the Values
or on the variables. In the calling function

#include <stdio.h>
void main()
{
int x, y, temp;
clrscr();
printf("Enter the value of x and y\n");
scanf("%d%d", &x, &y);
printf("Before Swapping\nx = %d\ny = %d\n",x,y);
swap(x,y);
getch();
}
Void swap(int a,int b)
{
Int temp;
temp = a;
a = b;
b = temp;
printf("After Swapping\nx = %d\ny = %d\n",a,b);
}
2) Use of pointers in Call By Reference :

While calling a function if we pass address of actual parameters as arguments to the


formal parameters in the calling function known as call by reference.
In call by reference mechanism, if any changes happened on the formal parameters
in the called function directly affects on the actual parameters in the calling
function.

#include<stdio.h>
#include<conio.h>
void swaping(int *x, int *y);
int main()
{
int n1,n2;
printf("Enter first number (n1) : ");
scanf("%d",&n1);
printf("Enter second number (n2) : ");
scanf("%d",&n2);
printf("\nBefore swapping values:");
printf("\n\tn1=%d \n\tn2=%d",n1,n2);
swaping(&n1,&n2);
printf("\nAfter swapping values:");
printf("\n\tn1=%d \n\tn2=%d",n1,n2);
getch();
return 0;
}

ASHOKA RAO
THUMUCHERLA

C-language
void swaping(int *x, int *y)
{
int z;
z=*x;
*x=*y;
*y=z;
printf("\nAfter swapping values:");
printf("\n\tn1=%d \n\tn2=%d",*x,*y);
}

Pointer Arithmetic:

When an ordinary variable increments, the value of a variable increases by 1 only.


But when a pointer is incremented, it points to the immediately next location of the
pointer of its type. i.e., when an integer pointer incremented, it points to an address
2 locations after the current location, since an int always two bytes long.
Pointers do not have to point to single variables.
They can also point at the cells of an array. For example, we can write
int *ip;
int a[10];
ip = &a[3];

now ip pointing to fourth cell in the array, *ip gives us what ip points to, which in this case
will be the value in a[3].

Once we have a pointer pointing into an array, we can start doing pointer arithmetic.
Given that ip is a pointer to a[3], we can add 1 to ip:
ip + 1
In C, it gives a pointer to the cell one farther on, which in this case is a[4]. To make this
clear, let's assign this new pointer to another pointer variable:
ip2 = ip + 1;
Now the picture looks like this:

If we now do
*ip2 = 4;
we've set a[4] to 4. But it's not necessary to assign a new pointer value to a pointer
variable in order to use it; we could also compute a new pointer value and use it
immediately:
*(ip + 1) = 5;

ASHOKA RAO
THUMUCHERLA

C-language
In this last example, we've changed a[4] again, setting it to 5. The parentheses are
needed because the unary ``contents of'' operator * has higher precedence (i.e., binds
more tightly than) the addition operator. If we wrote *ip + 1, without the parentheses,
we'd be fetching the value pointed to by ip, and adding 1 to that value.
#include <stdio.h>
int main()
{
int i,*ip;
char ch, *cp;
ip=&i;
cp=&ch;
printf("values of ip and cp :\t%u\t%u\n",ip,cp);
ip++; //increments by sizeof(int) (4 bytes)
cp++; //increments by sizeof(char) (1 bytes)
printf("values of ip and cp :\t%u\t%u\n",ip,cp);
ip=ip+10;//increses 40 bytes
cp=cp+10;//increses 10 bytes
printf("values of ip and cp :\t%u\t%u\n",ip,cp);
return 0;
}

Pointers to Arrays:

Combining pointers with arrays can be very helpful in certain situations.


A pointer to array is declared as :
<data type> (*<name of ptr>)[<an integer>]
For example :
int(*ptr)[5];

#define MAX 10
void main()
{
int a[MAX];
int i;
int *p;
p=a;
for(i=0; i<MAX; i++)
a[i]=i;
printf("%d\n",*p);
}

The statement p=a; works because a is a pointer.


Technically a point to the address of the 0th element of the actual array.
This element is an integer, so a is a pointer to a single integer.
Therefore, declaring p as a pointer to an integer and setting it equal to a works.

ASHOKA RAO
THUMUCHERLA

C-language

Another way to say exactly the same thing would be to replace p=a; with
p=&a[0];. Since a contains the address of a[0], a and &a[0] mean the same thing.

#include<stdio.h>
void main()
{
int a[5]={10,20,30,40,50};
int i;
int *p;
p=a;
for(i=0; i<5; i++)
{
printf("%d\t",a[i]);
printf("%d\t",p[i]);
printf("%d\t",*(p+i));
printf("%d\t",*(i+p));
printf("%d\n",i[p]);
}
}
You can copy the array a into b using pointers as well. The following code can
replace
(for i=0; i<MAX; a[i]=b[i], i++)
{
p=a;
q=b;
for (i=0; i<MAX; i++)
{
*q = *p;
q++;
p++;
}}
You can abbreviate this code as follows:
p=a;
q=b;
for (i=0; i<MAX; i++)
*q++ = *p++;
And you can further abbreviate it to:
for (p=a,q=b,i=0; i<MAX; *q++ = *p++, i++);
program that prints values and elements stored loactions
#include <stdio.h>
main(){

ASHOKA RAO
THUMUCHERLA

C-language
int a[5];
int i;
int *b;
for(i = 0;i<5;i++){
a[i]=i;
}
b=a;
for(i = 0;i<5;i++){
printf("value in array %d and address is %16lu\n",*b,b);
b=b+1;
}

Note: A pointer that holds an address of the string by which we can prints the total
string without pointing to the next character by incrementing the pointer variable.
#include <stdio.h>
int main(void)
{
char multiple[] = "a string";
char *p = multiple;
int i;
for(i = 0 ; i<strlen(multiple) ; i++)
{
printf("\n%c \n%c\n%c\n%c\n%c\n ",multiple[i],*(p+i),p[i],*(i+p),i[p]);
}
return 0;
}
What is the difference between array_name and &array_name?

One is a pointer to the first element in the array


The other is a pointer to the array as a whole.
An array is a type. It has a base type (what it's an array of ), a size (unless it's an
"incomplete" array), and a value (the value of the whole array).
You can get a pointer to this value:
char a[ MAX ];
/* array of MAX characters */
char *p;
/* pointer to one character */
pa is declared below
pa = & a;
p = a;
/* = & a[ 0 ] */
After running that code fragment, you might find that p and pa would be printed as
the same value; they both point to the same address.
They point to different types of MAX characters.
char *ap[ MAX ];

Array of pointers:
ASHOKA RAO
THUMUCHERLA

C-language
Pointers like any other data type can be arrayed. This array is called array of
pointers and is quite useful programming method.
Syntax:
data_type *variable_name [array_size];
Example:
int *array [5];
The C Source code below will show you a simple use of array of pointers in c programming.
#include <stdio.h>
int main ()
{
int data[5];
int *array[5];
for (int i = 0; i <5;i++){
data[i] = i;
}
//Assigning address of elements of array data to array of pointers.
for (int i = 0; i <5;i++){
array[i] = &data[i];
}
for (int i = 0; i <5;i++) //Accessing Array value using index
{
printf ("\n%d",data[i]);
}
for (int i = 0; i <5;i++) //Access Array value using array of pointers
{
printf ("\n%d",*array[i] );
}
return 0;
}

#include<stdio.h>
int main(void)
{
char *p1 = "Himanshu";
char *p2 = "Arora";
char *p3 = "India";
char *arr[3];
arr[0] = p1;
arr[1] = p2;
arr[2] = p3;
printf("\n p1 = [%s] \n",p1);

ASHOKA RAO
THUMUCHERLA

C-language
printf("\n
printf("\n
printf("\n
printf("\n
printf("\n
return 0;

p2 = [%s] \n",p2);
p3 = [%s] \n",p3);
arr[0] = [%s] \n",arr[0]);
arr[1] = [%s] \n",arr[1]);
arr[2] = [%s] \n",arr[2]);

}
Pointers vs. Multi-dimensional Arrays in C
Newcomers to C are sometimes confused about the difference between a twodimensional array and an array of pointers.
Given the definitions
int a[10][20];
int *b[10];
Then a[3][4] and b[3][4] are both syntactically legal references to a single int.
But a is a true two-dimensional array: 200 int-sized locations have been set aside,
and the conventional rectangular subscript calculation 20 * row +col is used to
find the element a[row,col].
For b, however, the definition only allocates 10 pointers and does not initialize
them; initialization must be done explicitly, either statically or with code.
Assuming that each element of b does point to a twenty-element array, then there
will be 200 ints set aside, plus ten cells for the pointers.
The important advantage of the pointer array is that the rows of the array may be of
different lengths.
That is, each element of b need not point to a twenty-element vector; some may
point to two elements, some to fifty, and some to none at all.
Although we have phrased this discussion in terms of integers, by far the most
frequent use of arrays of pointers is to store character strings of diverse lengths, as
in the function month_name.

Compare the declaration and picture for an array of pointers:


char *name[] = { "Illegal month", "Jan", "Feb", "Mar" };
with those for a two-dimensional array:
char aname[][15] = { "Illegal month", "Jan", "Feb", "Mar" };

#include <stdio.h>
int main(void)
{
char board[3][3] = {
{'1','2','3'},
{'4','5','6'},
{'7','8','9'}
};
printf("address of board
: %d\n", board);
printf("address of board[0][0] : %d\n", &board[0][0]);

ASHOKA RAO
THUMUCHERLA

C-language
printf("but what is in board[0] : %d\n", board[0]);
return 0;
}
Program to access the elements of two dimensional array using arrays
#include <stdio.h>
int main(void)
{
char board[3][3] = {
{'1','2','3'},
{'4','5','6'},
{'7','8','9'}
};
int i;
for(i = 0; i < 9; i++)
printf(" board: %c\n", *(*board + i));
return 0;
}

Pointer to a function:

One of the rarest used yet powerful features of C programming language is the
pointer to a function.
As most of the people dont know that every function defined in c programming
language have a base address attached to it.
This base address acts as an entering point into that function.
As you can now guess this address can be stored in a specially designed pointer
known as function pointer.
Address of the function can be obtained by using pointer name without parenthesis.

Syntax :
return_type (* pointer_name) ( variable1_type var1_name , var2_type
var3_name,....);

The declaration above tells compiler that pointer of name pointer_name will store a
address of function which return a value of return_type type. Also it will take
variables of name variable1_name, variable2_name of type variable1_type,
variable2_type respectively and so on.

Example:
int (*fptr) (int,int,int);
The above line declares that a functional pointer fptr points to a function whose
return type is int ant it takes three integers as arguments.
#include <stdio.h>
#include <conio.h>
int mul(int a, int b, int c)

ASHOKA RAO
THUMUCHERLA

C-language
{
return a*b*c;
}
void main()
{
int (*function_pointer)(int, int, int);
function_pointer = mul;
printf("The product of three numbers is:%d",
function_pointer(2, 3, 4));
getch();
}
#include <stdio.h>
void say_loud(char *a_message)
{
printf("\"%s!!!\" you shout.\n", a_message);
}
void say_soft(char *a_message)
{
printf("\"%s\" you whisper.\n", a_message);
}
void (*say)(char *a_message) = NULL;
int main(void)
{
say = say_loud;
say("WHAT");
say = say_soft;
say("I know a secret!");
return 0;
}
Pointer Conversion:(casting)

Pointer Conversion is a very powerful yet very dangerous feature.

Before concept of pointer conversion you must understand the concept of a void
pointer.

void pointer technically is a pointer which is pointing to the unknown.

void pointer has special property that it can be type casted into any other pointer
without any type casting though every other conversion needs an type casting.

In C++ even void pointer needs an type casting so to maintain the compatibility
you may want to type cast void pointer anyway. Also in dynamic memory allocation

ASHOKA RAO
THUMUCHERLA

C-language
function such as malloc ( ) and alloc ( ) returns void pointer which can be easily
converted to other types.

Also there is a pointer called null pointer which seems like void pointer but is
entirely different. Null pointer is a pointer which points to nothing. In fact it points to
the base address of you CPU register and since register is not addressable usage of
a null pointer will lead to crash or at minimum a segmentation fault. Be careful
while typecasting one pointer to another because even after type casting your
pointer can point to anything but it will still think it is pointing to something of it
declared type and have properties of the original type.

Type conversion is a powerful feature but yet it may lead difficult to remove bugs
and crashes and should be used with uttermost vigilance. It may also lead to
unexpected and unreliable results but program would compile successfully.

Code below shows a type casting of one pointer into another #include <stdio.h>
int main ()
{
int i = 10;
char* p1
int *p2;
p2 = &i;
p1 = (char *) p2; // Type Casting and Pointer Conversion
printf (" *p1 = %c And *p2 = %d", *p1,*p2);
return 0;
}

Pointer to Strings:

Another way of accessing a contiguous chunk of memory, instead of with an array,


is with a pointer.
Since we are talking about strings, which are made up of characters, we'll be using
pointers to characters, or rather, char*'s.
However, pointers only hold an address, they cannot hold all the characters in a
character array. This means that when we use a char * to keep track of a string, the
character array containing the string must already exist (having been either
statically- or dynamically-allocated).
Below is how you might use a character pointer to keep track of a string.
char label[] = "Single";
char label2[10] = "Married";
char *labelPtr;
labelPtr = label;
We would have something like the following in memory (e.g., supposing that the
array label started at memory address 2000, etc.):

ASHOKA RAO
THUMUCHERLA

C-language
label @2000
-----------------------------| S | i | n | g | l | e | \0 |
-----------------------------label2 @3000
-----------------------------------------| M | a | r | r | i | e | d | \0 | | |
-----------------------------------------labelPtr @4000
-------| 2000 |
-------Note: Since we assigned the pointer the address of an array of characters, the
pointer must be a character pointer--the types must match.

Also, to assign the address of an array to a pointer, we do not use the address-of (&)
operator since the name of an array (like label) behaves like the address of that
array in this context. That's also why you don't use an ampersand when you pass a
string variable to scanf(), e.g,
int id;
char name[30];
scanf("%d%s", &id, name);
Now, we can use labelPtr just like the array name label. So, we could access the
third character in the string with:
printf("Third char is: %c\n", labelPtr[2]);
It's important to remember that the only reason the pointer labelPtr allows us to
access the label array is because we made labelPtr point to it. Suppose, we do the
following:
labelPtr = label2;
Now, no longer does the pointer labelPtr refer to label, but now to label2 as
follows:
label2 @3000
-----------------------------------------| M | a | r | r | i | e | d | \0 | | |
------------------------------------------

labelPtr @4000
-------| 3000 |
-------So, now when we subscript using labelPtr, we are referring to characters in label2.
The following:
printf("Third char is: %c\n", labelPtr[2]);
prints out r, the third character in the label2 array.

ASHOKA RAO
THUMUCHERLA

C-language
#include <stdio.h>
#include <string.h>
int main() {
char *name="David Bolton";
printf("My name is %s\r\n",name) ;
return 0;
}
#include <stdio.h>
void concat( char *, char *, char * );
void concat( char *a, char *b, char *c)
{
while( *a )
{
*c = *a;
++a;
++c;
}
while( *b )
{
*c = *b;
++b;
++c;
}
*c = '\0';
}
void main()
{
static char string1[] = "Hello";
static char string2[] = " world!";
char string3[20];
concat( string1, string2, string3);
printf("%s\n", string3);
}
#include<stdio.h>
int main()
{
printf ("%c",*"abcde");
return 0;
}
#include<stdio.h>
int main()
{

ASHOKA RAO
THUMUCHERLA

C-language
char *names[] = { "Suresh", "Siva", "Sona", "Baiju", "Ritu"};
int i;
char *t;
t = names[3];
names[3] = names[4];
names[4] = t;
for(i=0; i<=4; i++)
printf("%s,", names[i]);
return 0;
}
Pointers to structures:
Pointers in C are general; we can have pointers to any type. It turns out that pointers to
structures are particularly useful.
We declare pointers to structures the same way we declare any other pointers: by
preceding the variable name with an asterisk in the declaration. We could declare two
pointers to struct complex with
struct complex *p1, *p2;
And, as before, we could set these pointers to point to actual variables of type complex:
p1 = &c2;
p2 = &c3;
Then,
*p1 = *p2
would copy the structure pointed to by p2 to the structure pointed to by p1 (i.e. c3 to c2),
and
p1 = p2
would set p1 to point wherever p2 points. (None of this is new, these are the obvious
analogs of how all pointer assignments work.) If we wanted to access the member of a
pointed-to structure, it would be a tiny bit messy--first we'd have to use * to get the
structure pointed to, then . to access the desired member. Furthermore, since . has higher
precedence than *, we'd have to use parentheses:
(*p1).real
(Without the parentheses, i.e. if we wrote simply *p1.real, we'd be taking the structure p1,
selecting its member named real, and accessing the value that p1.real points to, which
would be doubly nonfunctional, since the real member is in our ongoing example not a
pointer, and p1 is not a structure but rather a pointer to a structure, so the . operator
won't work on it.)
Since pointers to structures are common, and the parentheses in the example above are a
nuisance, there's another structure selection operator which works on pointers to
structures. If p is a pointer to a structure and m is a member of that structure, then
p->m
selects that member of the pointed-to structure. The expression p->m is therefore exactly
equivalent to

ASHOKA RAO
THUMUCHERLA

C-language
(*p).m
#include<stdio.h>
int main()
{
struct emp
{
int eno;
};
struct emp e={1001};
struct emp *eptr;
eptr=&e;
printf("%d",(*eptr).eno);
return 0;
}
#include <stdio.h>
#include <conio.h>
int main() {
struct st {
int id;
char *name;
char *address;
};
struct st employee, *stptr;
stptr = &employee;
stptr->id = 1;
stptr->name = "Angelina";
stptr->address ="Rohini,Delhi";
printf("Employee Information: id=%d\n%s\n%s\n", stptr->id, stptr->name,
stptr->address);
getch();
return 0;
}
Structure: Call by reference
#include <stdio.h>
#include <string.h>
struct student{
char name[20];
int id;
};
void Read (struct student *); /* function prototype*/
void main(void)
{

ASHOKA RAO
THUMUCHERLA

C-language
struct student student1;
Read(&student1); /* function call: passing reference */
printf("Name: %s", student1.name);
printf("\nID: %d\n", student1.id);
}
void Read (struct student *s1) /* function header, receive structure as a pointer variable */
{
printf("Enter name:");
scanf("%s",s1->name); /* you can also use: gets(s1->name) */
printf("Enter ID:");
scanf("%d",&s1->id);
}
Pointers to array of structures:
#include <stdio.h>
int main()
{
struct emp
{
int eno;
char ename[20];
float esal;
};
struct emp e[3];
struct emp *eptr[3];
int i=0;
for(i=0;i<3;i++)
{
eptr[i]=&e[i];
}
printf("enter the 3 employee details:\n");
for(i=0;i<3;i++)
{
printf("enter emp[%d] details(eno,ename,esal):\n",i+1);
scanf("%d%s%f",&e[i].eno,eptr[i]->ename,&eptr[i]->esal);
}
for(i=0;i<3;i++)
{
printf("emp[%d] details:\n",i+1);
printf("eno=%d\nename=%s\nesal=%f\n\n",eptr[i]>eno,e[i].ename,e[i].esal);
}
return 0;
}
Pointer to pointer:

ASHOKA RAO
THUMUCHERLA

C-language
Lets suppose we have a pointer p1 that points to yet another pointer p2 that points to a
character ch. In memory, the three variables can be visualized as :

So we can see that in memory, pointer p1 holds the address of pointer p2.
Pointer p2 holds the address of character ch.
So p2 is pointer to character ch, while p1 is pointer to p2 or we can also say that p2
is a pointer to pointer to character ch.
Now, in code p2 can be declared as :
char *p2 = &ch;
But p1 is declared as :
char **p1 = &p2;
So we see that p1 is a double pointer (ie pointer to a pointer to a character) and hence
the two *s in declaration.
Now,
p1 is the address of p2 ie 5000
*p1 is the value held by p2 ie 8000
**p1 is the value at 8000 ie c
#include<stdio.h>
int main(void)
{
char **ptr = NULL;
char *p = NULL;
char c = 'd';
p = &c;
ptr = &p;
printf("\n c = [%c]\n",c);
printf("\n *p = [%c]\n",*p);
printf("\n **ptr = [%c]\n",**ptr);
return 0;
}
How to read complex pointers in C Programming?
Rule 1. Assign the priority to the pointer declaration considering precedence and
associative according to following table.
Operator
(),[]
*, identifier
Data type

Precedence
1
2
3

Associative
Left to right
Right to left

ASHOKA RAO
THUMUCHERLA

C-language
Where
(): This operator behaves as function operator.
[]: This operator behaves as array subscription operator.
* : This operator behaves as pointer operator .
Identifier: it is name of pointer variable.
Data type: Data types also includes modifier (like signed int, long double etc.)
You will understand it better by examples:
(1) How to read following pointer?
char (* ptr)[3]
Step 1: () and [] enjoys equal precedence. So rule of associative will decide the priority. Its
associative is left to right So first priority goes to ().

Step 2: Inside the bracket * and ptr enjoy equal precedence. From rule of associative
(right to left) first priority goes to ptr and second priority goes to *.

Step3: Assign third priority to [].

Step4: Since data type enjoys least priority so assign fourth priority to char.

Now read it following manner:


ptr is pointer to such one dimensional array of size three which content
char type data.
(2) How to read following pointer?

ASHOKA RAO
THUMUCHERLA

C-language
float (* ptr)(int)
Assign the priority considering precedence and associative.

Now read it following manner:


ptr is pointer to such function whose parameter is int type data and return
type is float type data.
Rule 2: Assign the priority of each function parameter separately and read it also
separately.
Understand it through following example.
void (*ptr)(int (*)[2],int (*) void))
Assign the priority considering rule of precedence and associative.

Now read it following manner:


ptr is pointer to such function which first parameter is pointer to one
dimensional array of size two which content int type data and second parameter
is pointer to such function which parameter is void and return type is int data
type and return type is void.
How to read following pointer?
int ( * ( * ptr ) [ 5 ] ) ( )
Assign the priority considering rule of precedence and associative.

Now read it following manner:


ptr is pointer to such array of size five which content are pointer to such
function which parameter is void and return type is int type data.
How to read following pointer?
double*(*(*ptr)(int))(double **,char c)

ASHOKA RAO
THUMUCHERLA

C-language

ptr is pointer to function which parameter is int type data and return type
is pointer to function which first parameter is pointer to pointer of double data
type and second parameter is char type data type and return type is pointer to
double data type.
How to read following pointer?
unsigned **(*(*ptr)[8](char const *, ...)
Assign the priority considering rule of precedence and associative.

ptr is pointer to array of size eight and content of array is pointer to


function which first parameter is pointer to character constant and second
parameter is variable number of arguments and return type is pointer to pointer
of unsigned int data type.
Code1:
#include<stdio.h>
int main()
{
static char *s[] = {"black", "white", "pink", "violet"};
char **ptr[] = {s+3, s+2, s+1, s}, ***p;
p = ptr;
++p;
printf("%s", **p+1);
return 0;
}
#include<stdio.h>
int main()
{
char *s[]={"black","white","pink","violet"};
char **ptr[] = {s+1, s, s+3, s+2};
char ***p;
p = ptr;

ASHOKA RAO
THUMUCHERLA

C-language
p+1;
printf("%c\n", *(*(*++p+1))+3);
return 0;
}
Code2:
#include<stdio.h>
int main()
{
int i=3, *j, k;
j = &i;
printf("%d\n", i**j*i+*j);
return 0;
}
Code3:
#include<stdio.h>
int main()
{
int x=30, *y, *z;
y=&x; /* Assume address of x is 500 and integer is 4 byte size */
z=y;
*y++=*z++;
x++;
printf("x=%d, y=%d, z=%d\n", x, y, z);
return 0;
}
Code4:
#include<stdio.h>
int main()
{
char str[20] = "Hello";
char *const p=str;
*p='M';
printf("%s\n", str);
return 0;
}
Code5:
#include<stdio.h>
int main()
{
int ***r, **q, *p, i=8;
p = &i;
q = &p;

ASHOKA RAO
THUMUCHERLA

C-language
r = &q;
printf("%d, %d, %d\n", *p, **q, ***r);
return 0;
}
Code6:
#include<stdio.h>
void fun(void *p);
int i;
int main()
{
void *vptr;
vptr = &i;
fun(vptr);
return 0;
}
void fun(void *p)
{
int **q;
q = (int**)&p;
printf("%d\n", **q);
}
Code7:
#include<stdio.h>
int main()
{
void *vp;
char ch=74, *cp="JACK";
int j=65;
vp=&ch;
printf("%c", *(char*)vp);
vp=&j;
printf("%c", *(int*)vp);
vp=cp;
printf("%s", (char*)vp+2);
return 0;
}
Code8:
#include<stdio.h>
int main()
{
int arr[2][2][2] = {10, 2, 3, 4, 5, 6, 7, 8};
int *p, *q;

ASHOKA RAO
THUMUCHERLA

C-language
p = &arr[1][1][1];
q = (int*) arr;
printf("%d, %d\n", *p, *q);
return 0;
}
Code9:
#include<stdio.h>
int main()
{
int a[3][4] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12 };
printf("%u, %u, %u\n", a[0]+1, *(a[0]+1), *(*(a+0)+1));
return 0;
}
Code10:
#include<stdio.h>
int main()
{
int arr[3] = {2, 3, 4};
char *p;
p = arr;
p = (char*)((int*)(p));
printf("%d, ", *p);
p = (int*)(p+1);
printf("%d", *p);
return 0;
}
Code11:
#include<stdio.h>
int main()
{
char str[] = "peace";
char *s = str;
printf("%s\n", s++ +3);
return 0;
}
Code12:
#include<stdio.h>
int main()
{
char *p;
p="hello";
printf("%s\n", *&*&p);
return 0;

ASHOKA RAO
THUMUCHERLA

C-language
}

Summary:

C supports the use of pointers, a type of reference that records the address or
location of an object or function in memory.
Pointers can be dereferenced to access data stored at the address pointed to, or to
invoke a pointed-to function. Pointers can be manipulated using assignment or
pointer arithmetic.
Pointer arithmetic is automatically scaled by the size of the pointed-to data type.
Text strings are commonly manipulated using pointers into arrays of characters.
Pointers to functions are useful for passing functions as arguments to higher-order
functions.
Null pointer values are useful for indicating special cases such as no "next" pointer
in the final node of a linked list, or as an error indication from functions returning
pointers.
Void pointers (void *) point to objects of unspecified type, and can therefore be used
as "generic" data pointers.
Since the size and type of the pointed-to object is not known, void pointers cannot
be dereferenced, nor is pointer arithmetic on them allowed, although they can
easily be (and in many contexts implicitly are) converted to and from any other
object pointer type.
Careless use of pointers is potentially dangerous. Because they are typically
unchecked, a pointer variable can be made to point to any arbitrary location, which
can cause undesirable effects.
Although properly used pointers point to safe places, they can be made to point to
unsafe places by using invalid pointer arithmetic;

Dynamic Memory Allocation


Objectives:

Introduction to memory management?


What is static memory? Disadvantages of static memory?
What is dynamic memory?
Uses of dynamic memory allocation
What are pre-defined functions to allocate and deallocate memory dynamically
Allocation of memory dynamically using pre-defined functions
Advantages and disadvantages of dynamic memory allocation

Introduction:

ASHOKA RAO
THUMUCHERLA

C-language

Memory management is an art of managing computer memory. The essential


requirement of memory management is to provide ways to dynamically allocate portions
of memory to programs at their request, and freeing it for reuse when no longer needed.
This is critical to the computer system
The issue we address in this lecture is the efficient use of memory. The issue arises
because of inefficiencies inherent in the way memory is allocated for arrays. When you
declare an array of size 1000, all 1000 memory locations are reserved for the exclusive
use of that array. No matter how many values you actually store in the array, you will
always use 1000 memory locations. The same memory allocation strategy is used for most
implementations of strings. I will use the term static allocation to refer to this memory
allocation strategy, in which all the memory that a data structure might possibly need (as
specified by the user) is allocated all at once without regard for the actual amount needed
at execution time.
In some programming contexts, you need to process data but don't know what size of it is.
For example, you read a list of students from file but don't know how many student
records in the file. Yes, you can specify the maximum size for the the array but it is not
efficient in memory management. C provides you a powerful and flexible way to manage
memory allocation at runtime. It is called dynamic memory allocation. Dynamic means you
can specify the size of data at runtime. C programming language provides a set of
standard APIs to allow you to handle memory effectively. With dynamic memory allocation,
you can allocate and free memory as needed.

How much memory to allocate?


Sometimes obvious:

char
int

c;
array[10];

One byte
10 * sizeof(int) (= 40, usually)

Sometimes not:

ASHOKA RAO
THUMUCHERLA

C-language
Is this going to point to one character or a
How big will this array be?
string?

char *c;
int *array;

Static memory allocation: The compiler allocates the required memory space for
a declared variable. By using the address of operator, the reserved address is
obtained and this address may be assigned to a pointer variable. Since most of the
declared variable has static memory, this way of assigning pointer value to a pointer
variable is known as static memory allocation. memory is assigned during
compilation time.
The following pre-defined functions are responsible for allocating memory dynamically in C
language. These commonly used functions are available through the stdlib library so you
must include this library in order to use them.

Functi
on
malloc
()
calloc(
)
free()
realloc
()

Use Of Function
Allocates requested size of bytes and returns a pointer first byte of
allocated space
Allocates space for an array elements, initializes to zero and then
returns a pointer to memory
De allocate the previously allocated space
Change the size of previously allocated space

Getting to Know the Size of Data :


Before allocating memory, you need to know the way to identify the size of each
data so we can allocate memory accordingly. You can get the size of data by using
sizeof() function.
The sizeof() function returns a size_t an unsigned constant integer.
For example to get the size of integer type you can do as follows:
sizeof (int);
Dynamic Memory Allocation Process
When a program executes, the operating system gives it a stack and a heap to work
with.
The stack is where global variables, static variables, and functions and their locally
defined variables reside.
The heap is a free section for the program to use for allocating memory at runtime.

Allocating a Block of Memory


malloc():

Malloc function is used to allocate the memory dynamically when required.

ASHOKA RAO
THUMUCHERLA

C-language

It allocates size byte of memory and returns a pointer to the first byte
It returns NULL if there is some kind of error.
Malloc() function defined to allocate the memory for structure variables.
Malloc function available in stdlib library.
The prototype for malloc is:

void *malloc(size_t size);

Malloc function takes one argument that specifies the size of the area in bytes to
reserve for an argument.
Size_t represents unsigned type in most compilers.
Malloc function return type is void* that it can internally converts to any other
pointer. It doesnt need explicit conversion where as all the other typed pointers
requires explicit conversion.

Creation of memory for structure variable dynamically using malloc() :


Creation of structure:
Struct structure_name
{
-------------------------------}*var;
Creating memory :
*var = (struct structure_name*) malloc (sizeof(struct structure_name));
Allocation process steps:
Create one structure; it is working like user defined data type.
Create one pointer variable to that user defined structure.
Finding the size of the structure by calling sizeof() operator.
Passing size bytes as an argument to malloc() function.
If it allocates memory it return pointer to the first byte of type void.
We need to type cast that void pointer into our user defined structure type using
pointer type casting concept.
Assign the address of block into user defined structure variable.

Program to check locations of structure elements in memory


#include<stdio.h>

ASHOKA RAO
THUMUCHERLA

C-language
#include<stdlib.h>
int main()
{
struct emp
{
int eno;
char ename[20];
float esal;
};
struct emp *eptr;
eptr=(struct emp*)malloc(sizeof(struct emp));
printf("%u\n",&(eptr->eno));
printf("%u\n",&eptr->ename);
printf("%u\n",&eptr->esal);
return 0;
}
Program to store and retrieve employee info by creating memory structure
dynamically
#include<stdio.h>
#include<stdlib.h>
int main()
{
struct emp
{
int eno;
char ename[20];
float esal;
};
struct emp *eptr;
eptr=(struct emp*)malloc(sizeof(struct emp));
printf("enter employee details(eno,ename,esal):");
scanf("%d%s%f",&eptr->eno,eptr->ename,&eptr->esal);
printf("the details are :\n");
printf("eno=%d\nename=%s\nesal=%f\n",eptr->eno,eptr->ename,eptr->esal);
return 0;
}

calloc():

ASHOKA RAO
THUMUCHERLA

C-language

The calloc() function is used to allocate storage to a variable while the program is
running.
Calloc() function is used to reserve space for dynamic arrays, available in stdlib.h
library.
This library function is invoked by writing calloc (num, size).
This function takes two arguments that specify the number of elements to be
reserved, and the size of each element in bytes.
It allocates memory block equivalent to num*size.
The function returns a pointer to the beginning of the allocated storage area in
memory.
In an unsuccessful partitioning, NULL is returned.
The important difference between malloc() and calloc () function is that calloc()
initializes all bytes in the allocation block to zero and the allocated memory
may/may not be contiguous. Whereas malloc function initializes all bytes in
allocated block with some Garbage Values.

void * calloc (size_t n, size_t size);


For example, an int array of 10 elements can be allocated as follows.
int * arr1= (int *) calloc (10, sizeof (int));

Note that we can do the same thing using malloc() also that is as follows,
int * arr2 = (int *) malloc (sizeof (int) * 10);

Note: However, the malloc function, whereas the area reserved to the states that
are undefined, the area allocated by the calloc function contains a 0.

ASHOKA RAO
THUMUCHERLA

C-language

Program to allocate memory using malloc() function


# include<stdio.h>
# include<stdlib.h>
int main()
{
int *p,*i,j;
p=(int*)malloc(sizeof(int)*5);
if(p==NULL)
{
printf("Failed to allocate space for %d bytes", sizeof(int)*5);
exit(1);
}
i=p;
for(j=0;j<5;j++)
{
printf("%d\n",*i);
i++;
}
return 0;
}
Program to allocate memory using calloc function
# include<stdio.h>
# include<stdlib.h>
int main()
{
int *p,*i;
p=(int*)calloc(5,sizeof(int));
if(p==NULL)
{
printf("Failed to allocate space for %d bytes", sizeof(int)*5);
exit(1);
}
i=p;
while(i!=(p+5))
{
printf("%d\n",*i);
i++;
}
return 0;
}

ASHOKA RAO
THUMUCHERLA

C-language

Static memory allocation

Dynamic memory allocation

Memory is allocated during compilation time


Used only when the data size is fixed and
known in advance before processing.

Memory is allocated during execution time.


Used only for unpredictable memory
requirement.

malloc()
The syntax of malloc() is:
ptr = (data_type*)malloc(size);
The required number of bytes to be
allocated is specified as argument i.e., size
in bytes.

calloc()
The syntax of calloc() is:
ptr = (data_type*)calloc(n,size);
takes 2 arguments n number of blocks to
be allocated and size is number of bytes to
be allocated for each block.

Allocated space will not be initialized

Each byte of allocated space is initialized to


zero.

realloc():

With the function realloc(), you can change the size of the allocated area once.
It has the following form,
void * realloc (void * ptr, size_t size);
The first argument specifies the address of an area that is currently allocated.
Second argument specifies the new size in bytes of first argument.
It returns first bytes address of the allocated area else it returns NULL.
Size may be smaller but larger than the original. If you have small, reduced what
was written in part will be inaccessible. If you increase the portion of the region
will remain an indefinite increase.

STEP 1:

STEP 2:

ASHOKA RAO
THUMUCHERLA

C-language

STEP 3:

STEP 4:

#include <stdio.h>
#include <stdlib.h>
int main()
{
char *ptr, *retval;
ptr = (char *)calloc(10, sizeof(char));
if (ptr == NULL)
printf("calloc failed\n");
else
printf("calloc successful\n");

ASHOKA RAO
THUMUCHERLA

C-language
retval = realloc(ptr, 6);
if (retval == NULL)
printf("realloc failed\n");
else
printf("realloc successful\n");
free(ptr);
free(retval);
return 0;
}

free():

Function is used to releasing the Used Space.


The memory explicitly freed when no longer in use to prevent memory leaks.
Just remember that for every call to an *alloc function you must have a
corresponding call to free.
void free (void * ptr);
The argument specifies the address of a dynamically allocated area.
In addition, the space freed by the function free, guarantee that there is no data
remains intact. Thus, if once released, should not be accessing the same area.
By calling the free function it deletes the data inside the memory, but still pointer
pointing to the same memory location.
If you store NULL manually into the pointer variable, the data inside the memory will
not be deleted, but the pointer cannot point to the same location.

So, an example program that uses functions malloc and free functions in
practice.
# include<stdio.h>
# include<stdlib.h>
int main()
{
int *p;
p=(int*)malloc(sizeof(int)); /* partitioning of type int */
if (p == NULL) // failed to reserve area
{
printf ("Failed to allocate space for %d bytes", sizeof(int));
return;
}
*p=150;
printf ("%d\n", *p);
free (p); // free area
printf("%u\n",p);
printf ("%d\n", *p);
return 0;

ASHOKA RAO
THUMUCHERLA

C-language
}
Memory errors
Using memory that you have not initialized
Using memory that you do not own
Using more memory than you have allocated
Using faulty heap memory management
Advantages of DMA:
The main advantage of using dynamic memory allocation is preventingthe wastage of
memory. This is because when we use static memory allocation, a lot of memory is wasted
because all the memory allocated cannot be utilised. Thus dynamic memory allocation
helpsus to allocate memory as and when required and thus saves memory.
Disadvantages of DMA:
Freeing Memory
The user is responsible for freeing up memory when he is finished with it. This is a
seriousresponsibility, a potential source of bugs that are very hard to find.
For example, suppose you free up a location before you're actually finished with it.
Thenfurther access to the location will either cause a run-time error (memory
violation)or, what isworse (but more common), you will get access to a location that
is being used for somecompletely unrelated purpose.
Trouble also occurs if you forget to free up some space. If you do this, you are losing
theadvantages of dynamic allocation.
And in some circumstances - e.g. if you were writing the program that manages the
space on a disk drive - this could be disastrous.
There are no surefire safeguards against these problems, you must be very careful
whenwriting programs to return memory when you are finished with it, but not
before
Note the followings:
1. Don't free() memory twice. When you free memory, you relinquish your rights to it.
After you've free'd memory once, it is no longer yours. If you try to free it again,
what you're really trying to do is free memory that you don't own; it doesn't matter
that you once owned it, you don't anymore. So, free()ing memory twice is like
coding your program with the explicit instruction to crash.
2. Don't free() static memory, as in:
int arr[100];
free(arr); /* bad! */
3. Don't free anywhere but the beginning of a chunk of memory you've allocated. For
example, if you allocate a block of memory and store the address into a variable int
*steve, don't do something like free(steve + 5). This will result in the computer

ASHOKA RAO
THUMUCHERLA

C-language
attempting to free up the memory at steve + 5 which is not the exact address
previously returned by the operating system. This most likely won't crash your
program, but it might result in strange behavior.
Programs to understand allocation and deallocation of memory
Program1:
# include<stdio.h>
#include<stdlib.h>
int main()
{
int * p1, * p2;
p1 = (int *) calloc (5, sizeof (int)); /* number of elements in an array of type 5 int */
/ * To do something * /
p2 = (int *) realloc (p1, sizeof (int)); * / re-acquire the space of one type / * int
if (p2 == NULL) * / check if successful * /
{
free (p1); if it fails to get re-/ *, the region remains valid since the original * / to free myself
return 0;
}
p1 = NULL; safety measure * /. p1 is realloc () because it is released inside, / * Keep
assigning NULL to clear the other cannot use / * To do something * /
free (p2);
return 0;
}

Program2:
#include <stdio.h>
#include <stdlib.h>
int main()
{
int n,i,*ptr,sum=0;
printf("Enter number of elements: ");
scanf("%d",&n);
ptr=(int*)malloc(n*sizeof(int)); //memory allocated using malloc
if(ptr==NULL)
{
printf("Error! memory not allocated.");
exit(0);
}
printf("Enter elements of array: ");
for(i=0;i<n;++i)
{
scanf("%d",ptr+i);
sum+=*(ptr+i);
}

ASHOKA RAO
THUMUCHERLA

C-language
printf("Sum=%d",sum);
free(ptr);
return 0;
}
Program3:
#include <stdio.h>
#include <stdlib.h>
int main(){
int *ptr,i,n1,n2;
printf("Enter size of array: ");
scanf("%d",&n1);
ptr=(int*)malloc(n1*sizeof(int));
printf("Address of previously allocated memory: ");
for(i=0;i<n1;++i)
printf("%u\t",ptr+i);
printf("\nEnter new size of array: ");
scanf("%d",&n2);
ptr=realloc(ptr,n2);
for(i=0;i<n2;++i)
printf("%u\t",ptr+i);
return 0;
}
Program4:
#include<stdio.h>
#include<stdlib.h>
int main()
{
int *p1,*i,j;
p1=(int*)calloc(5,sizeof(int));
i=p1;
for(j=0;j<5;j++)
{
printf("%d\n",*i);
i++;
}
free(p1);
for(j=0;j<5;j++)
{
printf("%d\n",*i);
i++;
}
return 0;
}

ASHOKA RAO
THUMUCHERLA

C-language

Summary:
This property of creating dynamic structure variables is most used in dynamic data
structures, such as singly linked lists, doubly linked lists, linked stacks and linked queues,
trees and graphs.
Memory can be allocated either statically or dynamically. C uses runtime library functions,
such as malloc(), calloc() and realloc(), for allocation of memory dynamically and free()
function for releasing the memory dynamically. You can create memory space dynamically
for one-dimensional arrays, two-dimensional arrays, strings and structures.

ASHOKA RAO
THUMUCHERLA

C-language

Input and Output in C


Objectives

After working through this module you should be able to:


Identify and describe the purpose of the C standard input/output library.
Use the standard input operations in C programs.
Use the standard output operations in C programs.
Convert data values to formatted text using standard output operations.
State the significance of standard error output.
Use other input/output libraries, for example the Turbo C console library, to perform
input and output operations.
Working with other input/output libraries.
Screen output using CONIO.

Introduction

C is not a language rich in input and output facilities and the functions that are
provided are very primitive.
Particular input/output, libraries for support in developing the user interface for a
program.
The functions do not support mouse input, text-based or high resolution graphics
output, or other non-standard input and output devices. One library that will be
looked at in this module is the console input/output (CONIO) library that is provided
with the Turbo C development system.
This library extends the function provided in STDIO to include screen management
operations for text-based output.

STANDARD INPUT AND OUTPUT


The header file STDIO.H and its associated object code file define the
standard input and output operations.
This file forms part of the larger C standard library defined in the ANSI
standard for the language.
The standard library consists of 12 library files, each designated to a
particular purpose. The standard library includes data structures and
functions to:
o Handle strings, as defined in STRING.H
o Perform character tests and conversions, as defined in CTYPE.H
o Perform mathematical operations, as defined in MATH.H
o Perform number conversions, storage allocation and similar tasks, as
defined in STDLIB.H
o

Manipulate date and time data, as defined in TIME.H

These standard files or streams are called:


stdin : connected to the keyboard

ASHOKA RAO
THUMUCHERLA

C-language
stdout : connected to the screen
stderr: connected to the screen

Standard input/output functions:


Function
atof()

Format
[numvar = ]
atof(string);

atoi()

[numvar = atoi](string);

fflush(stdin)

fflush(stdin);

getchar()

[ch = ]getchar();

gets()

gets(string);

printf()

printf("format"[,var[,var
...]]);

putchar()

putchar(ch);

puts()

puts(string);

scanf()

scanf("format",&var);

Description
Converts a floating-point value found in
string into a floating-point number, which
can be stored in a variable, numvar, or used
immediately. Requires the STDLIB.H header
file to be included.
Converts an integer value found in string
into an integer, which can be stored in a
variable, numvar, or used immediately.
Requires the STDLIB.H header file to be
included.
Removes characters from the input stream
(keyboard).
Reads a single character from the keyboard.
The character is displayed and, optionally,
stored in the char variable ch.
Reads a string of text from the keyboard
(terminated by the Enter key). The text is
stored in the variablestring.
Displays formatted text according to
the formatstring. Optional values or
variables, var, can be specified to match
placeholders or conversion characters in the
format string.
Displays the character ch on the screen,
where ch is a single character (or escape
code) in single quotes or the name of a char
variable.
Displays the text string on the screen,
wherestring is a literal string of text
(enclosed in double quotes) or the name of
a string variable.
Reads information from the keyboard
according to the conversion character in
the format string. The information is then
stored in the variable var, which must
match the type of conversion character
that's used (int, float, or char, for example).

ASHOKA RAO
THUMUCHERLA

C-language
#include<stdlib.h>
void main()
{
char *s="20.5";
float num;
num =atof(s);
printf("%f",num);
}

printf():

The input/output functions fall into two categories, formatted display and read functions,
and non-formatted display and read functions. The following are descriptions of the
formatted display and read functions.
int printf( const char *format [,argument, ...] );

Where format is composed of literal text, escape sequences used as carriage


control, and format specifiers for conversion of data in the arguments to a display
format.
This function returns the number of characters printed.
printf() returns the number of bytes output.
In the event of error, printf returns EOF.
For example:

main()
{
char name[30];
printf("\nEnter your name:");
gets(name);
printf("\nHello %s",name);
}
Note: The printf() function has the capability to manage conversion control.
General form
%[-][width][flags]format
Where:
%
: marks the start of the conversion control string
: specifies that the data is to be printed left-justified
width : the width of field or number of spaces to allot on the display
flags
: precision of output to be displayed
format : the format specifier desired
#include "stdio.h"
int main()
{

ASHOKA RAO
THUMUCHERLA

C-language
printf("/%d/\n",336);
printf("/%2d/\n",336);
printf("/%10d/\n",336);
printf("/%-10d/\n",336);
return 0;
}
Conversion Character
c
d
e
f
g
h
i
o
x
s
u
[. . .]

Data type of input data


character
decimal integer
floating point value
floating point value
floating point value
short integer
decimal, hexadecimal or octal integer
octal integer
hexadecimal integer
string
unsigned decimal integer
string which may include whitespace characters

scanf():

int scanf( const char *format [,address, ...] );


where format is a list of format specifiers indicating the format and type of data to
be read from the keyboard and stored in the corresponding address.
There must be the same number of format specifiers and addresses as there are
input fields.
scanf returns the number of input fields successfully scanned, converted, and
stored.
The return value does not include scanned fields that were not stored. If scanf
attempts to read end-of- file, the return value is EOF.
If no fields were stored, the return value is 0.

#include "stdio.h"
int main()
{
char last_name[30];
int age, ret;
printf("\nEnter Last_name and age");
scanf("%s %d%c", last_name, &age, &ret);
return 0;
}
Non-formatted Input and Output

ASHOKA RAO
THUMUCHERLA

C-language
int puts( const char *s );
puts() displays a string literal or a stored character string on the screen.
The function automatically carriage return and line feeds at the end of the display.
The string can contain escape sequences but not format specifiers.
On successful completion, puts() returns a nonnegative value.
Otherwise, it returns a value of EOF.
#include "stdio.h"
int main()
{
char name[30];
printf("\nEnter your name:");
gets(name);
printf("\nHello ");
puts(name);
return 0;
}
char *gets( char *s );
gets() reads characters from the keyboard and stores them in a passed character
array.
The reading of keyboard is terminated when the '\n' (RETURN/ENTER) key is
pressed.
On success, gets() returns the string argument s; it returns NULL on end-of-file or
error.
#include "stdio.h"
int main()
{
char name[30];
printf("\nEnter your name:");
gets(name);
printf("\nHello %s",name);
return 0;
}
int putchar( int c );
putchar() writes a character to the stdout data stream.
On success, putchar() returns the character c. On error, putchar() returns EOF.
int putch( int c );
putch() writes the character directly to the screen.
This function is available only on PC based compilers.
On success, putch returns the characer printed, c. On error, it returns EOF.
#include "stdio.h"
int main()

ASHOKA RAO
THUMUCHERLA

C-language
{
int c;
c = 'A';
putchar(c);
putch(c);
return 0;
}
int getchar( void ); int getch( void ); int getche( void );
getchar() reads a single character the from the input data stream; but does not
return the character to the program until the '\n' (RETURN/ENTER) key is pressed.
getch() reads, without echoing, a single character from the keyboard and
immediately returns that character to the program; available only on PC compilers.
getche() reads, with echo, a single character from the keyboard and immediately
returns that character to the program; available only on PC compilers.
#include "stdio.h"
int main()
{
int ch;
printf("\nContinue(Y/N)?");
ch = getchar();
return 0;
}
NOTE: The '\n' (RETURN/ENTER) key must be pressed after the response in order for the
character to be stored in 'ch'. Also, the character pressed is automatically displayed on the
screen.
#include "stdio.h"
int main(){
int ch;
printf("\nContinue(Y/N)?");
ch = getch();
return 0;
}
NOTE: Upon pressing the 'Y' or 'N' key the character is immediately stored in 'ch', but the
character pressed is not automatically shown on the screen. This is available only with PC
based compilers.
#include "stdio.h"
int main()
{
int ch;
printf("\nContinue(Y/N)?");
ch = getche();
return 0;

ASHOKA RAO
THUMUCHERLA

C-language
}
NOTE: Upon pressing the 'Y' or 'N' key the character is immediately stored in 'ch' and also
is echoed on the screen. This is available only with PC based compilers.
CONIO Functions
The following definitions describe 12 functions that can be used to improve the
standard output produced by C programs. Bear in mind that because these functions are
not standard they are not supported outside the Turbo C environment. Further, because
they do not directly extend the functions provided by the standard library, they cannot be
used with programs that redirect standard input or output.
gotoxy():
Syntax: void gotoxy(int x, int y)
Description: The gotoxy() function sends the text screen cursor to the location specified
by x,y. If either or both of the coordinates are invalid, no action takes place.
clreol():
Syntax: void clreol(void)
Description: The clreol() function clears the screen from the current cursor position to the
end of the line in the active text window. The cursor position remains unchanged.
#include<conio.h>
#include<stdio.h>
void main()
{
FILE *fp;
int i;
clrscr();
fp=fopen("src.c","r");
while((i=getc(fp))!=EOF)
{
printf("%c",i);
}
gotoxy(1,5);
clreol();
}
clrscr():
Syntax: void clrscr(void)
Description: The clrscr() function clears the entire active text window and locates the
cursor in the upper-left corner (1,1). The colour of the window is set to the current
textbackground colour.
delline():
Syntax: void delline(void)

ASHOKA RAO
THUMUCHERLA

C-language
Description: The delline() function deletes the line in the active window that contains the
cursor. All lines below the deleted line are moved up to fill the gap and a blank line is
inserted at the bottom of the window. Only the text inside the cureent window is affected.
#include<conio.h>
#include<stdio.h>
void main()
{
FILE *fp;
int i;
clrscr();
fp=fopen("src.c","r");
while((i=getc(fp))!=EOF)
{
printf("%c",i);
}
gotoxy(1,5);
delline();
}
gettext():
Syntax: int gettext(int left, int top,int right, int bottom, void *buf)
Description: The gettext() function copies into the buffer pointed to by buf the text from
the rectangle defined by left,top and right,bottom. The coordinates are screen coordinates,
not window relative. buf needs to point to an amount of memory equal to 2 rows
columns. The function returns 1 if the action was successful, 0 on failure.
insline():
Syntax: void insline(void)
Description: The insline() function inserts a blank line at the current cursor position, and
all the lines below the cursor move down. The function only affects the active text window.
movetext():
Syntax: int movetext(int left, int top, int right, int bottom, int newleft, int newtop)
Description: The movetext() function moves the portion of the screen defined by the
rectangle left,top and right, bottom to the region of the screen that has its upper-left
corner defines by newleft, newtop. The coordinates are screen coordinates, not window
relative. The function returns 1 if the action was successful, 0 on failure.
puttext():
Syntax: int putttext(int left, int top, Int right, int bottom, void *buf)
Description: The gettext() function copies the text previously saved in the buffer pointed
to by buf to the region defined by left,top and right,bottom. The coordinates are screen
coordinates, not window relative. The function returns 1 if the action was successful, 0 on
failure.
textattr():
Syntax: void clreol(int attr)

ASHOKA RAO
THUMUCHERLA

C-language
Description: The textattr() function sets both the foreground and background colours in
the text screen at one time. The value of attr represents an encoded form of the colour
information. For example, to set the colours to be white text on a green background, attr
would be defined as GREEN*16 | WHITE.
textbackground():
Syntax: void clreol(int colour)
Description: The textbackground() function sets the background colour of a text screen.
A call to textbackground() only affects subsequent write operations. The existing
background colour(s) remain unchanged. The valid values for colour are shown below:
BLACK
0
BLUE
1
GREEN
2
CYAN
3
RED
4
MAGENTA
5
BROWN
6
LIGHTGRAY 7
textcolor():
Syntax: void textcolor(int colour)
Description: The textcolor() function sets the color of the text displayed on the screen.
The valid values for colour are:
BLACK
0
DARKGRAY
8
BLUE
1
LIGHTBLUE
9
GREEN
2
LIGHTGREEN
10
CYAN
3
LIGHTCYAN
11
RED
4
LIGHTRED
12
MAGENTA
5
LIGHTMAGENTA
13
BROWN
6
YELLOW
14
LIGHTGRAY 7
WHITE
15
window():
Syntax: void window(int left, int top, int right, int bottom)
Description: The window () function is used to create a rectangular text window whose
upper-left and lower-right coordinates are specified by left, top and right, bottom
respectively. If any coordinate is invalid, window () takes no action.

ASHOKA RAO
THUMUCHERLA

C-language

Files
Objectives:

After working through this module you should be able to distinguish between the
data stored in, and the operations performed on?
What are text and binary files?
How to perform file operations such as opening a file, reading and writing a file and
closing a file?
How to work with file handling library functions?
How to create pointers to files to work on?
How to work with error handling functions?

Introduction:
We frequently use files for storing information which can be processed by our programs. In
order to store information permanently and retrieve it we need to use files.
In order to use files we have to learn about File I/O i.e. how to write information to a file
and how to read information from a file.
We will see that file I/O is almost identical to the terminal I/O that we have being using so
far.
As you know, you can have many files on your disk. If you wish to use a file in your
programs, then you must specify which file or files you wish to use.
Specifying the file you wish to use is referred to as opening the file.
When you open a file you must also specify what you wish to do with it i.e. Read from the
file, Write to the file, or both.
Because you may use a number of different files in your program, you must specify when
reading or writing which file you wish to use. This is accomplished by using a variable
called a file pointer.
Every file you open has its own file pointer variable. When you wish to write to a file you
specify the file by using its file pointer variable.

What is a File?
A file is a collection of bytes stored on a secondary storage device, which is generally a
disk of some kind. The collection of bytes may be interpreted,
As characters, words, lines, paragraphs and pages from a textual document;
Fields and records belonging to a database;
Pixels from a graphical image.

ASHOKA RAO
THUMUCHERLA

C-language

C supports a number of functions that have the ability to perform basic file operations
which include:
1) Naming a file
2) Opening a file
3) Reading from a file
4) Writing data into a file
5) Closing a file
Library functions to work with files in C:

File name

Description

fopen()
fclose()
fseek()
rewind()
rename()
remove()
fprintf()
fscanf()
fwrite()
fread()
putc()
getc()
fputs()
fgets()
getw()
putw()

Create or open a file for reading or writing or appending.


Close a file after reading or writing it.
Seek to a certain location in a file.
Rewind a file back to its beginning and leave it open.
Rename a file.
Delete a file.
Formatted write.
Formatted read.
Unformatted write
Unformatted read.
Write a single byte to a file.
Read a single byte from a file.
Write a string to a file.
Read a string from a file.
Reads int data into a file
Write int data into a file

Note: All these library functions depend on definitions made in the "stdio.h" header
file, and so require the declaration:
#include <stdio.h>

fopen():
The "fopen()" function opens and, if need be, creates a file.
Its syntax is:
<file pointer> = fopen( <filename>, <access mode> );
The "fopen()" function returns a "file pointer", declared as follows:
FILE *<file pointer>;

ASHOKA RAO
THUMUCHERLA

C-language

NOTE: When you open a file, you must specify how it is to be opened. This means
whether to create it from new overwrite it and whether it's text or binary, read or
write and if you want to append to it. This is done using one or more file mode
specifies which are single letters "r", "b", "w", "a"
The "access modes" are defined as follows:

Access
mode

Description
Open file for reading and file must exist;

r
w

Open file for writing. If file does not exist it is created or if file
already exist its content is erased.

Open file for appending. It adds all information at the end of the file
leaving old data untouched. If file does not exist it is created.
Open file for reading and writing and file must exist.

r+
w+

a+

Open file for writing and reading. If file does not exist it is created
or if file already exists its content is erased.
Open file for appending and reading. Again all new data is written
at the end of the file old data leaving untouched. If file does not
exist it is created. (You can read old data by moving pointer in file
using fseek or rewind functions from stdio.h. But all writing
operations will be done at the end of the file no matter how you
change pointer)

ASHOKA RAO
THUMUCHERLA

C-language

Opening a File
To work with a file first we have to declare a pointer of type FILE points to the
corresponding file.

FILE *fp;

In the above code, we declared the variable, but it doesn't point to anything yet. Here's
how you make it point to a file called "results.txt" that you intend to write to:
#include <stdio.h>
int main(void)
{
FILE *fp;
fp = fopen("results.txt", "w"); //here w stands for write mode and it is a character
pointer.
return 0;
}
Here's how you would open a file to read from it:
#include <stdio.h>
int main(void){
FILE *fp;
fp = fopen("results.txt", "r");//here r stands for read mode and it is a character
pointer.
return 0;
}
Open a file named "results.txt" to append data to it:
#include <stdio.h>
int main(void)
{
FILE *fp;
fp = fopen("results.txt", "a");//here a stands for append mode and it is a character
pointer.

ASHOKA RAO
THUMUCHERLA

C-language
return 0;
}
Note: It is possible for fopen to fail even if your program is perfectly correct: you
might try to open a file specified by the user, and that file might not exist (or it
might be write-protected). In those cases, fopen will return NULL pointer.
#include <stdio.h>
#include <stdlib.h>
int main(void)
{
FILE *fp;
fp = fopen("results.txt", "r");
if (fp == NULL) {
printf("I couldn't open results.txt for reading.\n");
exit(1);
}
return 0;
}
Here, "r" is used to indicate that the text file is about to be opened for reading only. If an
error occurs such as the file is non-exist, when the fopen() function tries to open the file,
the function returns a null pointer.

Then an error message is printed out by the printf() function and the program is
aborted by calling the exit() function with a nonzero value

fclose():
After a disk file is read, written, or appended with some new data, you have to
disassociate the file from a specified stream by calling the fclose() function.

The prototype for the fclose() function is:


int fclose(FILE *stream);
Here, stream is a file pointer that is associated with a stream to the opened file.
If fclose() closes a file successfully, it returns 0. Otherwise, the function returns EOF.

#include<stdio.h>
int main()
{
FILE *fp,*fs;
int i,j;
fp=fopen("abc.txt","r");
if(fp==NULL)
{
printf("cannot open file");
exit(1);

ASHOKA RAO
THUMUCHERLA

C-language
}
i=fclose(fp);
fs=fp;
j=fclose(fs);
printf("%d\n%d",i,j);
return 0;
}
EOF:(End Of File)
EOF is a macro defined as an int with a negative value. It is normally returned by
functions that perform read operations to denote either an error or end of input.
#include<stdio.h>
int main()
{
printf("%d\n%c\n%c",EOF,EOF,-1);
return 0;
}

Reading a char from a file:

Returns the character currently pointed by the internal file position indicator of the
specified stream. The internal file position indicator is then advanced to the next
character.
int getc(FILE *stream);
int fgetc(FILE *stream);
On success both functions return the unsigned char that they read
On failure both functions return EOF.
#include<stdio.h>
int main()
{
FILE *fp;
char ch;
fp=fopen("example.c","r");
if(fp==NULL)
{
printf("cannot open file to read...");
exit(1);
}
while((ch=fgetc(fp))!=EOF)
{
printf("%c",ch);
}
return 0;
}

Writing data into a File:

The below two functions can a write a single character into any opened file.

ASHOKA RAO
THUMUCHERLA

C-language
int fputc ( int character, FILE * stream );
int putc ( int character, FILE * stream );

On success writes the character to the file and returns the character written.
On failure both functions return EOF.

#include<stdio.h>
int main()
{
FILE *f1;
char ch;
printf("Input the data into a file to stop (press '.') :");
f1=fopen("input.txt","w");
if(f1==NULL)
{
printf("unable to access file");
exit(0);
}
while((ch=getchar())!='.')
{
printf("%c",ch);
putc(ch,f1);
}
fclose(f1);
f1=fopen("input.txt","r");
while((ch=fgetc(f1))!=EOF)
{
printf("%c", ch);
}
fclose(f1);
return 0;
}
ungetc (): Pushes a character back into the input stream.
Syntax:
int ungetc(int c, FILE *stream);

Virtually puts a character back into a file.


Doesnt modify the file.
On success, returns the character that was pushed
On failure returns EOF.

#include <stdio.h>
#include <string.h>
int main()
{
FILE *fp;

ASHOKA RAO
THUMUCHERLA

C-language
char ch;
fp=fopen("e.c","r");
while((ch=getc(fp))!=EOF)
{
if(ch=='a')
{
ungetc('*',fp);
}
else
{
printf("%c",ch);
}
}
fclose(fp);
return 0;
}

#include <stdio.h>
#include <string.h>
int main()
{
FILE *f;
int i;
char tmp[40];
if (f = fopen("e.c", "r"))
{
int blas = 0;
while (!feof(f))
{
char c = getc(f);
if (c == 'b')
{
ungetc('4', f);
//replace 4 with b and see the output
for (i = 0; i < 3; ++i)
tmp[i] = getc(f);
tmp[3] = 0;
if (!strcmp(tmp, "bla"))
++blas;
}
}
fclose(f);
printf("Number of bla's: %d\n", blas);
}
return 0;
}

ASHOKA RAO
THUMUCHERLA

C-language

Reading a string from a file:


char* fgets(char *str, int size, FILE *stream);

The fgets() function reads at most one less than the number of characters
specified by size from the given stream and stores them in the string str.
Reading stops when a newline character is found, at end-of-file or error.
If any characters are read and there is no error, a \0 character is appended to end
the string.
On success returns a pointer to str.
On failure returns NULL(not EOF)

Parameters:
Str: Pointer to an array of chars where the string read is copied.
Size: Maximum number of characters to be copied into str (including the terminating nullcharacter).
Stream: Pointer to a FILE object that identifies an input stream.
#include<stdio.h>
#include<string.h>
int main()
{
FILE *fp;
char str[10];
fp=fopen("e.c","r");
while(fgets(str,10,fp)!=NULL)
{
printf("%s\t",str);
}
fclose(fp);
return 0;
}
Writing a string into a file:
int fputs (char* str, FILE *stream );

Writes the C string pointed by str to the stream.


The function begins copying from the address specified (str) until it reaches the
terminating null character ('\0'). This terminating null-character is not copied to the
stream.

Parameters:
Str:C string with the content to be written to stream.
Stream:Pointer to a FILE object that identifies an output stream.

ASHOKA RAO
THUMUCHERLA

C-language

#include<stdio.h>
#include<string.h>
int main(){
FILE *fp1,*fp2;
char str[10];
char ch;
fp1=fopen("e.c","r");
fp2=fopen("sample.txt","w");
while(fgets(str,10,fp1)!=NULL)
{
fputs(str,fp2);
}
fclose(fp2);
fp2=fopen("sample.txt","r");
while((ch=fgetc(fp2))!=EOF){
printf("%c",ch);
}
fclose(fp1);
fclose(fp2);
return 0;
}

fscanf() and fprintf():

fscanf():The fscanf() function reads from the named input stream.


int fscanf(FILE *stream, const char *format, ... );
fprintf():The fprintf() function sends information (the arguments) according to the
specified format to the file indicated by stream.
int fprintf( FILE *stream, const char *format, ... );
#include <stdio.h>
#include <stdlib.h>
int main(void)
{

ASHOKA RAO
THUMUCHERLA

C-language
FILE *fp;
char s[80];
int t;
if((fp=fopen("test","w"))==NULL)
{
printf("Cannot open file.\n");
exit(1);
}
printf("Enter a string and a number: ");
fscanf(stdin,"%s%d",s,&t); /* read from keyboard */
fprintf(fp,"%s%d",s,t); /* write to file */
fclose(fp);
if((fp=fopen("test","r")) == NULL)
{
printf("Cannot open file.\n");
exit(1);
}
fscanf(fp,"%s%d",s,&t); /* read from file */
fprintf(stdout,"%d",t); /* print on screen */
return 0;
}

sscanf():The sscanf() function reads from the string s.


int sscanf(const char *s, const char *format, ... );
#include<stdio.h>
int main()

ASHOKA RAO
THUMUCHERLA

C-language
{
char buff[20]={"Sarah 111.2"};
char name[10];
float num;
sscanf(buff,"%s %f", name, &num);
printf("%s %.2f", name, num);
getchar();
}
sprintf():Write formatted data to string.
int sprintf ( char * str, const char * format, ... );

A terminating null character is automatically appended after the content.


On success, the total number of characters written is returned. This count does not
include the additional null-character automatically appended at the end of the
string.
On failure, a negative number is returned.

#include <stdio.h>
int main ()
{
char buffer [50];
int n, a=5, b=3;
n=sprintf (buffer, "%d plus %d is %d", a, b, a+b);
printf ("[%s] is a string %d chars long\n",buffer,n);
return 0;
}

fseek(): The "fseek()" function call allows the byte location in a file to be selected for
reading or writing.
Syntax:
int fseek( <file_pointer>, <offset>, <origin> );
The offset is a "long" and specifies the offset into the file, in bytes. The "origin" is an "int"
and is one of three standard values, defined in "stdio.h":
SEEK_SET Start of file.
SEEK_CUR Current location.
SEEK_END End of file.

Returns 0 on success
Returns non-zero on failure.

ASHOKA RAO
THUMUCHERLA

C-language

fseek(fp, 100, SEEK_SET); // seek to the 100th byte of the file


fseek(fp, -30, SEEK_CUR); // seek backward 30 bytes from the current pos
fseek(fp, -10, SEEK_END); // seek to the 10th byte before the end of file
fseek(fp, 0, SEEK_SET); // seek to the beginning of the file
rewind(fp);
// seek to the beginning of the file
Code1:
#include <stdio.h>
int main ()
{
FILE * pFile;
pFile = fopen ( "myfile.txt" , "w" );
fputs ( "This is an apple." , pFile );
fseek ( pFile , 9 , SEEK_SET );
fputs ( " sam" , pFile );
fclose ( pFile );
return 0;
}
Code2:
#include <stdio.h>
int main ()
{
FILE *pFile;
char ch;
pFile=fopen("e.c","r");
fseek(pFile,10,SEEK_SET );
while((ch=fgetc(pFile))!=EOF)
{
printf("%c",ch);
}
fclose(pFile);
return 0;
}
rewind():
The "rewind()", "rename()", and "remove()" functions are straightforward. The
"rewind()" function resets an open file back to its beginning. It has the syntax:
void rewind( <file_pointer> );
#include <stdio.h>
int main ()
{
FILE *pFile;

ASHOKA RAO
THUMUCHERLA

C-language
char ch;
pFile=fopen("e.c","r");
fseek(pFile,70,SEEK_SET );
while((ch=fgetc(pFile))!=EOF)
{
printf("%c",ch);
}
rewind(pFile);
printf("\n\n\n");
while((ch=fgetc(pFile))!=EOF)
{
printf("%c",ch);
}
fclose(pFile);
return 0;
}
rename():The "rename()" function changes the name of a file:
rename( <old_file_name_string>, <new_file_name_string> );

If the file is successfully renamed, a zero value is returned.


On failure, a nonzero value is returned.

#include <stdio.h>
int main ()
{
int result;
char old[] ="sample.txt";
char new[] ="hello.txt";
result= rename(old,new);
if(result==0)
puts("File successfully renamed" );
else
puts("Error renaming file");
return 0;
}
remove():The "remove()" function deletes a file:
remove( <file_name_string>)

If the file is successfully deleted, a zero value is returned.


On failure, a nonzero value is returned.

perror():The perror() function is another of C's error-handling tools. When called, perror()
displays a message on stderr describing the most recent error that occurred during a
library function call or system call.

ASHOKA RAO
THUMUCHERLA

C-language
The prototype, in STDIO.H, is
void perror(char *msg);

The argument msg points to an optional user-defined message.


This message is printed first, followed by a colon and the implementation-defined
message that describes the most recent error.
If you call perror() when no error has occurred, the message displayed is no error.

#include<stdio.h>
int main()
{
if(remove("hello.txt"))
{
perror("error in deleting file");
}
else
{
perror("successfully removed");
}}
fwrite() and fread():
The "fwrite()" and "fread()" functions are used for binary file I/O. The syntax of "fwrite()" is
as follows:
fwrite( <array_pointer>, <element_size>, <count>, <file_pointer> );

The array pointer is of type "void", and so the array can be of any type.
The element size and count, which give the number of bytes in each array element
and the number of elements in the array, are of type "size_t", which are equivalent
to "unsigned int".
File_pointer is the file stream

The "fread()" function similarly has the syntax:


fread( <array_pointer>, <element_size>, <count>, <file_pointer> );
The "fread()" function returns the number of items it actually read. #include <stdio.h>
#include <math.h>
#define SIZE 20
void main()
{
int n;
float d[SIZE];
FILE *fp;
for( n = 0; n < SIZE; ++n )
/* Fill array with roots. */

ASHOKA RAO
THUMUCHERLA

C-language
{
d[n] =(float)sqrt((double)n);
}
fp = fopen("data","w+");
/* Open file. */
fwrite(d,sizeof(float),SIZE,fp);
/* Write it to file. */
rewind(fp);
/* Rewind file. */
fread(d,sizeof(float),SIZE,fp);
/* Read back data. */
for(n=0;n<SIZE;++n)
/* Print array. */
{
printf( "%d: %7.3f\n", n, d[n] );
}
fclose( fp );
/* Close file. */
}The getw() and putw() functions:
These are integer-oriented functions. They are similar to getc() and putc() functions
and are used to read and write integer values. These functions would be useful when we
deal with only integer data.
The general forms of getw() and putw() are:
int putw(integer, FILE *stream);
int getw(FILE *stream);
#include<stdio.h>
int main()
{
FILE *f1,*f2,*f3;
int number,i;
f1=fopen("DATA.txt","w");
for(i=1;i< 30;i++)
{
putw(number,f1);
}
fclose(f1);
f1=fopen("DATA.txt","r");
f2=fopen("ODD.txt","w");
f3=fopen("EVEN.txt","w");
while((number=getw(f1))!=EOF)/* Read from data file*/
{
if(number%2==0)
{
putw(number,f3);/*Write to even file*/
}
else
{
putw(number,f2);/*write to odd file*/
}
}
fclose(f1);

ASHOKA RAO
THUMUCHERLA

C-language
fclose(f2);
fclose(f3);
f2=fopen("ODD.txt","r");
f3=fopen("EVEN.txt","r");
printf("\nContents of the odd file :");
while((number=getw(f2))!=EOF)
{
printf("\t%d",number);
}
printf("\nContents of the even file :");
while((number=getw(f3))!=EOF)
{
printf("\t%d",number);
}
fclose(f2);
fclose(f3);
return 0;
}

ASHOKA RAO
THUMUCHERLA

C-language

PREPROCESSOR
Preprocessor
a system program that modifies the text of a C program before it is compiled
Occurs before a program is compiled
Inclusion of other files
Definition of symbolic constants and macros
Conditional compilation of program code
Conditional execution of preprocessor directives
Preprocessing, Compiling and Linking
There are three basic phases that are important when programming in C and using a C
compiler. The phases are called preprocessing, compiling, and linking. When
programming in other languages, only two phases are required: compiling and linking.

A C input file is first passed to a preprocessing program called the preprocessor.

The output of the preprocessor is passed to the true-C compiler.

The output of the C compiler is then fed into a linker program.

The linker finally produces an executable form of your program.

The following diagram demonstrates a C program one.c being converted into an


executable program.

one.c --> PREPROCESSOR -> tmp.c(temporary)


LINKER -> one.exe (final Executable)

-> COMPILER -> one.obj

->

Preprocessing Phase:
A C preprocessor is a program that accepts C code with preprocessing statements
and produces a pure form of C code that contains no preprocessing statements. A
preprocessor basically reads line by line from the input and replicates the line to the
output. If the line is a preprocessing statement, then it performs the preprocessing
directives. All preprocessing statements in C begin with the # symbol and are at the
beginning of a line. The operations of taking the input file and generating the output file, is
called pre-processing.

ASHOKA RAO
THUMUCHERLA

C-language
Input File(ie One.c)

---> Preprocessor

--> Output File (ie tmp.c )

The output file is then fed as input into the true C compiler. If there are no
preprocessing directives in the original C input file, then the output file will look identical
to the input file.
The preprocessing language consists of directives to be executed and macros to be
expanded. Its primary capabilities are:

Inclusion of header files. These are files of declarations that can be substituted into
your program.
Macro expansion. You can define macros, which are abbreviations for arbitrary
fragments of C code. The preprocessor will replace the macros with their definitions
throughout the program. Some macros are automatically defined for you.
Conditional compilation. You can include or exclude parts of the program according
to various conditions.
Line control. If you use a program to combine or rearrange source files into an
intermediate file which is then compiled, you can use line control to inform the
compiler where each source line originally came from.

The # is followed by an identifier, is the directive name. It specifies the operation to


perform. Directives are commonly referred to as #name where name is the directive
name.
For example, #define is the directive that defines a macro.
Inclusion of header files:
A header file is a file containing C declarations and macro
definitions to be shared between several source files.
You request the use of a header file in your program by
including it, with the C preprocessing directive #include.

#include
Copy of a specified file included in place of the directive
#include <filename>
Searches standard library for file
Use for standard library files
#include "filename"
Searches current directory, then standard library
Use for user-defined files
Used for:
Programs with multiple source files to be compiled together

For example,
if you have a header file header.h as follows,
int x;

ASHOKA RAO
THUMUCHERLA

C-language
int biggest(int x, int y)
{
retrun x>y?x:y;
}
and a main program called program.c that uses the header file, like this,
#include "header.h"
int main (void)
{
x=biggest(10,20);
printf(big :%d,x);
return 0;
}
the compiler will see the same token stream as it would if program.c read
int x;
int biggest(int x, int y)
{
retrun x>y?x:y;
}
int main (void)
{
x=biggest(10,20);
printf(big :%d,x);
return 0;
}
Macros:
A macro is a fragment of code which has been given a name. Whenever the name is
used, it is replaced by the contents of the macro. There are two kinds of macros. They
differ mostly in what they look like when they are used. Object-like macros resemble data
objects when used, function-like macros resemble function calls.
Object-like Macros
An object-like macro is a simple identifier which will be replaced by a code
fragment. It is called object-like because it looks like a data object in code that uses it.
They are most commonly used to give symbolic names to numeric constants.
You create macros with the #define directive. #define is followed by the name of
the macro and then the token sequence it should be an abbreviation for, which is variously
referred to as the macros body, expansion or replacement list.

ASHOKA RAO
THUMUCHERLA

C-language

The #define Preprocessor Directive:

#define
Preprocessor directive used to create symbolic constants and macros
Symbolic constants
When program compiled, all occurrences of symbolic
constant replaced with replacement text
Format
#define identifier replacement-text
Example:
#define PI 3.14159
Everything to right of identifier replaces text
#define PI = 3.14159
Replaces PI with "= 3.14159"
Note: Cannot redefine symbolic constants once they have been created

Function-like Macros
You can also define macros whose use looks like a function call. These are called
function like macros. To define a function-like macro, you use the same #define directive,
but you put a pair of parentheses immediately after the macro name.
For example,
#define CIRCLE_AREA( x ) ( PI * ( x ) * ( x ) )
Would cause
area = CIRCLE_AREA( 4 );
To become
area = ( 3.14159 * ( 4 ) * ( 4 ) );
Use parenthesis
Without them the macro
#define CIRCLE_AREA( x ) PI * x * x
Would cause
area = CIRCLE_AREA( c + 2 );
To become
area = 3.14159 * c + 2 * c + 2;

ASHOKA RAO
THUMUCHERLA

C-language

#define CIRCLE_AREA( x ) PI * (x) * (x)


area = 3.14159 *( c + 2) * (c + 2);

Multiple arguments
#define RECTANGLE_AREA( x, y ) ( ( x ) * ( y ) )
Would cause
rectArea = RECTANGLE_AREA( a + 4, b + 7 );
To become
rectArea = ( ( a + 4 ) * ( b + 7 ) );
Predefined Macros
Several object-like macros are predefined; you use them without supplying their
definitions.
Use of the preprocessor is advantageous since it makes:

programs easier to develop,

easier to read,

easier to modify

C code more transportable between different machine architectures.

Conditional Compilation (#if, #ifdef, #ifndef, #else, #elif, #endif)


Six directives are available to control conditional compilation. They delimit blocks of
program text that are compiled only if a specified condition is true. These directives can be
nested.
The beginning of the block of program text is marked by one of three directives:
#if
#ifdef
#ifndef
Optionally, an alternative block of text can be set aside with one of two directives:
#else
#elif
The end of the block or alternative block is marked by the directive.
#endif
NOTE:
If the condition checked by #if , #ifdef , or #ifndef is true (nonzero), then all
lines between the matching #else (or #elif ) and an #endif directive, if present,
are ignored.
ASHOKA RAO
If the condition is false (0), then
the
lines
between
the
#if
,
#ifdef
,
THUMUCHERLA
or #ifndef and an #else , #elif , or #endif directive are ignored.

C-language

#if directive :
It is conditional compilation directive. That is if condition is true then it will compile
the c programming code otherwise it will not compile the c code.
Syntax :
#if <Constant_expression>
------------------------#endif
If constant expression will return 0 then condition will FALSE if it will return any non zero
number condition will TRUE.
#include<stdio.h>
#if 0
int main(){
printf("HELLO WORLD");
return 0;
}
#endif
RE: undefined symbol main
#else directive:
Syntax :
#if <Constant_expression>
--------------------------------#else
--------------------------------#endif
Code1:
#include<stdio.h>
#if(-4)
int main(){
printf("WELCOME TO C-WORLD ");
return 0;
}
#else
int main(){

ASHOKA RAO
THUMUCHERLA

C-language
printf("HELLO WORLD");
return 0;
}
#endif
Output: WELCOME TO C-WORLD
Explanation: -4 is non zero integer constant. So #if condition is true.
Code2:
#include<stdio.h>
#if -2
int main(){
printf("HELLO WORLD");
return 0;
}
#else
int main(){
printf("WELCOME TO C-WORLD ");
return 0;
}
#endif
Output: HELLO WORLD
Explanation: -2 is non zero number so #if condition is true.
Note: Consonant expression in #if condition should not include any c programming
variable since all preprocessor directives execute just before the actual c code.
Code3:
#include<stdio.h>
int main(){
int var = 5;
#if var
printf("%d",var);
#else
printf("%d",var);
#endif
return 0;
}
Output: CE:
Explanation: Directive #if will not think expression constant var as integer variable and
also it will not throw an error. Then what is var for directive #if?
Directive #if will treat var as undefined macro constant. In C, any undefined macro
constant returns zero so #else directive will execute. So proper way of above c code is:

ASHOKA RAO
THUMUCHERLA

C-language
#include<stdio.h>
#define var 10
int main(){
#if var
printf("%d",var);
#else
printf("%d",var);
#endif
return 0;
}
Note: Constant expression in #if directive cannot be string constant. It can be
character constant which returns its ASCII value to directive.

# elif directive
Processor directive #elif is part of #if directive. It will execute only if its just previous
constant expression of #if or #elif is zero.
Syntax:
#if <Constant_expression>
----------------------------------#elif <Constant_expression>
----------------------------------#elif <Constant_expression>
----------------------------------#else
----------------------------------#endif
#include<stdio.h>
int main(){
#if(!5>=5)
int a=5;
#elif -1
int a=10;
#else
int a=15;
#endif
printf("%d",a);
return 0;

ASHOKA RAO
THUMUCHERLA

C-language
}
Its intermediate file will look like:
int main()
{
int a=10;
printf("%d",a);
return 0;
}

#ifdef directive:
Directive #ifdef is very similar to #if except its conditional statement which is
identifier instead of a constant expression. Identifier may a macro constant or global
identifier. It only checks identifier has been defined or not. It doesnt care what the value
of identifier is. If identifier has been defined then it executes #ifdef body otherwise it
executes the body of #else directive.
Note: Global identifiers are predefined macro constants.
Syntax:
#ifdef <Identifer>
------------------------#else
------------------------#endif
#include<stdio.h>
#define ABC 25
#define PQR "Exact Help"
int main(){
int num = 3;
#ifdef ABC
printf("%d",ABC * ABC);
#else
printf("%s",PQR);
#endif
return 0;
}

ASHOKA RAO
THUMUCHERLA

C-language
Output: 625
Explanation: Since macro constant ABC has defined so #ifdef condition is true.
#include<stdio.h>
int main(){
#ifdef __DATE__
printf("%s",__DATE__);
#else
printf("First define the __DATE__");
#endif
return 0;
}
#include<stdio.h>
#include<limits.h>
#define ABC 25
#define PQR "Exact Help"
int main()
{
int num = 3;
#ifndef EOF
printf("%d\n",ABC * ABC);
#else
printf("%d\n",INT_MIN);
#endif
return 0;
}
Output: It will print current system date.
Explanation: __DATE__ is global identifier. It has already defined in the header
file stdio.h and it keeps the current system date.
#ifndef directive
Directive #ifndef is just opposite to the directive #ifdef . In this case if identifier has
not defined then #ifndef is true and if identifier has defined then #ifndef condition will
false.
Syntax :
#ifndef <Identifier>
--------------------------#else
--------------------------#endif
#include<stdio.h>

ASHOKA RAO
THUMUCHERLA

C-language
#define int A
int main(){
char num = int;
#ifndef int
printf("Please define int");
#else
printf("%d",int);
#endif
return 0;
}
Output: 65
Explanation: Macro constant int has been defined so #else directive will execute.
Its intermediate file will look like:
int main(){
char num = A;
printf("%d",A);
return 0;
}
ASCII value of A is 65.
#include<stdio.h>
#define I 30
int main(){
#ifndef __TIME__
printf("%d",I);
#else
printf("%s",__TIME__);
#endif
return 0;
}
Output: It will print current system time.
Explanation: __TIME__ is global identifier. It has been defined in the header file stdio.h.
Compiler doesnt compile the c codes which are inside the any conditional preprocessor
directive if its condition is false. So we can write anything inside it.
Its intermediate file will look like:
int main()
{
printf("%s",__TIME__);
return 0;

ASHOKA RAO
THUMUCHERLA

C-language
}

#undef directive:
Directive #undef is used to un define any macro constants except global identifiers.
It is useful when we want to redefined any macro constants.
#include<stdio.h>
#define ABC 25
#ifdef ABC
#undef ABC
#define ABC 50
#else
#define ABC 100
#endif
int main(){
printf("%d",ABC);
return 0;
}
Output: 50
Explanation: Since macro constant ABC has already defined. So #ifdef condition is true.
Directive #undef will undefined the macro constant ABC but #define will again define.
# error directive:
Syntax :
#error
If compiler compiles this line then it shows a compiler fatal error i.e it only issue an error
message and this error message includes . i.e it only issue an error message and this error
message includes .
#include<stdio.h>
#ifndef __MATH_H
#error First include then compile
#else
int main(){
float a,b=25;
a=sqrt(b);
printf("%f",a);
return 0;
}
#endif
Output: compiler error --> Error directive :First include then compile

ASHOKA RAO
THUMUCHERLA

C-language

#line directive:
A preprocessor line control directive supplies line numbers for compiler messages. It
causes the compiler to view the line number of the next source line as the specified
number.
You can use #line control directives to make the compiler provide more meaningful error
messages. The following example program uses #line control directives to give each
function an easily recognizable line number:
Example:
#include <stdio.h>
#define LINE200 200
void func_1(void);
void func_2(void);
int main()
{
func_1();
func_2();
return 0;
}
#line 100
void func_1()
{
printf("Func_1 - the current line number is %d\n",__LINE__);
}
#line LINE200
void func_2()
{
printf("Func_2 - the current line number is %d\n",__LINE__);
}
#pragma directive
Pragma having many forms in C-language
#pragma startup and #pragma exit
By which we can set the priorities to the
functions those we defined in our application.
#pragma startup [priority]
#pragma exit [priority]

Where priority is optional integral number.

ASHOKA RAO
THUMUCHERLA

C-language

For user-defined functions priority varies from 64 to 255


For c libraries functions priority varies from 0 to 63
Default priority is 100.
pragma startup always execute the function before the main function.
pragma exit always execute the function after the main function.
Function that having priority should not take any arguments and
should not return any value.
If more than one startup directive then priority decides which will
execute first.

startup:
Lower value: higher priority
exit:
Higher value: higher priority
void india();
void usa() ;
#pragma startup india 105
#pragma startup usa
#pragma exit usa
#pragma exit india 105
void main(){
printf("\nI am in main");
getch();
}
void india(){
printf("\nI am in india");
getch();
}
void usa(){
printf("\nI am in usa");
getch();
}

ASHOKA RAO
THUMUCHERLA

C-language

Storage classes
To fully define a variable one needs to mention not only its type, but also its storage class.
Every variable has a storage class, if we dont specify any storage class of a variable in its
declaration, the compiler will assume a storage class depending on the context in which
the variable is used.
Functions of storage class:

Where the variable would be stored?


What will be the initial value of a variable, if the
initial value is not specifically assigned?
What is the scope of the variable?
What is the life of the variable?

Scope: The scope of a variable determines over what part(s) of the program a variable is
actually available for use (active).

Block scope
Function scope
File scope
Program scope

Block Scope:
In this section, a block refers to any sets of statements enclosed in braces ({ and }).
A variable declared within a block has block scope. Thus, the variable is active and
accessible from its declaration point to the end of the block. Sometimes, block scope is
also called local scope.
For example, the variable i declared within the block of the following main function has
block scope:
int main()
{
int i; /* block scope */
.
.
.
return 0;
}
Note: Usually, a variable with block scope is called a local variable.
Nested Block Scope:
You can also declare variables within a nested block. If a variable declared in the
outer block shares the same name with one of the variables in the inner block, the

ASHOKA RAO
THUMUCHERLA

C-language
variable within the outer block is hidden by the one within the inner block for the scope of
the inner block.
#include <stdio.h>
main()
{
int i = 32;
printf("Within the outer block: i=%d\n", i);
{
int i, j;
//dont declare and check the output once.
printf("Within the inner block:\n");
for (i=0, j=10; i<=10; i++, j--)
printf("i=%2d, j=%2d\n", i, j);
}
printf("Within the outer block: i=%d\n", i);
return 0;
}
Function Scope:
Function scope indicates that a variable is active and visible from the beginning to
the end of a function. In C, only the goto label has function scope. For example, the goto
label, start, shown in the following code portion has function scope:
int main()
{
int i; /* block scope */
.
.
.
start: /* A goto label has function scope */
.
.
.
goto start; /* the goto statement */
.
.
return 0;
}
Here the label start is visible from the beginning to the end of the main() function.
Therefore, there should not be more than one label having the same name within the
main() function.
Program Scope:
A variable is said to have program scope when it is declared outside a function. For
instance, look at the following code:

ASHOKA RAO
THUMUCHERLA

C-language

int x = 0;
/* program scope */
float y = 0.0; /* program scope */
int main()
{
int i; /* block scope */
.
.
.
return 0;
}

Here the int variable x and the float variable y have program scope.
Variables with program scope are also called global variables, which are visible
among different files. These files are the entire source files that make up an
executable program. Note that a global variable is declared with an initialize outside
a function.

File Scope
In C, a global variable declared with the static specifier is said to have file scope. A
variable with file scope is visible from its declaration point to the end of the file. Here the
file refers to the program file that contains the source code. Most large programs consist of
several program files.
int x = 0;
/* program scope */
static int y = 0;
/* file scope */
static float z = 0.0; /* file scope */
int main()
{
int i; /* block scope */
.
.
.
return 0;
}
Here the int variable y and the float variable z both have file scope.
Types of Storage Classes :
Storage classes are categorised in 4 (four) types as,
Automatic Storage Class
Register Storage Class
Static Storage Class
External Storage Class

ASHOKA RAO
THUMUCHERLA

C-language

Automatic Storage Class:


Keyword : auto
Storage Location : Main memory(RAM)
Initial Value : Garbage Value
Life : Control remains in a block where it is defined.
Scope : Local to the block in which variable is declared.
Syntax :
auto [data_type] [variable_name];
Example :
auto int a;
#include <stdio.h>
#include <conio.h>
void main()
{
auto int i=10;
clrscr();
{
auto int i=20;
printf("\n\t %d",i);
}
printf("\n\n\t %d",i);
getch();
}
NOTE:
Any variable local to main will normally live throughout the whole program,
although it is active only in main.
In case local variable and global variable have the same name, the local variable
will have precedence over the global one.
Once a variable has been declared global any function can use it and change its
value. The subsequent functions can then reference only that new value.
Register Storage Class:
The storage of this type of variable is in the CPU registers.
It has a garbage value initially.
The scope of the variable is local to the block in which the variable is defined.
Each computer has a certain number of registers to hold data and perform
arithmetic or logical calculations.

ASHOKA RAO
THUMUCHERLA

C-language

Because registers are located within the CPU (central processing unit) chip, it's
much quicker to access a register than a memory location.
Therefore, storing variables in registers may help to speed up your program.
Therefore, if a variable is used at many places in a program, it is better to declare
its storage class as register.
It's illegal to take the address of a variable that is declared with the register
specifier because the variable is intended to be stored in a register, not in the
memory.
A good example of frequently used variable is loop counters.

Keyword : register
Storage Location : CPU Register
Initial Value : Garbage
Life : Local to the block in which variable is declared.
Scope : Local to the block.
Syntax :
register [data_type] [variable_name];
Example :
register int a;
#include <stdio.h>
#include <conio.h>
void main()
{
register int i=10;
clrscr();
{
register int i=20;
printf("\n\t %d",i);
}
printf("\n\n\t %d",i);
getch();
}

Static Storage Class:


Keyword : static
Storage Location : Main memory
Initial Value : Zero and can be initialize once only.
Life : within the file.
Scope : Local to the block(if you declare locally).

ASHOKA RAO
THUMUCHERLA

C-language
Syntax :
static [data_type] [variable_name];
Example :
static int a;
NOTE: The value will not disappear once the function in which it has been declared
becomes inactive. It is unavailable only when you come out of the program.
#include <stdio.h>
void increment(void);
void main()
{
int i;
for (i=0;i<3;i++)
{
increment();
}
}
void increment(void)
{
int avar=1;
static int svar=1;
avar++;
svar++;
printf("Automatic variable value : %d\n",avar);
printf("Static variable value : %d\n\n",svar);
}

#include<stdio.h>
void main()
{
value();
value();
value();
}
void value()
{
static int a=5;
a=a+2;
printf("%d\n",a);
}
External Storage Class:

ASHOKA RAO
THUMUCHERLA

C-language
As stated in the section titled "Program Scope", a variable with program scope is
visible through all source files that make up an executable program. A variable with
program scope is also called a global variable.
Keyword : extern
Storage Location : Main memory
Initial Value : Zero
Life : Until the program ends.
Scope : Global to the program.
Syntax :
extern [data_type] [variable_name];
Example :
extern int a;
The variables of this class can be referred to as 'global or external variables.' They are
declared outside the functions and can be invoked at anywhere in a program.
#include <stdio.h>
#include <conio.h>
extern int i=10;
void main()
{
int i=20;
void show(void);
clrscr();
printf("\n\t %d",i);
show();
getch();
}
void show(void)
{
printf("\n\n\t %d",i);
}
Use of extern with C functions:
By default, the declaration and definition of a C function have extern prepended
with them.
It means even though we dont use extern with the declaration/definition of C
functions, it is present there. For example, when we write.
int func(int arg1, char arg2);
Theres an extern present in the beginning which is hidden and the compiler treats
it as below.
extern int func(int arg1, char arg2);
Same is the case with the definition of a C function (Definition of a C function means
writing the body of the function).

ASHOKA RAO
THUMUCHERLA

C-language

Therefore whenever we define a C function, an extern is present there in the


beginning of the function definition.
Since the declaration can be done any number of times and definition can be done
only once, we can notice that declaration of a function can be added in several C/H
files or in a single C/H file several times.
But we notice the actual definition of the function only once (i.e. in one file only).
And as the extern extends the visibility to the whole program, the functions can be
used (called) anywhere in any of the files of the whole program provided the
declaration of the function is known. (By knowing the declaration of the function, C
compiler knows that the definition of the function exists and it goes ahead to
compile the program).

use of extern with C variables:


how would you declare a C variable without defining it?
extern int var;
Here, an integer type variable called var has been declared (remember no definition
i.e. no memory allocation for var so far). And we can do this declaration as many
times as needed. (remember that declaration can be done any number of times) So
far so good.
Now how would you define a variable. Now I agree that it is the most trivial question
in programming and the answer is as follows.
int var;
Here, an integer type variable called var has been declared as well as defined.
(remember that definition is the super set of declaration).
Here the memory for var is also allocated.
Now here comes the surprise, when we declared/defined a C function, we saw that
an extern was present by default.
While defining a function, we can prepend it with extern without any issues. But it is
not the case with C variables.
If we put the presence of extern in variable as default then the memory for them
will not be allocated ever, they will be declared only. Therefore, we put extern
explicitly for C variables when we want to declare them without defining them.
Also, as the extern extends the visibility to the whole program, by externing a
variable we can use the variables anywhere in the program provided we know the
declaration of them and the variable is defined somewhere.
Now let us try to understand extern with examples.
Example 1:

ASHOKA RAO
THUMUCHERLA

C-language

#include<stdio.h>
int var;
int main(void)
{
var = 10;
printf("%d\n",var);
return 0;
}
Analysis: This program is compiled successfully. Here var is defined (and declared
implicitly) globally.
Example 2:
extern int var;
int main(void)
{
return 0;
}
Analysis: This program is compiled successfully. Here var is declared only. Notice var is
never used so no problems.
Example 3:
extern int var;
int main(void)
{
var = 10;
return 0;
}
Analysis: This program throws error at runtime. Because var is declared but not defined
anywhere. Essentially, the var isnt allocated any memory. And the program is trying to
change the value to 10 of a variable that doesnt exist at all.
Example 4:
#include "somefile.h"
extern int var;
int main(void)
{
var = 10;
return 0;
}
Analysis: Supposing that somefile.h has the definition of var. This program will be
compiled successfully.
Example 5:
extern int var = 0;
int main(void)
{
var = 10;

ASHOKA RAO
THUMUCHERLA

C-language
return 0;
}
Analysis: Guess this program will work? Well, here comes another surprise from C
standards. They say that..if a variable is only declared and an initializer is also provided
with that declaration, then the memory for that variable will be allocated i.e. that variable
will be considered as defined. Therefore, as per the C standard, this program will compile
successfully and work.
#include <stdio.h>
void func1(void);
extern int y;
int main()
{
int y=5;
return 0;
}
void func1()
{
y=y+1;
}
The Storage Class Modifiers
Besides the four storage class specifiers introduced in the previous sections, C also
provides you with two storage class modifiers (or qualifiers, as they're sometimes called)
that you can use to indicate to the C compiler how variables may be accessed.
The const Modifier
If you declare a variable with the const modifier, the content of the variable cannot
be changed after it is initialized.
For instance, the following expression indicates to the compiler that circle_ratio is a
variable whose value should not be changed:
const double circle_ratio = 3.141593;
Likewise, the value of the character array str declared in the following statement
cannot be changed, either:
const char str[] = "A string constant";
Therefore, it's illegal to do something like this:
str[0] = `a'; /* It's not allowed here. */
In addition, you can declare a pointer variable with the const modifier so that an
object pointed to by the pointer cannot be changed. For example, consider the
following pointer declaration with the const modifier:
char const *ptr_str = "A string constant";
After the initialization, you cannot change the content of the string pointed to by the
pointer ptr_str. For instance, the following statement is not allowed:
*ptr_str = `a';
/* It's not allowed here. */
Scope:

ASHOKA RAO
THUMUCHERLA

C-language
Storage class

How it has
declared

Scope

Visibility

Auto

Block

Block

Register

Globally
Locally
Globally

Static

Locally
Globally

Block
Program

Block
File

extern

Locally
Globally

Program
Program

Block
Program

Locally

Program

block

Interview codes:
Code1:
Void main(){
value();
value ();
value();
getch();
}
value()
{
static int a=5;
a=a+2;
printf("\n%d",a);
}
Code2:
Void main()
{
auto int a=2;
{
auto int b=3;
printf("%d %d",a,b);
}
printf("%d",a);
}
Here the out put is 2 3 2.Here
Code3:
main()
{
auto int a=2;
{

ASHOKA RAO
THUMUCHERLA

C-language
auto int b=3;
printf("%d %d",a,b);
}
printf("%d %d",a,b); // compiler error
}
code4:
main()
{
auto int a=2;
{
auto int a=3;
printf("%d ",a);
}
printf("%d",a);
}
code5:
void main(){
register a,b,sum;
scanf(%d%d,&a,&b);
sum=a+b;
printf(%d,sum);
}
Code6:
void main(){
extern int i;
printf(%d,i);
}
int i=6;
code7:
int main()
{
int y=128;
const int x=y;
printf("%d\n", x);
return 0;
}
Code8:
int main()
{
const int x=5;
const int *ptrx;
ptrx = &x;

ASHOKA RAO
THUMUCHERLA

C-language
*ptrx = 10;
printf("%d\n", x);
return 0;
}
Code9:
int main()
{
const char *s = "";
char str[] = "Hello";
s = str;
while(*s)
printf("%c", *s++);
return 0;
}
Code10:
int get(void);
int main()
{
const int x = get();
printf("%d", x);
return 0;
}
int get()
{
return 20;
}
Code11:
#include <stdio.h>
int i; //By default it is extern variable
int main(){
printf("%d",i);
return 0;
}
Code12:
#include <stdio.h>
extern int i; //extern variable
int main(){
printf("%d",i);
return 0;
}
Code13:
#include <stdio.h>

ASHOKA RAO
THUMUCHERLA

C-language
void sum(int,int) //By default it is extern.
int main(){
int a=5,b=10;
sum(a,b);
return 0;
}
void sum(int a,int b){
printf("%d",a+b);
}
Code14:
#include <stdio.h>
char c;
int i;
float f;
char *str;
int main(){
printf("%d %d %f %s",c,i,f,str);
return 0;
}
Code15:
#include <stdio.h>
int main(){
extern int i=10; //Try to initialize extern variable
//locally.
printf("%d",i);
return 0;
}
Output: Compilation error: Cannot initialize extern variable.
Code16:
#include <stdio.h>
int main(){
extern int i; //Declaration of extern variable i.
int i=10;
//Try to locally initialization of
//extern variable i.
printf("%d",i);
return 0;
}
Code17:
#include <stdio.h>
int main(){
extern int i; //It will search the initialization of
//variable i.
printf("%d",i);
return 0;

ASHOKA RAO
THUMUCHERLA

C-language
}
int i=20;

//Initialization of variable i.

code18:
#include <stdio.h>
int main(){
extern int i; //It will search the any initialized
//variable i which may be static or
//extern.
printf("%d",i);
return 0;
}
extern int i=20; //Initialization of extern variable i.
code19:
#include <stdio.h>
int main(){
extern int i; //It will search the any initialized
//variable i which may be static or
//extern.
printf("%d",i);
return 0;
}
static int i=20; //Initialization of static variable i.
code20:
extern int i; //Declaring the variable i.
int i=25;
//Initializing the variable.
extern int i; //Again declaring the variable i.
#include <stdio.h>
int main(){
extern int i; //Again declaring the variable i.
printf("%d",i);
return 0;
}
Code21:
extern int i; //Declaring the variable
int i=25;
//Initializing the variable
#include <stdio.h>
int main(){
printf("%d",i);
return 0;
}
int i=20; //Initializing the variable
code22:

ASHOKA RAO
THUMUCHERLA

C-language
#include <stdio.h>
extern int i;
int i=10; //Initialization statement
i=25;
//Assignment statement
int main(){
printf("%d",i);
return 0;
}
Output: Compilation error
Note: Assigning any value to the variable at the time of declaration is known as
initialization while assigning any value to variable not at the time of declaration is known
assignment.
Code23:
#include <stdio.h>
extern int i;
int main(){
i=25;
//Assignment statement
printf("%d",i);
return 0;
}
int i=10; //Initialization statement
code24:
#include<stdio.h>
int a;
int main(){
printf("%d",a);
return 0;
}
Code25:
#include<stdio.h>
static int a;
int main(){
printf("%d",a);
return 0;
}
Code26:
#include <stdio.h>
static char c;
static int i;
static float f;
static char *str;
int main(){
printf("%d %d %f %s",c,i,f,str);
return 0;

ASHOKA RAO
THUMUCHERLA

C-language
}
Code27:
#include <stdio.h>
static int i;
//Declaring the variable i.
static int i=25;
//Initializing the variable.
static int i;
//Again declaring the variable i.
int main(){
static int i; //Again declaring the variable i.
printf("%d",i);
return 0;
}
Code28:
#include <stdio.h>
static int i;
//Declaring the variable
static int i=25;
//Initializing the variable
int main(){
printf("%d",i);
return 0;
}
static int i=20;
//Again initializing the variable
code29:
#include <stdio.h>
static int i=10; //Initialization statement
i=25;
//Assignment statement
int main(){
printf("%d",i);
return 0;
}
Code30:
#include <stdio.h>
static int i=10;
int main(){
i=5;
for(i=0;i<5;i++){
static int a=10; //This statement will execute
//only time.
printf("%d",a++);//This statement will execute
//five times.
}
return 0;
}
Code31:
#include<stdio.h>

ASHOKA RAO
THUMUCHERLA

C-language
int main(){
{
static int a=5;
printf("%d",a);
}
//printf("%d",a); variable a is not visible here.
return 0;
}
Code32:
Int main()
{
Register int a=10;
Int *p;
P=&a;
Printf(%u,p);
}
CE: we cannot dereference register variable since it has no memory address.
Note: if any variable declared as static variable or function globally then its visibility
willobly the file in which it has declared not in the other files.
One.c:
#include"two.c"
static int i=10;
static int j=20;
void main()
{
sum();
}
Two.c:
static int i;
static int j;
static void sum()
{
int a;
a=i+j;
printf("%d\n",a);
}

ASHOKA RAO
THUMUCHERLA

C-language

Command line arguments

In C it is possible to accept command line arguments. Command-line arguments are


given after the name of a program in command-line operating systems like DOS or
Linux, and are passed in to the program from the operating system.
To use command line arguments in your program, you must first understand the full
declaration of the main function, which previously has accepted no arguments.
In fact, main can actually accept two arguments: one argument is number of
command line arguments, and the other argument is a full list of all of the command
line arguments.

The full declaration of main looks like this:


int main ( int argc, char *argv[] )

The integer, argc is the argument count. It is the number of arguments passed
into the program from the command line, including the name of the program.
argv is array of character pointers is the listing of all the arguments.
argv[0] is the name of the program, or an empty string if the name is not available.
After that, every element number less than argc is a command line argument..
argv[argc] is a null pointer.

#include<stdio.h>
void main(int argc,char *argv[])
{
if(argc==2)
printf("the argument supplied is %s\n",argv[1]);
else if(argc>2)
printf("too many argumentssupplied.\n");
else
printf("one argument expected");
}
What will be the output of the program (myprog.c) given below if it is executed from the
command line?
cmd> myprog one two three
/* myprog.c */
#include<stdio.h>
int main(int argc, char **argv)
{
printf("%c\n", **++argv);
return 0;
}
O

ASHOKA RAO
THUMUCHERLA

C-language

What will be the output of the program (myprog.c) given below if it is executed from the
command line?
cmd> myprog one two three
/* myprog.c */
#include<stdio.h>
#include<stdlib.h>
int main(int argc, char **argv)
{
printf("%s\n", *++argv);
return 0;
}
ONE
What will be the output of the program (sample.c) given below if it is executed from the
command line (turbo c under DOS)?
cmd> sample Good Morning
/* sample.c */
#include<stdio.h>
int main(int argc, char *argv[])
{
printf("%d %s", argc, argv[1]);
return 0;
}
3 GOOD
What will be the output of the program
#include<stdio.h>
void fun(int);
int main(int argc)
{
printf("%d\n", argc);
fun(argc);
return 0;
}
void fun(int i)
{
if(i!=4)
main(++i);
}
1 234
What will be the output of the program (sample.c) given below if it is executed from the
command line?
cmd> sample "*.c"
/* sample.c */
#include<stdio.h>

ASHOKA RAO
THUMUCHERLA

C-language
int main(int argc, int *argv[])
{
int i;
for(i=1; i<argc; i++)
printf("%s\n", argv[i]);
return 0;
}
D. List of all files and folders in the current directory
What will be the output of the program if it is executed like below?
cmd> sample
/* sample.c */
#include<stdio.h>
int main(int argc, char **argv)
{
printf("%s\n", argv[argc-1]);
return 0;
}
SAMPLE
8. What will be the output of the program (sample.c) given below if it is executed from the
command line?
cmd> sample friday tuesday sunday
/* sample.c */
#include<stdio.h>
int main(int argc, char *argv[])
{
printf("%c", **++argv);
return 0;
}
FRIDAY
#include<stdio.h>
#include<stdlib.h>
int main(int argc, char *argv[])
{
int a,b,c;
a=atoi(argv[1]);
b=atoi(argv[2]);
c=a+b;
printf("sum=%d\n",c);
return 0;
}

ASHOKA RAO
THUMUCHERLA

C-language

typedef
Introduction:

A typedef declaration lets you define your own identifiers that can be used in place
of type specifiers such as int, float, and double.
A typedef declaration does not reserve storage.
The names you define using typedef are not new data types, but synonyms for the
data types or combinations of data types they represent.

The following statements define LENGTH as a synonym for int and then use this typedef to
declare length, width, and height as integer variables:
typedef int LENGTH;
LENGTH length, width, height;
The following declarations are equivalent to the above declaration:
int length, width, height;
Some more examples
typedef int aaa, bbb, ccc;
typedef int ar[15], arr[9][6];
typedef char c, *cp, carr[100];
/* now declare some objects */
/* all ints */
aaa
int1;
bbb
int2;
ccc
int3;
ar
arr

yyy;
xxx;

/* array of 15 ints */
/* 9*6 array of int */

c
ch;
/* a char */
cp
pnt; /* pointer to char */
carr chry; /* array of 100 char */
Similarly, typedef can be used to define a structure, union, or C++ class. For example:
typedef struct {
int scruples;
int drams;
int grains;
} WEIGHT;
The structure WEIGHT can then be used in the following declarations:
WEIGHT chicken, cow, horse, whale;

ASHOKA RAO
THUMUCHERLA

C-language
Similarly, the declaration
typedef char *String;
makes String a synonym for char * or character pointer, which may then be used in
declarations and casts:
String p, lineptr[MAXLINES], alloc(int);
int strcmp(String, String);
p = (String) malloc(100);
Note: That the type being declared in a typedef appears in the position of a variable
name, not right after the word typedef. Syntactically, typedef is like the storage
classes extern, static, etc.
As a more complicated example, we could make typedefs for the tree nodes shown earlier
in this chapter:
typedef struct tnode *Treeptr;
typedef struct tnode { /* the tree node: */
char *word;
/* points to the text */
int count;
/* number of occurrences */
struct tnode *left; /* left child */
struct tnode *right; /* right child */
} Treenode;
This creates two new type keywords called Treenode (a structure) and Treeptr (a pointer to
the structure). Then the routine talloc could become
Treeptr talloc(void){
return (Treeptr) malloc(sizeof(Treenode));
}

It must be emphasized that a typedef declaration does not create a new type in any
sense; it merely adds a new name for some existing type.
In effect, typedef is like #define, except that since it is interpreted by the compiler,
it can cope with textual substitutions that are beyond the capabilities of the
preprocessor. For example,
typedef int (*PFI)(char *, char *);
creates the type PFI, for ``pointer to function (of two char * arguments) returning
int,'' which can be used in contexts like
PFI strcmp, numcmp;
Code1:
#include<stdio.h>
int main()
{
typedef int arr[5];
arr iarr = {1, 2, 3, 4, 5};
int i;
for(i=0; i<4; i++)
printf("%d,", iarr[i]);

ASHOKA RAO
THUMUCHERLA

C-language
return 0;
}
Code2:
#include<stdio.h>
int main()
{
typedef int LONG;
LONG a=4;
LONG b=68;
float c=0;
c=b;
b+=a;
printf("%d,", b);
printf("%f\n", c);
return 0;
}
Code3:
#include<stdio.h>
int main()
{
typedef float f;
static f *fptr;
float fval = 90;
fptr = &fval;
printf("%f\n", *fptr);
return 0;
}

Code4:
#include<stdio.h>
typedef struct error {int warning, err, exception;} ERROR;
int main()
{
ERROR e;
e.err=1;
printf("%d\n", e.err);
return 0;
}
#include<stdio.h>
typedef char* String;

ASHOKA RAO
THUMUCHERLA

C-language
String read(void);
int main()
{
String s;
s=read();
puts(s);
return 0;
}
String read()
{
return "amar";
}

Enumeration
Introduction:

An enumeration consists of a set of named integer constants.


An enumeration type declaration gives the name of the (optional) enumeration tag
and defines the set of named integer identifiers (called the "enumeration set,"
"enumerator constants," "enumerators," or "members").
A variable with enumeration type stores one of the values of the enumeration set
defined by that type.
An enumeration constant or a value of enumerated type can be used anywhere the
C language permits an integer expression.

syntax:
enum identifier { enumerator-list }

Each enumeration-constant in an enumeration-list names a value of the


enumeration set. By default, the first enumeration-constant is associated with the
value 0. The next enumeration-constant in the list is associated with the value of
( constant-expression + 1 ), unless you explicitly associate it with another value.
The name of an enumeration-constant is equivalent to its value.

You can use enumeration-constant = constant-expression to override the default


sequence of values. Thus, if enumeration-constant = constant-expression appears
in the enumerator-list, the enumeration-constant is associated with the value given
by constant-expression. The constant-expression must have int type and
can be negative.

The following rules apply to the members of an enumeration set:

ASHOKA RAO
THUMUCHERLA

C-language

An enumeration set can contain duplicate constant values. For example, you could
associate the value 0 with two different identifiers, perhaps named null and zero, in
the same set.
The identifiers in the enumeration list must be distinct from other identifiers in the
same scope with the same visibility, including ordinary variable names and
identifiers in other enumeration lists.
Enumeration tags obey the normal scoping rules. They must be distinct from other
enumeration, structure, and union tags with the same visibility.

Code1:
#include <stdio.h>
int main()
{
enum {WIN=0, TIE=1, BYE=1, LOSE=0, NO_SHOW=0} result;
enum {SUN, MON, TUE, WED, THU, FRI, SAT} days;
result = WIN;
printf(" WIN = %d\n", result);
result = LOSE;
printf(" LOSE = %d\n", result);
result = TIE;
printf(" TIE = %d\n", result);
result = BYE;
printf(" BYE = %d\n", result);
result = NO_SHOW;
printf("NO_SHOW = %d\n\n", result);
for(days = MON ; days < FRI ; days++)
printf("The day code is %d\n", days);
return 0;
}
Code2:
#include<stdio.h>
int main()
{
enum Day {Sunday,Monday,Tuesday,Wednesday,Thursday,Friday,Saturday};
enum Day today;
int x;
printf("please enter the day of the week(0 to 6)\n");
scanf("%d",&x);
today=x;
if(today==Sunday || today==Saturday)
printf("Enjoy! Its the weekend\n");

ASHOKA RAO
THUMUCHERLA

C-language
else
printf("Week day.do your work\n");
return 0;
}
Code3:
#include<stdio.h>
int main()
{
enum months {Jan=1,Feb,Mar,Apr,May,Jun,Jul,Aug,Sep,Oct,Nov,Dec};
enum months month;
printf("month=%d\n",month=Feb);//Assign integer value
return 0;
}

PROCESS MEMORY LAYOUT

A running program is called a process and when a program is run, its executable
image is loaded into memory area that normally called a process address space in
an organized manner.
This is a physical memory space and do not confuse yourself with the virtual
address space explained in Module W.
Process address space is organized into three memory areas, called segments: the
text segment, stack segment, and data segment (bss and data) and can be
illustrated below.

ASHOKA RAO
THUMUCHERLA

C-language

The text segment (also called a code segment) is where the compiled code of the program
itself resides.

In the disk file (object files) the segments were called sections.
By using a C program, the segments can be illustrated below.

ASHOKA RAO
THUMUCHERLA

C-language

In C language memory allocation through the variables in C programs is supported


by two kinds of memory allocation as listed in the following Table.
Memory
Allocation
Type

Description

Static
allocation

This allocation happens when you declare a static or


global variable. Each static or global variable defines
one block of space, of a fixed size. The space is
allocated once, when your program is started, and is
never freed. In memory address space, for
uninitialized variables are stored in bss segment
while an initialized variables stored in data segment.

Automatic
allocation

This allocation happens when you declare an automatic


variable, such as a function argument or a local variable. The
space for an automatic variable is allocated when the
compound statement containing the declaration is entered,
and is freed when that compound statement is exited. As
discussed before this allocation done in the stack segment.

ASHOKA RAO
THUMUCHERLA

C-language

GRAPHICS

Graphics allows the c-programmer to draw shapes, to set the colors to text,
to window and allowed to write game programming.
Firstly you should know the function initgraph which is used to initialize the
graphics mode . To initialize graphics mode we use initgraph function in our
program.
initgraph function is present in "graphics.h" header file, so your every
graphics program should include "graphics.h" header file.

#include<graphics.h>
#include<conio.h>
int main()
{
int gd = DETECT, gm;
initgraph(&gd, &gm, "C:\\TC\\BGI");
getch();
closegraph();
return 0;
}

This program initializes graphics mode and then closes it after a key is
pressed.
To begin with we have declared two variables of int type gd and gm for
graphics driver and graphics mode respectively, you can choose any other
variable name as you wish.
DETECT is a macro defined in "graphics.h" header file, then we have passed
three arguments to initgraph function first one is the address of gd, second is
the address of gm and third is the path where your library files are present
( you have to adjust this accordingly where you turbo compiler is installed).
Initgraph function automatically decides an appropriate graphics driver and
mode such that maximum screen resolution is set.
getch() helps us to wait until a key is pressed, closegraph function closes the
graphics mode and finally return statement returns a value 0 to main
indicating successful execution of your program.
After you have understood initgraph function then you can use functions to
draw shapes such as circle, line , rectangle etc, then you can learn how to
change colors and fonts using suitable functions, then you can go for
functions such as getimage, putimage etc for doing animation.

ASHOKA RAO
THUMUCHERLA

C-language
Program code to display arc:

void arc(int x, int y, int stangle, int endangle, int radius);

arc function is used to draw an arc with center (x,y) and stangle specifies starting angle,
endangle specifies the end angle and last parameter specifies the radius of the arc. arc
function can also be used to draw a circle but for that starting angle and end angle should
be 0 and 360 respectively.
#include <graphics.h>
#include <conio.h>
main()
{
int gd = DETECT, gm;
initgraph(&gd, &gm, "");
arc(100, 100, 0, 90, 90);
getch();
closegraph();
return 0;
}

Program code to display bar:

void bar(int left, int top, int right, int bottom);


Bar function is used to draw a 2-dimensional, rectangular filled in bar . Coordinates of left
top and right bottom corner are required to draw the bar. Left specifies the X-coordinate of
top left corner, top specifies the Y-coordinate of top left corner, right specifies the Xcoordinate of right bottom corner, bottom specifies the Y-coordinate of right bottom corner.
Current fill pattern and fill color is used to fill the bar. To change fill pattern and fill color
use setfillstyle.
#include <graphics.h>
#include <conio.h>
main()
{
int gd = DETECT, gm;
initgraph(&gd, &gm, "");
bar(100, 100, 120, 400);
getch();
closegraph();
return 0;
}

C program for circle

void circle(int x, int y, int radius);


Circle function is used to draw a circle with center (x,y) and third parameter specifies the
radius of the circle. The code given below draws a circle.
#include<graphics.h>
#include<conio.h>
main()
{

ASHOKA RAO
THUMUCHERLA

C-language
int gd = DETECT, gm;
initgraph(&gd, &gm, "C:\\TC\\BGI");
circle(100, 100, 50);
getch();
closegraph();
return 0;
}

void cleardevice();

cleardevice function clears the screen in graphics mode and sets the current
position to (0,0). Clearing the screen consists of filling the screen with current background
color.
#include <graphics.h>
#include <conio.h>
main()
{
int gd = DETECT, gm;
initgraph(&gd, &gm, "C:\\TC\\BGI");
outtext("Press any key to clear the screen.");
getch();
cleardevice();
outtext("Press any key to exit...");
getch();
closegraph();
return 0;
}

void closegraph();
closegraph function closes the graphics mode, deallocates all memory allocated by
graphics system and restores the screen to the mode it was in before you called initgraph.
#include<graphics.h>
#include<conio.h>
main()
{
int gd = DETECT, gm;
initgraph(&gd, &gm, "C:\\TC\\BGI");
outtext("Press any key to close the graphics mode...");
getch();
closegraph();
return 0;
}

void drawpoly( int num, int *polypoints );

Drawpoly function is used to draw polygons i.e. triangle, rectangle, pentagon,


hexagon etc.

ASHOKA RAO
THUMUCHERLA

C-language

num indicates (n+1) number of points where n is the number of vertices in a


polygon,
polypoints points to a sequence of (n*2) integers .
Each pair of integers gives x and y coordinates of a point on the polygon.
We specify (n+1) points as first point coordinates should be equal to (n+1)th to
draw a complete figure.
To understand more clearly we will draw a triangle using drawpoly, consider for
example the array :int points[] = { 320, 150, 420, 300, 250, 300, 320, 150};
points array contains coordinates of triangle which are (320, 150), (420, 300) and
(250, 300). Note that last point(320, 150) in array is same as first. See the program
below and then its output, it will further clear your understanding.

#include <graphics.h>
#include <conio.h>
main()
{
int gd=DETECT,gm,points[]={320,150,420,300,250,300,320,150};
initgraph(&gd, &gm, "C:\\TC\\BGI");
drawpoly(4, points);
getch();
closegraph();
return 0;
}

Declaration of fillellipse function :void fillellipse(int x, int y, int xradius, int yradius);
x and y are coordinates of center of the ellipse, xradius and yradius are x and y radius of
ellipse respectively.
#include <graphics.h>
#include <conio.h>
int main()
{
int gd = DETECT, gm;
initgraph(&gd, &gm, "C:\\TC\\BGI");
fillellipse(100, 100, 50, 25);
getch();
closegraph();
return 0;
}

int getbkcolor();

getbkcolor function returns the current background color


e.g. color = getbkcolor(); // color is an int variable
if current background color is GREEN then color will be 2.

ASHOKA RAO
THUMUCHERLA

C-language
#include<graphics.h>
#include<conio.h>
main()
{
int gd = DETECT, gm, bkcolor;
char a[100];
initgraph(&gd,&gm,"C:\\TC\\BGI");
bkcolor = getbkcolor();
sprintf(a,"Current background color = %d", bkcolor);
outtextxy( 10, 10, a);
getch();
closegraph();
return 0;
}

int getmaxx();

getmaxx function returns the maximum X coordinate for current graphics mode and

driver.

int getmaxy();

getmaxy function returns the maximum Y coordinate for current graphics mode and

driver.
#include<graphics.h>
#include<conio.h>
main()
{
int gd = DETECT, gm, max_x,max_y;
char a1[100],a2[100];
initgraph(&gd,&gm,"");
max_x = getmaxx();
sprintf(a1, "Maximum X coordinate for current graphics mode and driver = %d.",max_x);
outtextxy(100,100,a1);
max_y = getmaxy();
sprintf(a2, "Maximum Y coordinate for current graphics mode and driver is =
%d.",max_y);
outtextxy(100,200,a2);
getch();
closegraph();
return 0;
}
void line(int x1, int y1, int x2, int y2);
line function is used to draw a line from a
point(x1,y1) to point(x2,y2) .
#include <graphics.h>
#include <conio.h>
main()
{

ASHOKA RAO
THUMUCHERLA

C-language
int gd = DETECT, gm;
initgraph(&gd, &gm, "C:\\TC\\BGI");
line(100, 100, 200, 200);
getch();
closegraph();
return 0;
}

void outtextxy(int x, int y, char *string);

outtextxy function display text or string at a specified point(x,y) on the screen.x, y


are coordinates of the point and third argument contains the address of string to be
displayed.
#include<graphics.h>
#include<conio.h>
main()
{
int gd = DETECT, gm;
initgraph(&gd,&gm,"C:\\TC\\BGI");
outtextxy(100, 100, "Outtextxy function");
getch();
closegraph();
return 0;
}

void setbkcolor(int color);

setbkcolor function changes current background color e.g. setbkcolor(YELLLOW)


changes the current background color to YELLOW. Remember that default drawing color is
WHITE and background color is BLACK.
#include<graphics.h>
#include<conio.h>
main()
{
int gd = DETECT, gm;
initgraph(&gd, &gm, "C:\\TC\\BGI");
outtext("Press any key to change the background color to GREEN.");
getch();
setbkcolor(GREEN);
getch();
closegraph();
return 0;
}

void setcolor(int color);

In Turbo Graphics each color is assigned a number. Total 16 colors are available.
Strictly speaking number of available colors depends on current graphics mode and driver.

ASHOKA RAO
THUMUCHERLA

C-language
For Example :- BLACK is assigned 0, RED is assigned 4 etc. setcolor function is used
to change the current drawing color.e.g. setcolor(RED) or setcolor(4) changes the current
drawing color to RED. Remember that default drawing color is WHITE.
#include<graphics.h>
#include<conio.h>
main()
{
int gd = DETECT, gm;
initgraph(&gd,&gm,"C:\\TC\\BGI");
circle(100,100,50);
/* drawn in white color */
setcolor(RED);
circle(200,200,50);
/* drawn in red color */
getch();
closegraph();
return 0;
}
#include<graphics.h>
#include<conio.h>
main()
{
int gd = DETECT, gm, bkcolor;
char a[100];
initgraph(&gd,&gm,"");
setbkcolor(CYAN);
setcolor(4);
bkcolor = getbkcolor();
sprintf(a,"Current background color = %d", bkcolor);
outtextxy( 50, 100, a);
outtextxy( 50,200,"press any key to change background color to RED...");
outtextxy( 50,300, "and foreground color to GREEN.......");
getch();
setbkcolor(RED);
cleardevice();
setcolor(2);
outtextxy(100,100,"background color changed to RED.....") ;
getch();
closegraph();
return 0;
}

#include<graphics.h>
#include<conio.h>
main()

ASHOKA RAO
THUMUCHERLA

C-language
{
int gd = DETECT, gm;
initgraph(&gd,&gm,"");
setcolor(2);
outtextxy(70,40,"white circle");
setcolor(15);
circle(100,100,50);
/* drawn in white color */
setcolor(2);
outtextxy(200,200,"red circle");
setcolor(RED);
circle(250,250,50);
/* drawn in red color */
getch();
closegraph();
return 0;
}
#include<graphics.h>
#include<conio.h>
main()
{
int gd = DETECT, gm,i,j,k=0;
initgraph(&gd,&gm,"");
setbkcolor(4);
for(i=100;i<=400;i=i+100)
{
for(j=100;j<=400;j=j+100)
{
setcolor(k);
circle(j,i,25);
k++;
}
}
getch();
closegraph();
return 0;
}

void setfillstyle( int pattern, int color);

setfillstyle function sets the current fill pattern and fill color.

ASHOKA RAO
THUMUCHERLA

C-language
enum fill_styles
{
EMPTY_FILL,
SOLID_FILL,
LINE_FILL,
LTSLASH_FILL,
SLASH_FILL,
BKSLASH_FILL,
LTBKSLASH_FILL,
HATCH_FILL,
XHATCH_FILL,
INTERLEAVE_FILL,
WIDE_DOT_FILL,
CLOSE_DOT_FILL,
USER_FILL
};
#include<graphics.h>
#include<conio.h>
main()
{
int gd = DETECT, gm;
initgraph(&gd, &gm, "C:\\TC\\BGI");
setfillstyle(XHATCH_FILL, RED);
circle(100, 100, 50);
floodfill(100, 100, WHITE);
getch();
closegraph();
return 0;
}
#include<graphics.h>
#include<conio.h>
main()
{
int gd = DETECT, gm;
initgraph(&gd, &gm, "C:\\TC\\BGI");
setfillstyle(1, RED); /*1 for solid fill according to enum set of filling styles*/
circle(100, 100, 50);
floodfill(100, 100, WHITE);
getch();
closegraph();
return 0;
}

void settextstyle( int font, int direction, int charsize);

Settextstyle function is used to change the way in which text appears, using it we
can modify the size of text, change direction of text and change the font of text.

ASHOKA RAO
THUMUCHERLA

C-language

font argument specifies the font of text, Direction can be HORIZ_DIR (Left to right) or
VERT_DIR (Bottom to top).
Different fonts
enum font_names
{
DEFAULT_FONT,
TRIPLEX_FONT,
SMALL_FONT,
SANS_SERIF_FONT,
GOTHIC_FONT,
SCRIPT_FONT,
SIMPLEX_FONT,
TRIPLEX_SCR_FONT,
COMPLEX_FONT,
EUROPEAN_FONT,
BOLD_FONT
};
#include <graphics.h>
#include <conio.h>
main()
{
int gd = DETECT, gm, x = 25, y = 25, font = 0;
initgraph(&gd,&gm,"C:\\TC\\BGI");
for (font = 0; font <= 10; font++)
{
settextstyle(font, HORIZ_DIR, 1);
outtextxy(x, y, "Text with different fonts");
y = y + 25;
}
getch();
closegraph();
return 0;
}

C program draw bar chart


#include <graphics.h>
#include <conio.h>
main()
{
int gd = DETECT, gm;
initgraph(&gd, &gm, "");
setcolor(YELLOW);
rectangle(50,100,500,440);

ASHOKA RAO
THUMUCHERLA

C-language

settextstyle(SANS_SERIF_FONT,HORIZ_DIR,3);
setcolor(WHITE);
outtextxy(200,50,"Bar Chart");
setlinestyle(SOLID_LINE,0,2);
line(90,120,90,420);
line(90,420,430,420);
outtextxy(80,110,"Y");
outtextxy(435,420,"X");
outtextxy(85,415,"O");
setfillstyle(LINE_FILL,BLUE);
bar(120,160,160,420);
setfillstyle(XHATCH_FILL,RED);
bar(200,250,240,420);
setfillstyle(WIDE_DOT_FILL,GREEN);
bar(280,120,320,420);
setfillstyle(INTERLEAVE_FILL,MAGENTA);
bar(360,200,400,420);
getch();
return 0;
}

traffic light program in c, traffic light simulation


#include<graphics.h>
#include<conio.h>
#include<dos.h>
#include<stdlib.h>
main()
{
int gd = DETECT, gm, midx, midy;
initgraph(&gd, &gm, "C:\\TC\\BGI");
midx = getmaxx()/2;
midy = getmaxy()/2;
setcolor(RED);
settextstyle(SCRIPT_FONT, HORIZ_DIR, 3);
settextjustify(CENTER_TEXT, CENTER_TEXT);
outtextxy(midx, midy-10, "Traffic Light Simulation");

ASHOKA RAO
THUMUCHERLA

C-language
outtextxy(midx, midy+10, "Press any key to start");
getch();
cleardevice();
setcolor(WHITE);
settextstyle(DEFAULT_FONT, HORIZ_DIR, 1);
rectangle(midx-30,midy-80,midx+30,midy+80);
circle(midx, midy-50, 22);
setfillstyle(SOLID_FILL,RED);
floodfill(midx, midy-50,WHITE);
setcolor(BLUE);
outtextxy(midx,midy-50,"STOP");
delay(2000);
graphdefaults();
cleardevice();
setcolor(WHITE);
rectangle(midx-30,midy-80,midx+30,midy+80);
circle(midx, midy, 20);
setfillstyle(SOLID_FILL,YELLOW);
floodfill(midx, midy,WHITE);
setcolor(BLUE);
outtextxy(midx-18,midy-3,"READY");
delay(2000);
cleardevice();
setcolor(WHITE);
rectangle(midx-30,midy-80,midx+30,midy+80);
circle(midx, midy+50, 22);
setfillstyle(SOLID_FILL,GREEN);
floodfill(midx, midy+50,WHITE);
setcolor(BLUE);
outtextxy(midx-7,midy+48,"GO");
setcolor(RED);
settextstyle(SCRIPT_FONT, HORIZ_DIR, 4);
outtextxy(midx-150, midy+100, "Press any key to exit...");
getch();
closegraph();
return 0;
}

Flying kite:

#include<stdio.h>
#include<stdlib.h>
#include<conio.h>
#include<dos.h>
#include<graphics.h>
#include<ctype.h>
#include<math.h>
void main()
{
int
int
int
int

gd=DETECT,gm;
color;
x=10,y=1,inc_x=10,inc_y=10;
poly[10];

initgraph(&gd,&gm," ");
while(!kbhit())

ASHOKA RAO
THUMUCHERLA

C-language
{

x += inc_x;
if(x > 200)
inc_x = -5;
if(x < 0 )
inc_x = 10;
y += inc_y;
if(y > 100)
inc_y = -10;
if(y < 0 )
inc_y = 10;
cleardevice();
setcolor(WHITE);
setbkcolor(BLUE);
poly[0]=100+x;
poly[1]=50+y;
poly[2]=140+x;
poly[3]=100+y;
poly[4]=100+x;
poly[5]=155+y;
poly[6]=60+x;
poly[7]=100+y;
poly[8]=100+x;
poly[9]=50+y;
drawpoly(5,poly);
setfillstyle(SOLID_FILL,RED);
fillpoly(5,poly);
setlinestyle(SOLID_LINE,1,3);
line(100+x,155+y,100+x,180+y);
line(100+x,155+y,110+x,180+y);
line(100+x,155+y,90+x,180+y);
setlinestyle(SOLID_LINE,1,0);
line(0,480,100+x,90+y);
line(100+x,90+y,130+x,100+y);
line(100+x,90+y,70+x,100+y);
line(100+x,90+y,100+x,70+y);

delay(6000);
}
setlinestyle(SOLID_LINE,0,0);
fflush(stdin);
}

ASHOKA RAO
THUMUCHERLA

C-language
Conio.h

kbhit in c
kbhit :

kbhit function is used to determine if a key has been pressed or not.


To use kbhit function in your program you should include the header file
"conio.h". If a key has been pressed then it returns a non zero value
otherwise returns zero.

Declaration : int kbhit();

C programming code for kbhit


#include <stdio.h>
#include <conio.h>
main()
{
while (!kbhit())
printf("You haven't pressed a key.\n");
}

return 0;

textcolor in c
textcolor function is used to change the color of drawing text in c programs.
Declaration :- void textcolor(int color);
where color is an integer variable. For example 0 means BLACK color, 1 means BLUE, 2 means GREEN and soon. You can also use
write appropriate color instead of integer. For example you can write textcolor(YELLOW); to change text color to YELLOW. But
use colors in capital letters only.

C programming code to change text color


#include<stdio.h>
#include<conio.h>
main()
{
textcolor(RED);
cprintf("C programming");
getch();
return 0;
}

C programming code for blinking text


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

ASHOKA RAO
THUMUCHERLA

C-language
{

textcolor(MAGENTA+BLINK);
cprintf("C programming");
getch();
return 0;

gotoxy in c
gotoxy in c: gotoxy function places cursor at a desired location on screen i.e. we can change cursor position using gotoxy function.
Declaration : void gotoxy( int x, int y);
where (x, y) is the position where we want to place the cursor.

C programming code for gotoxy


// Works in turbo c compiler only
#include <stdio.h>
#include <conio.h>
main()
{
int x=10, y=5;
clrscr();
gotoxy(x,y);
printf("cursor at point (%d,%d)\n",x,y);
y = y+10;
gotoxy(x,y);
printf("cursor at point (%d,%d)\n",x,y);
getch();
return 0;
}

getch in c
getch in c language: getch function prompts the user to press a character and that character is not printed on screen, getch header file
is conio.h.

C programming code for getch


/* getch in c example */
#include<stdio.h>
#include<conio.h>
main()
{
printf("Waiting for a character to be pressed from the keyboard to exit.\n");
getch();
return 0;

ASHOKA RAO
THUMUCHERLA

C-language
}

wherex in c
wherex function return current horizontal cursor position.
Declaration :- int wherex();

C programming code for wherex


#include<stdio.h>
#include<conio.h>
main()
{
int x;
printf("Hello");
x = wherex();
printf("Horizontal cursor position from where this text appears = %d\n",x);

getch();
return 0;

textbackground in c
textbackground function is used to change of current background color in text mode. See availablecolors.
Declaration : void textbackground(int color);

C programming code for textbackground


#include<stdio.h>
#include<conio.h>
main()
{
int i;
clrscr();
for(i=1;i<16;i++)
{
textbackground(i);
textcolor(i+1);
cprintf("different colors in c");
printf("\n");
}
getch();
return 0;
}

ASHOKA RAO
THUMUCHERLA

C-language

delline
delline function deletes the line containing the cursor and move all lines below it one line up.

C programming code for delline


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

clrscr()
printf("This line will be deleted when you press a key.");
getch();
delline();
printf("\rLine deleted successfully.");
getch();
return 0;

#include<stdio.h>
#include<conio.h>
main()
{
clrscr();
printf("This line will be deleted when you press a key.\n");
getch();
gotoxy(1,1);
delline();
printf("Line deleted successfully.");
getch();
return 0;
}

#include<stdio.h>
#include<conio.h>
main()
{
int i;
clrscr();
for(i=1;i<=5;i++)
{

ASHOKA RAO
THUMUCHERLA

C-language
printf("line number %d.\n",i);
}
printf("press any key to exit....");
gotoxy(1,6);
getch();
clreol();
getch();
return 0;
}
#include<stdio.h>
#include<conio.h>
main()
{
int i;
clrscr();
for(i=1;i<=5;i++)
{
printf("line number %d.\n",i);
}
gotoxy(1,3);
getch();
/*delline();*/
clreol();
getch();
return 0;

ASHOKA RAO
THUMUCHERLA

C-language
}Math.h

sqrt function
sqrt function returns square root of a number.
Declaration :- double sqrt(double);

C programming code for sqrt


#include <stdio.h>
#include <math.h>
int main()
{
double n, result;
printf("Enter a number to calculate it's square root\n");
scanf("%lf", &n);
result = sqrt(n);
printf("Square root of %.2lf = %.2lf\n", n, result);
return 0;
}

pow function
pow function returns x raise to the power y where x and y are variables of double data type.
Declaration :- double pow(double, double);

C programming code for pow


#include <stdio.h>
#include <math.h>
int main()
{
double c, d, result;
printf("Enter c and d to calculate c^d\n");
scanf("%lf%lf", &c, &d);
result = pow(c, d);
printf("%.2lf raised to %.2lf = %.2lf\n", c, d, result);
}

return 0;

abs c - math.h
abs is not a function but is a macro and is used for calculating absolute value of a number.

ASHOKA RAO
THUMUCHERLA

C-language
C programming code for abs
#include <stdio.h>
#include <math.h>
int main()
{
int n;
float f;
clrscr();
printf("Enter one integer :");
scanf("%d",&n);
printf("absolute value :%d\n",abs(n));

printf("enter one real number :");


scanf("%f",&f);
printf("absolute value :%f",fabs(f));
return 0;
}

Output of program:

ceil in c - math.h
Ceil function is used to round up a number i.e. it returns the smallest number which is greater than argument passed to it.
Declaration: double ceil(double);

ASHOKA RAO
THUMUCHERLA

C-language
C programming code
#include <stdio.h>
#include <math.h>
int main()
{
double n, result;
printf("Enter a number to round it up\n");
scanf("%lf", &n);
result = ceil(n);
printf("Original number = %.2lf\n", n);
printf("Number rounded up = %.2lf\n", result);
return 0;
}

floor function
Floor function returns the greatest integer not greater than x. For example if the input is 2.25 then output will be 2.00.
Declaration :- double floor(double x);

C programming code for floor


#include <stdio.h>
#include <math.h>
int main()
{
double n, result;
printf("Enter a number to round it down\n");
scanf("%lf", &n);
result = floor(n);
printf("Original number = %.2lf\n", n);
printf("Number rounded down = %.2lf\n", result);
}

return 0;

Dos.h

delay function in c
Delay in c: delay function is used to suspend execution of a program for a particular time.

ASHOKA RAO
THUMUCHERLA

C-language
Declaration :- void delay(unsigned int);
Here unsigned int is the number of milliseconds ( remember 1 second = 1000 milliseconds ). To use delay function in your program
you should include the dos.h header file.

C programming code for delay


#include<stdio.h>
#include<stdlib.h>
main()
{
printf("This c program will exit in 10 seconds.\n");
delay(10000);
return 0;
}

getdate c
Program to print the current system date, getdate c code below explain how to use this function to print computer date.

Getdate example
C programming code to print date

#include<stdio.h>
#include<dos.h>
main()
{
struct date d;
clrscr();
getdate(&d);
printf("Current system date is %d/%d/%d\n",d.da_day,d.da_mon,d.da_year);
printf("\n%s",__DATE__);
return 0;
}

gettime c
gettime in c: gettime function is used to find current system time. We pass address of a structure varibale of type ( struct time ).

C programming code for gettime


#include<stdio.h>
#include<dos.h>
main()
{
struct time t;
clrscr();
gettime(&t);
printf("Current system time is %d : %d : %d\n",t.ti_hour,t.ti_min,t.ti_sec);
printf("\n%s",__TIME__);

ASHOKA RAO
THUMUCHERLA

C-language

return 0;

ASHOKA RAO
THUMUCHERLA

Vous aimerez peut-être aussi