Académique Documents
Professionnel Documents
Culture Documents
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).
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:
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.
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
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.
ASHOKA RAO
THUMUCHERLA
C-language
Disadvantages of Assembly Language
c) String and List Processing: These are used for string manipulation including search
for patterns, inserting and deleting characters. Examples are:
C++
ASHOKA RAO
THUMUCHERLA
C-language
Java
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
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
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
ASHOKA RAO
THUMUCHERLA
C-language
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
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.
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.
ASHOKA RAO
THUMUCHERLA
C-language
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.
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.
ASHOKA RAO
THUMUCHERLA
C-language
ASHOKA RAO
THUMUCHERLA
C-language
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
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
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
Keywords:
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
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
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:
ASHOKA RAO
THUMUCHERLA
C-language
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:
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
}
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():
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;
}
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
10^2
10^1 10^1
thousand hundred
tens
s
s
ones
1000
100
10
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:
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)
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
=
=
000
001
010
011
100
101
110
111
100
4
101
5
011
3
= 345 oct
digits.
0101
5
0110
6
0111
7
1101
D
1110
E
1111
F
1110 0101
ASHOKA RAO
THUMUCHERLA
C-language
Hexadecimal
= E5 hex
011
100
101
= 011100101
binary
ASHOKA RAO
THUMUCHERLA
C-language
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
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:
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
+5
=
0000 0010
+2
-3
+7
=
=
-12
-5
-4
=
+4
ASHOKA RAO
THUMUCHERLA
C-language
1111 0000
-16
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:
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):
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
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.
!
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
ASHOKA RAO
THUMUCHERLA
C-language
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:
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;
}
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
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.
Description
Associativity
ASHOKA RAO
THUMUCHERLA
C-language
()
[]
.
->
++ -++ -+!~
(type)
*
&
sizeof
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
ASHOKA RAO
THUMUCHERLA
C-language
CONTROL 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
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.
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:
ASHOKA RAO
THUMUCHERLA
C-language
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
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)
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)
ASHOKA RAO
THUMUCHERLA
C-language
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 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
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.
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
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.
#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.
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:
#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.
If there are fewer initializes than elements in the array, C initializes the
remaining elements to zero.
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.
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.
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,
ASHOKA RAO
THUMUCHERLA
C-language
printf("the array elements are :\n");
for(i = 0;i<5;i++){
printf("%d\n",arr[i]);
}
}
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;
}
#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();
}
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', ' '}
};
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;
}
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
Int*
Int
10
11 12 13 14 15
Int
16 17 18 19 20
Int
21
22 23 24 25
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
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
Overview:
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:
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
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
strchr
strcmp
strncat
char *strncat(char *t
o,
char *from, int size);
strncmp
memchr
void *memchr(void *
p, char n, unsigned
int v);
memcmp
int memcmp(void *s
1, void *s2, int n);
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);
ASHOKA RAO
THUMUCHERLA
C-language
strlwr
char * strlwr(char
*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;
}
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;
}
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:
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
ASHOKA RAO
THUMUCHERLA
C-language
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>..
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.
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();
}
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
STRUCTURE
UNION
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
THUMUCHERLA
C-language
ASHOKA RAO
THUMUCHERLA
C-language
#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:-
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 :
#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:
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:
#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);
}
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?
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.
#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)
Before concept of pointer conversion you must understand the concept of a void
pointer.
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:
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 *.
Step4: Since data type enjoys least priority so assign fourth priority to char.
ASHOKA RAO
THUMUCHERLA
C-language
float (* ptr)(int)
Assign the priority considering precedence and associative.
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.
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;
Introduction:
ASHOKA RAO
THUMUCHERLA
C-language
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
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:
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.
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.
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
ASHOKA RAO
THUMUCHERLA
C-language
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.
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():
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
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.
ASHOKA RAO
THUMUCHERLA
C-language
stdout : connected to the screen
stderr: connected to the screen
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, ...] );
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
[. . .]
scanf():
#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()
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.
#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;
}
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;
}
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);
#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
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 );
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;
}
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;
}
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, ... );
#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
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> );
#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>)
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);
#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
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.
->
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
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.
#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
#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
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:
easier to read,
easier to modify
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]
ASHOKA RAO
THUMUCHERLA
C-language
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:
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
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();
}
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
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
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:
syntax:
enum identifier { enumerator-list }
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;
}
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
Description
Static
allocation
Automatic
allocation
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:
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;
}
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;
}
ASHOKA RAO
THUMUCHERLA
C-language
#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();
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;
}
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;
}
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;
}
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;
}
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;
}
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 :
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.
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.
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.
ASHOKA RAO
THUMUCHERLA
C-language
}
wherex in c
wherex function return current horizontal cursor position.
Declaration :- int wherex();
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);
ASHOKA RAO
THUMUCHERLA
C-language
delline
delline function deletes the line containing the cursor and move all lines below it one line up.
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);
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);
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));
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);
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.
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 ).
ASHOKA RAO
THUMUCHERLA
C-language
return 0;
ASHOKA RAO
THUMUCHERLA