+ All Categories
Home > Documents > Learn C Programming Step by Step

Learn C Programming Step by Step

Date post: 14-Apr-2015
Category:
Upload: arvinvit
View: 110 times
Download: 3 times
Share this document with a friend
Description:
C Programming Step by Step
192
LEARN C PROGRAMMING STEP BY STEP -Gopal Raha Many people are really interested in learning and implementing C programs on their favorite platforms like DOS/Windows or Linux. If you are the one looking for a step-by-step guide to get started, this tutorial is for you.
Transcript
Page 1: Learn C Programming Step by Step

LEARN C PROGRAMMING STEP BY STEP -Gopal Raha

Many people are really interested in learning and implementing C programs on their favorite

platforms like DOS/Windows or Linux. If you are the one looking for a step-by-step guide to get

started, this tutorial is for you.

Page 2: Learn C Programming Step by Step

P a g e | 1

LEARN C PROGRAMMING

STEP BY STEP

-Gopal Raha

Page 3: Learn C Programming Step by Step

P a g e | 2

Dedicated to

My Dad,Mom and Gore Sir,

Who inspire me to write this book.

Page 4: Learn C Programming Step by Step

P a g e | 3

Preface

What is a programming language?--Human beings need language to communicate between

them. Similarly to communicate with computers we need a programming language. All the

events in life can be communicated to computers with the help of programming language. C

is the basic of all programming language. Before the introduction of C we had only Machine

level languages. C is just like any other communication Language.

If you learn C programming thoroughly you can easily learn other programming

languages. To learn C we just need to know the syntax of C program only. i.e order in which

we have to write the contents.This book is intended to introduce C programming to beginning

programmers. Over several years of studying, I have noted a large number of students appear

to have difficulty in grasping the fundamentals of C Language. So I am trying to explain

them with the help of simple examples.

This book will help you get a quick start with C programming. This book is a guide

for the beginners and also for those who have little knowledge on C Programming

fundamentals.

There are different types of programming languages such as Structure oriented,

Object oriented etc. C is the most commonly used Structure oriented programming language.

Compiler for some languages are developed using C only. With the help of this tutorial I am

trying to explain all the basics of C.In order to successfully complete this tutorial, you won't

need any prior knowledge of the C programming language. First of all I will start with the

most basic concepts and take you up to the highest level of C programming including the

usually intimidating concepts of structures, union,file, pointers and dynamic memory

allocation,etc.

Once you have mastered C, you will find Object Oriented Language such as

c++,java, etc are easy to learn.

So let's start our Journey.........

-AUTHOR

Page 5: Learn C Programming Step by Step

P a g e | 4

Contents

1. Introduction 5

2. Turbo C++ IDE 6

3. A Basic C Program 8

4. Fundamentals 12

5. Input/Output Functions 37

6. Control Statements 44

7. Arrays 58

8. Strings 65

9. Functions 92

10. Storage Classes 98

11. Structure 102

12. Union 107

13. Pointers 110

14. Dynamic memory allocation 114

15. File 126

16. Graphics 138

17. The C Preprocessor 183

18. Standard Library Functions 185

19. Examples 187

20. Reference 191

Page 6: Learn C Programming Step by Step

P a g e | 5

Introduction To C Programming Language

The C language was invented at Bell Labs by Dennis Ritchie in 1972 to allow the writing of

the UNIX operating system, then developed by Ken Thompson and Dennis Ritchie.

The UNIX operating system, born in the late 1960s – early 1970s, was written

directly in assembly language for the machines which it was intended. Born in the late 1960s

– early 1970s, was written directly in assembly language for the machines which it was

intended. If the assembly language for writing such a system, it was nevertheless not easy to

use. Such language is in fact a particular type of processor, which makes the whole system

should be rewritten to make it work on a new architecture. This is its main creator, Ken

Thompson, wanted to use a language more quickly evolved to rewrite UNIX.

Among the languages available at the time, BCPL (Basic Combined

Programming Language for, which is a simplification of CPL), created by Martin Richards in

1966, was interesting. Without going into detailed descriptions, BCPL is a simple language,

procedural, and not typed. Its simplicity makes it easy to create BCPL compilers on machines

of the time, when resources were very limited (the first computer used by Keith Thompson

was to launch a Unix PDP-7, which had a memory of 4000 words 18 bits, or less than 9 KB).

Ken Thompson has evolved to design the B language, which he implemented the first UNIX

machines. However, some limitations of language B were UNIX could be rewritten in this

language.

From 1971, Dennis Ritchie B did evolve to address these issues. Like the

programmers increment versions of their programs, Ritchie “Nudge” the letter B to call the

new language C. This evolution is “stabilized” to 1973, from which UNIX and UNIX system

utilities have been rewritten successfully in C.

Subsequently in 1978, Brian W. Kernighan documentation very active

language, and finally publish the book with reference Ritchie The C Programming

Language. Often called K & R C language as specified in the first edition of this book.

In the years that followed, the C language was carried on many other machines.

These ports were often made at the beginning, from the pcc compiler Steve Johnson, but then

the original compilers were developed independently. During these years, every C compiler

was written in accordance with the specifications of K & R, but some added extensions, such

as data types or additional features, or different interpretations of certain parts of the book

(not necessarily very precise). Because of this, it was less easy to write C programs that can

run unchanged on many architectures.

Page 7: Learn C Programming Step by Step

P a g e | 6

Turbo C++ Integrated Development

Environment

IDE is nothing but Integrated Development Environment in which one can develop,

run, test and debug the application. The Turbo C++ IDE appears as shown in figure.

The C Developing Environment is a screen display with windows and pull-down

menus. The program listing, error messages and other information are displayed in separate

windows. The menus may be used to invoke all the operations necessary to develop the

program, including editing, compiling, linking, and debugging and program execution. If the

menu bar is inactive, it may be invoked by pressing the [F10] function key. To select

different menu, move the highlight left or right with cursor (arrow) keys. You can also revoke

the selection by pressing the key combination for the specific menu.

Invoking the Turbo C IDE

The default directory of Turbo C compiler is c:\tc\bin. So to invoke the IDE from the

windows you need to double click the TC icon in the directory c:\tc\bin.

The alternate approach is that we can make a shortcut of tc.exe on the desktop.

Opening New Window in Turbo C

To type a program, you need to open an Edit Window. For this, open file menu and click

“new”. A window will appear on the screen where the program may be typed.

Writing a Program in Turbo C

Page 8: Learn C Programming Step by Step

P a g e | 7

When the Edit window is active, the program may be typed. Use the certain key

combinations to perform specific edit functions.

Saving a Program in Turbo C

To save the program, select save command from the file menu. This function can also be

performed by pressing the [F2] button. A dialog box will appear asking for the path and name

of the file.Provide an appropriate and unique file name. You can save the program after

compiling too but saving it before compilation is more appropriate.

Making an Executable File in Turbo C

The source file is required to be turned into an executable file. This is called “Making” of the

.exe file. The steps required to create an executable file are:

1. Create a source file, with a .c extension.

2. Compile the source code into a file with the .obj extension.

3. Link your .obj file with any needed libraries to produce an executable program

All the above steps can be done by using Run option from the menu bar or using key

combination Ctrl+F9 (By this linking & compiling is done in one step).

Compiling and linking in the Turbo C IDE

In the Turbo C IDE, compiling and linking can be performed together in one

step. There are two ways to do this: you can select Make EXE from the compile menu, or you

can press the [F9] key

Correcting Errors in Turbo C

If the compiler recognizes some error, it will let you know through the Compiler window.

You’ll see that the number of errors is not listed as 0, and the word “Error” appears instead

of the word “Success” at the bottom of the window. The errors are to be removed by

returning to the edit window. Usually these errors are a result of a typing mistake. The

compiler will not only tell you what you did wrong, they’ll point you to the exact place in

your code where you made the mistake.

Executing a Programs in Turbo C

If the program is compiled and linked without errors, the program is executed by selecting

Run from the Run Menu or by pressing the [Ctrl+F9] key combination.

Exiting Turbo C IDE

An Edit window may be closed in a number of different ways. You can click on

the small square in the upper left corner, you can select close from the window menu, or you

can press the Alt+F3 combination. To exit from the IDE, select Exit from the File Menu or

press Alt+X Combination.

Page 9: Learn C Programming Step by Step

P a g e | 8

A Simple C Program

Every C program must have one special function main (). This is the point where

execution begins when the program is running. We will see later that this does not have to be

the first statement in the program, but it must exist as the entry point. The group

of statements defining the main () enclosed in a pair of braces ({}) are executed

sequentially. Each expression statement must end with a semicolon. The closing brace of the

main function signals the end of the program. The main function can be located anywhere in

the program but the general practice is to place it as the first function.

Here is an elementary C program.

Main ()

{

}

There is no way to simplify this program, or to leave anything out. Unluckily, the

program does not do anything. Following the “main” program name is a couple of

parentheses, which are an indication to the compiler that this is a function. The 2 curly

brackets { }, properly called braces, are used to specify the limits of the program itself. The

actual program statements go between the 2 braces and in this case, there are no statements

because the program does absolutely nothing. You will be able to compile and run this

program, but since it has no executable statements, it does nothing. Keep in mind however,

that it is a legal C program.

Main ( ) function should return zero or one.Turbo C accepts both int and void main ( ) and

Turbo C coders use both int and void main ( ) in their programs.But in my belief, void main (

) is not a standard usage. The reason is, whenever a program gets executed it returns an

integer to the OS. If it returns ‘zero’, the program is executed successfully. Otherwise it

means the program has been ended with error. So main ( ) shouldn’t be declared as void.d as

void.

Main( ) should be declared as

int main( )

{

……………..

……………..

return 0 ;

}

.For a much more interesting program, load the program

Page 10: Learn C Programming Step by Step

P a g e | 9

int main ()

{

printf (“Welcome to C language”);

return 0;

}

and display it on your monitor. It is same as the previous program except that it has one

executable statement between the braces.

The executable statement is another function. Again, we won’t care about what a

function is, but only how to use this one. In order to output text to the monitor, it’s placed

within the function parentheses and bounded by quotes. The end result is that whatever is

included between the quotes will be showed on the monitor when the program is run.

Notice the semi-colon; at the end of the line. C uses a semi-colon as a statement

terminator, so semi-colon is required as a signal to the compiler that this line is complete.

This program is also executable, so you’ll be able to compile and run it to see if it does what

you think it should. With some compilers, you may get an error message while compiling,

indicating that the function printf () should have a prototype.

#include<stdio.h>

#include<conio.h>

int main ()

{

printf (“Welcome to C language”);

return 0;

}

Here you’ll be able to see #include at the beginning of the program. It is a pre-

processor directive. It’s not a part of our program; it’s an instruction to the compiler to make

it do something. It says the C compiler to include the contents of a file, in this case the system

file stdio.h. This is the name of the standard library definition file for all Standard Input

Output. Your program will almost certainly want to send stuff to the screen and read things

from the keyboard. Stdio.h is the name of the file in which the functions that we want to use

are defined. A function is simply a group of related statements that we can use later. Here the

function we used is printf . To use printf correctly C needs to know what it looks like, i.e.

what things it can work on and what value it returns. The actual code which performs the

printf will be tied in later by the linker. Note that without the definition of what printf looks

like the compiler makes a guess when it sees the use of it. This can lead to the call failing

when the program runs, a common cause of programs crashing.

Page 11: Learn C Programming Step by Step

P a g e | 10

The <> characters around the name tell C to look in the system area for the file

stdio.h. If I had given the name “abc.h” instead it would tell the compiler to look in the

current directory. This means that I can arrange libraries of my own routines and use them in

my programs.

Imagine you run above program and then change it and run it again you may find

that the previous output is still stucked there itself, at this time clrscr(); would clear the

previous screen.

One more thing to remember while using clrscr() is that it should be called only after the

variable declaration, like

int p,q,r;

clrscr()

Here is an example of minimal C program that displays the string Welcome to C language

(this famous example included in all languages moreover been done originally in C in 1978

from the creators of the language, Brian Kernighan and Dennis Ritchie) Example

#include<stdio.h>

#include<conio.h>

int main ()

{

clrscr();

printf (“Welcome to C language”);

return 0;

}

When you execute above program you won’t see ‘Welcome to C language’ on

the console because the screen will just flash and go away .If you want to see the line you

can use getch() function just below the printf() statement. Actually it waits until a key is

pressed.

Example:

Page 12: Learn C Programming Step by Step

P a g e | 11

Page 13: Learn C Programming Step by Step

P a g e | 12

Fundamentals

1. Identifiers

Identifiers are the names that are given to various program elements such as variables,

symbolic constants and functions.Variable or function identifier that is called a symbolic

constant name.

Identifier can be freely named, the following restrictions.

Alphanumeric characters ( a ~ z , A~Z , 0~9 ) and half underscore ( _ ) can only be used.

The first character of the first contain letters ( a ~ z , A~Z ) or half underscore ( _ ) can only be used.

Case is distinguishable. That is, word and WORD is recognized as a separate identifier. Reserved words are not allowed. However, part of an identifier reserved words can be

included.

Here are the rules you need to know:

1. Identifier name must be a sequence of letter and digits, and must begin with a

letter.

2. The underscore character (‘_’) is considered as letter.

3. Names shouldn't be a keyword (such as int , float, if ,break, for etc)

4. Both upper-case letter and lower-case letter characters are allowed. However,

they're not interchangeable.

5. No identifier may be keyword.

6. No special characters, such as semicolon,period,blank space, slash or comma

are permitted

Examples of legal and illegal identifiers follow, first some legal identifiers:

float _number;

float a;

int this_is_a_very_detailed_name_for_an_identifier;

The following are illegal (it's your job to recognize why):

float :e;

float for;

Page 14: Learn C Programming Step by Step

P a g e | 13

float 9PI;

float .3.14;

float 7g;

Example :

Page 15: Learn C Programming Step by Step

P a g e | 14

2. Keywords

Keywords are standard identifiers that have standard predefined meaning in C.

Keywords are all lowercase, since uppercase and lowercase characters are not equivalent it's

possible to utilize an uppercase keyword as an identifier but it's not a good programming

practice.

Points to remember

1. Keywords can be used only for their intended purpose.

2. Keywords can't be used as programmer defined identifier.

3. The keywords can't be used as names for variables.

The standard keywords are given below:

Page 16: Learn C Programming Step by Step

P a g e | 15

3. Data Types

C offers a standard, minimal set of basic data types. Sometimes these are called

"primitive" types. A lot of complex data structures can be developed from these basic data

types. The C language defines 4 fundamental data types:

character

integer

floating-point and

double floating-point

This data types are declared using the keywords char,int,float and double respectively.

Typical memory requirements of the basic data types are given below

The size and range of these data types may vary among processor types and

compilers. Data type qualifiers modify the behavior of variable type to which they are

applied. Data type qualifiers can be classified into two types.two types.

1. size qualifiers

2. sign qualifiers

Size qualifiers:

Size qualifiers alter the size of the basic data types. There are two size qualifiers that

can be applied to integer: short and long.

The minimum size of short int is 16 bit. The size of int must be greater than or equal to that of

a short int. The size of long int must be greater than or equal to a short int. The minimum size

of a long int is 32 bits.

Sign qualifiers:

The keywords signed and unsigned are the two sign qualifiers that specify whether a

variable can hold both –ve and +ve numbers, or only +ve numbers. These qualifiers can be

applied to the data types int and char only.

Example: unsigned int I;

The following table shows all valid data type combinations supported by C, along

with their minimal ranges and typical memory size.

Page 17: Learn C Programming Step by Step

P a g e | 16

Page 18: Learn C Programming Step by Step

P a g e | 17

4. int

An integer is a whole number (a number without a fractional part). It can

be positive or negative numbers like 1, -2, 3, etc., or zero.

The sizes of the integer variables depend on the hardware and operating system

of the computer. On a typical 16-bit system, the sizes of the integer types are as follows.

TYPE Bytes Possible Values le Values

int

2 or 4

-32,767 to 32,767

unsigned

int

2 or 4

0 to 65,535

signed

int

2 or 4

-32,767 to 32,767

short int

2

-32,767 to 32,767

unsigned short int 2

0 to 65,535

signed short int

2

-32,767 to 32,767

long int

4

-2,147,483,647 to 2,147,483,647

signed long

int

4

-2,147,483,647 to 2,147,483,647

unsigned long

int

4

0 to 4,294,967,295

Example:

Page 19: Learn C Programming Step by Step

P a g e | 18

Page 20: Learn C Programming Step by Step

P a g e | 19

5. char

char is a special integer type designed for storing single characters. The integer

value of a char corresponds to an ASCII character. E.g., a value of 65 corresponds to the

letter A, 66 corresponds to B, 67 to C, and so on.

As in the table below, unsigned char permits values from 0 to 255, and signed

char permits values from -127 (or -128) to 127. The char type is signed by default on some

computers, but unsigned on others the sizes of the char types are as follows.

Type Bytes Minimal range

char 1 -127 to 127

unsigned char 1 0 to 255

signed char 1 -127 to 127

Example:

Page 21: Learn C Programming Step by Step

P a g e | 20

6. Float

Floating point numbers are numbers with a decimal point. The float type can take

large floating point numbers with a small degree of precision (Precision is simply the number

of decimal places to which a number can be calculated with accuracy. If a number can be

calculated to three decimal places, it is said to have three significant digits.)

Memory size : 4 bytes

Minimal range : IE-38 to IE+38 with six digit of precision

Example:

Page 22: Learn C Programming Step by Step

P a g e | 21

7. Double

Double-precision floating point numbers are also numbers with a decimal point.

We know that the float type can take large floating point numbers with a small degree of

precision but the double-precision double type can hold even larger numbers with a higher

degree of precision.

The sizes of the double types are as follows.

Type Bytes Minimal range

doubleprecision 8 IE-38 to IE+38 with 10 digit of precision

long double 8 IE-38 to IE+38 with 10 digit of precision

Example:

Page 23: Learn C Programming Step by Step

P a g e | 22

8. Constants

The term constant means that it does not change during the execution of program.

There are four basic types of constants in C. They are:

1.Integer constants

2.Floating-point constants

3.Character constants

4.String constants

Integer and floating-point constants represent numbers. They are often referred to

as numeric-type constants. The following rule applies to all numeric type constants:

Comma and blank spaces cannot be included within the constants.

Constants can be preceded by a – or + sign, if desired. If either sign does not precede

the constant it is assumed to be positive.

The value of a constant cannot exceed specified minimum and maximum bounds. For

each type of constant, these bound vary from one C compiler to another.

Page 24: Learn C Programming Step by Step

P a g e | 23

9. Integer constants

Integer constants are whole numbers without any fractional part. Thus integer

constants consist of a sequence of digits. Integer constants can be written in three different

number systems: Decimal, Octal and Hexadecimal.

A decimal integer constant consists of any combination of digits taken from the

set 0 through 9. If the decimal constant contains two or more digits, the first digit must be

something other than 0. The following are valid decimal integer constants.

0 1 1234 -786

Example:

The following decimal integer constants are written incorrectly for the reasons stated.

12,001 Illegal character (,).

103.0 Illegal decimal point (.).

10 20 30 Illegal character (blank space).

045 First digit cannot be zero.

Example:

Page 25: Learn C Programming Step by Step

P a g e | 24

An octal integer constant can consist any combination of digits taken from the set

0 through 7. However, the first digit must be 0, in order to identify the constant as an octal

number. The following are valid octal integer constants.

0 01 0125 0555

Example :

The following decimal integer constants are written incorrectly for the reasons stated.

2010 Does not begin with 0.

2008 Illegal digit (8).

05.10 Illegal character (.).

Page 26: Learn C Programming Step by Step

P a g e | 25

A hexadecimal integer constant must begin with either 0x or 0X. It can then be followed by

any combination of digits taken from the set 0 through 9 and A through F (either upper-case

or lower-case). The following are valid hexadecimal integer constants.

0X0 0x1 0XAB125 -0x555

Example:

The following hexadecimal integer constants are written incorrectly for the reasons stated.

0x20.10 Illegal character (.).

02008 Does not begins with 0x or 0X.

0xabcdefg Illegal character (g).

Page 27: Learn C Programming Step by Step

P a g e | 26

10. Floating-point constants

A floating-point constant is a base-10 number that contains either a decimal point

or an exponent or both. A floating-point constant can be written in two forms: Factorial form

or Exponential form. A floating-point constant in a fractional form must have at least one

digit each to the left and right of the decimal point. A floating-point in exponent form

consists of a mantissa and an exponent. The mantissa itself is represented as a decimal integer

constant or a decimal floating-point constant in fractional form. The letter E or e and the

exponent follow the mantissa. The exponent must be a decimal integer. The actual number of

digits in the mantissa and the exponent depends on the computer being used.

The following are valid floating-point constants.</1.0 0.1 2E-4 -0.1555e-4

The following floating-point constants are written incorrectly for the reasons stated.written

incorrectly for the reasons stated.

1 No decimal point or exponent.

2,00.8 Illegal character (,).

2 E+10.20 Exponent must be an integer.

3 E10 Illegal character (space).

Example:

Page 28: Learn C Programming Step by Step

P a g e | 27

11. Character constants

A character constant is a single character, enclosed in single quotation marks.

e.g., ‘A’ ‘B’ ‘1’

Characters are stored internally in computer as coded set of binary digits, which have

positive decimal integer equivalents. The value of a character constant is the numeric value of

the character in the machine’s character set. This means that the value of a character constant

can vary from one machine to the next, depending on the character set being used on the

particular machine. For example, on ASCII machine the value of ‘A’ is 65 and on EBCDIC

machine it is 193.

Example:

Page 29: Learn C Programming Step by Step

P a g e | 28

12. String constants

A string constant consists of zero or more character enclosed in quotation marks.

Several string constants are given below.

“Welcome to C Programming” “ ”

“a+b\n” “Error\a\a\a”

There is a difference between the constant ‘A’ and “A” in C, the first ‘A’ is a

character constant while the second “A” is string constant. The notation ‘A’ is a constant

occupying a single byte containing the ASCII code of the character A. The notation “A” on

the other hand ,is a constant that occupies two bytes one for ASCII code of A and another for

the null character with the value 0,that terminates all the string.

Example:

Page 30: Learn C Programming Step by Step

P a g e | 29

13. Variables

Variables are means for location in memory used by a program to store data. The

size of that block depends upon the range over which the variable is allowed to vary.

For example, on personal computer the size of an integer variable is two bytes, and that of a

long integer is four bytes.

A variable region is temporarily remember a number or string value, such as covered by the

program. To identify the variables, you have a name unique to every single variable. This is

called a variable name. Before using a variable, use variables to what is called a variable

declaration that you have to reveal the names and data types that can be stored in the variable

variable.

The format for declaring a variable in C.

[Storage-class] type data variable name [= initial value];

Storage class and the initial value can be omitted.

The same data type and storage class variable can be declared, separated by commas.

[Storage-class] type data variable name [= initial value] variable [= initial value] variable [=

initial value];

In C the size of a variable type such as an integer need not be the same on all types

of machines. When we declare a variable we inform the compiler of two things, the name of

the variable and the type of the variable. For example, we declare a variable of type character

with the name i by writing:

char i;

On seeing the "char" part of this statement the compiler sets aside one bytes of

memory to hold the value of the character. It also sets up a symbol table. In that table it adds

the symbol i and the relative address in memory where those one byte was set aside. Thus,

later if we write: i = 'x'; we expect that,at run time when this statement is executed, the value

'x' will be placed in that memory location reserved for the storage of the value of i.

Following are the rules for naming the variables:

1. All variables must be declared before they can appear in executable statement.

2. A declaration consists of a data type followed by one or more variable names

separated by commas.

Example: int a,b,c;

3. Variables can be distributed among declarations in any fashion. The above declaration

can be written as

int a;

Page 31: Learn C Programming Step by Step

P a g e | 30

int b,c;

4. Integer type variables can be declared to be short integer for smaller integer quantities

or long integer for larger integer quantities.

Example:

short int a,b,c;

long int a,b,c;

5. An integer variable can also be declared to be un signed by writing unsigned int.

Example: unsigned int;

Example:

Page 32: Learn C Programming Step by Step

P a g e | 31

14. Expressions

An expression is a sequence of operators and operands that specifies computation of

a value. An expression may consist of single entity or some combination of such entities

interconnected by one or more operators. All expression represents a logical connection that's

either true or false. Thus logical type expression actually represents numerical quantities.

In C every expression evaluates to a value i.e., every expression results in some

value of a certain type that can be assigned to a variable. Some examples of expressions are

shown in the table given below.

A+b

3.14*r*r

a*a+2*a*b+b*b

Example:

Page 33: Learn C Programming Step by Step

P a g e | 32

15. Statements

The statements of a C program control the flow of program execution.In C

language several kinds of statements are available. They are

if statement

switch statement

goto statement

for statement

while statement

do-while statement

break statement

continue statement

expression statement

compound statement

return statement

null statement

Page 34: Learn C Programming Step by Step

P a g e | 33

16. Symbolic constant in c Language

A symbolic constant is name that substitute for a sequence of character that

cannot be changed. The character may represent a numeric constant, a character constant, or a

string. When the program is compiled, each occurrence of a symbolic constant is replaced by

its corresponding character sequence. They are usually defined at the beginning of the

program. The symbolic constants may then appear later in the program in place of the

numeric constants, character constants, etc., that the symbolic constants represent.

For example

, a C program consists of the following symbolic constant definitions.

#define PI 3.141593

#define TRUE 1

#define FALSE 0

#define PI 3.141593 defines a symbolic constant PI whose value is 3.141593. When the

program is preprocessed, all occurrences of the symbolic constant PI are replaced with the

replacement text 3.141593.

Note that the preprocessor statements begin with a #symbol, and are not end with a

semicolon. By convention, preprocessor constants are written in UPPERCASE.

Example: 1

#include<stdio.h>

#include<conio.h>

#define TRUE 1

#define PI 3.141593

void main()

{

float a;

float b;

float c;

float d=PI;

clrscr();

if(TRUE)

{

a=100;

b=a*10;

c=b-a;

}

printf("\na=%f\nb=%f\nc=%f\nPI=%f",a,b,c,d);

getch();

}

Example: 2

Page 35: Learn C Programming Step by Step

P a g e | 34

Page 36: Learn C Programming Step by Step

P a g e | 35

17. Operators

An operator in general, is a symbol that operates on a certain data type. C

language is very rich in operators. The commonly used operators include

1. Arithmetic operators

2. Relational operators

3. Logical operators

4. Assignment operators

5. Conditional operators

6. Comma operators

7. Unary operators

8. Bitwise Operators

Page 37: Learn C Programming Step by Step

P a g e | 36

18. Comments

Comments are added to make a program more readable to you but the compiler

must ignore the comments. Everything that is inside /* and */ is considered a comment and

will be ignored by the compiler. You must not include comments within other comments, so

something like this is not allowed: [*].

/* this is a /* comment */ inside a comment, which is wrong! */

Example :

Page 38: Learn C Programming Step by Step

P a g e | 37

Input/Output Function

1. scanf

The usually used input statement is scanf () function.

Syntax of scanf function is

scanf (“format string”, argument list);

The format string must be a text enclosed in double quotes. It contains the

information for interpreting the entire data for connecting it into internal representation in

memory.

Example: integer (%d) , float (%f) , character (%c) or string (%s).

The argument list contains a list of variables each preceded by the address list and

separated by comma. The number of argument is not fixed; however corresponding to each

argument there should be a format specifier. Inside the format string the number of argument

should tally with the number of format specifier.

Example: if i is an integer and j is a floating point number, to input these two

numbers we may use

scanf (“%d%f”, &i, &j);

Program:

Page 39: Learn C Programming Step by Step

P a g e | 38

2. getchar

getchar function will accept a character from the console or from a file, displays

immediately while typing and we need to press Enter key for proceeding.

Syntax of getchar() is

int getchar(void);

It returns the unsigned char that they read.If end-of-file or an error is encountered

getchar() functions return EOF.

For example:

char a;

a= getchar();

The function "getchar()" reads a single character from the standard input device,

the keyboard being assumed because that is the standard input device, and assigns it to the

variable "a".

The following program illustrates the use of getchar function.

Page 40: Learn C Programming Step by Step

P a g e | 39

3. gets

It is used to scan a line of text from a standard input device. The gets() function

will be terminated by a newline character. The newline character won't be included as part of

the string. The string may include white space characters.

Syntax : char *gets(char *s);

gets() function is declared in the header file stdio.h. It takes a single argument. The

argument must be a data item representing a string. On successful completion, gets() shall

return a pointer to string s.

The usage of gets() is illustrated in the following program.

Page 41: Learn C Programming Step by Step

P a g e | 40

4. printf

The usually used output statement is printf (). It is one of the library functions.

Syntax : printf (“format string”, argument list);

Format string may be a collection of escape sequence or/and conversion

specification or/and string constant. The format string directs the printf function to display the

entire text enclosed within the double quotes without any change.

Escape sequence:

Escape sequence is a pair of character. The first letter is a slash followed by a

character. Escape sequence help us to represent within the format string invisible and non-

printed character although there are physically two characters in any escape sequence. It

actually represents only one. The various escape sequences are

Escape sequence Meaning

\n New line

\t Tab

\b Back space

\a Bell

\o Null character

\? To print question mark

\\ To print slash

\' To print single quote

\" To print double quote

Conversion specification:

Conversion specification is also a pair of character. it is preceded by % and

followed by a quote which may be a character. The Conversion specification inscribes the

printf() function that it could print some value at that location in the text. The Conversion

characters supported by C are

Conversion character Meaning

Page 42: Learn C Programming Step by Step

P a g e | 41

%d Data item is displayed as a signed decimal integer.

%i Data item is displayed as a single decimal integer.

%f Data item is displayed as a floating-point value without

an exponent.

%c Data item is displayed as a single character.

%e Data item is displayed as a floating-point value with an

exponent.

%g Data item is displayed as a floating-point value using

either e-type or f-type conversion depending on value.

%o Data item is displayed as an octal integer, without a

leading zero.

%s Data item is displayed as string.

%u Data item is displayed as an unsigned decimal integer.

%x Data item is displayed as a hexadecimal integer,

without a leading 0x.

The following program illustrates the use of puts function.

Page 43: Learn C Programming Step by Step

P a g e | 42

5. putchar

putchar function displays a single character on the screen.

prototype: int putchar(int c);

The following program illustrates the use of putchar function.

Page 44: Learn C Programming Step by Step

P a g e | 43

6. puts

It is used to display a string on a standard output device. The puts() function

automatically inserts a newline character at the end of each string it displays, so each

subsequent string displayed with puts() is on its own line. puts() returns non-negative on

success, or EOF on failure.

The following program illustrates the use of puts function.

Page 45: Learn C Programming Step by Step

P a g e | 44

Control Statement

1. if statements

If statement is a conditional branching statement. In conditional branching

statement a condition is evaluated, if it is evaluate true a group of statement is executed. The

simple format of an if statement is as follows:

if (expression)

statement;

If the expression is evaluated and found to be true, the single statement following

the "if" is executed. If false, the following statement is skipped. Here a compound statement

composed of several statements bounded by braces can replace the single statement.

Here's an example program using simple if statement:

if else statement:

This feature permits the programmer to write a single comparison, and then

execute one of the two statements depending upon whether the test expression is true or false.

The general form of the if-else statement is

if(expression)

statement1

Page 46: Learn C Programming Step by Step

P a g e | 45

else

statement2

Here also expression in parentheses must evaluate to (a boolean) true or false.

Typically you're testing something to see if it's true, and then running a code block(one or

more statements) if it is true, and another block of code if it isn't. The statement1 or

statement2 can be either simple or compound statement.

The following program demonstrates a legal if else statement:

You can set up an if-else statement to test for multiple conditions. The following

example uses two conditions so that if the first test fails, we want to perform a second test

before deciding what to do:

if (x%2==0)

{

printf(“x is an even number”);

}

else

{

if (x>10)

{

printf(“x is an odd number and greater than 10”);

}

else

{

printf(“x is an odd number and less than 10”);

}

}

Page 47: Learn C Programming Step by Step

P a g e | 46

This brings up the other if-else construct, the if, else if, else. This construct is

useful where two or more alternatives are available for selection.

The syntax is

if(condition)

statement 1;

else if (condition)

statement 2;

.....................

.....................

else if(condition)

statement n-1;

else

statemens n ;

The various conditions are evaluated one by one starting from top to bottom, on

reaching a condition evaluating to true the statement group associated with it are executed

and skip other statements. If none of expression is evaluate to true, then the statement or

group of statement associated with the final else is executed.

The following program demonstrates a legal if-elseif-else statement:

Page 48: Learn C Programming Step by Step

P a g e | 47

2. c switch statement

Switch statements simulate the use of multiple if statement.The switch statement is

probably the single most syntactically awkward and error-prone feature of the C language.

Syntax of c switch statement is

switch(expression)

{

case constant1:

statements 1;

break;

case constant2:

statements 2;

break;

…………………..

default:

statements n;

break;

}

When the switch statement is executed, the expression in the switch statement is

evaluated and the control is transferred directly to the group of statements whose case label

value matches the value of the expression. Each group of statement ends with a break

statement. The execution of break statement causes immediate exit from the switch statement.

If break statement is not present, then the execution will falls trough all the statement in the

selected case. If none of the case-label value matches the value of expression, then none of

the group within the switch statement will be selected and the control is transferred directly to

the statement that follows the switch statement c.

The expression that forms the argument of switch is evaluated to either char or

integer. Similarly the constant expression follows the keyword case should be a value int or

char. That is, names of variable can also be used. Switch can test for only equality.

Take a look at the following if-else code, and notice how confusing it can be to

have nested if tests, even just a few levels deep:

int number = 10;

if(number == 1)

{

printf("Given number is 1\n");

}

else if((number == 2)

{

printf("Given number is 2\n");

}

else if((number ==3)

{

printf("Given number is 3\n");

}

Page 49: Learn C Programming Step by Step

P a g e | 48

else if((number ==4)

{

printf("Given number is 4\n");

}

else if((number ==5)

{

printf("Given number is 5\n");

}

else

{

if(number<0)

printf("Given number is negative\n");

else

printf("Given number is greater than 5\n");

}

Now let's see the same functionality represented in a switch construct:

It’s illegal to have more than one case label using the same value. For example, the

following block of code won't compile because it uses two cases with the same.

Page 50: Learn C Programming Step by Step

P a g e | 49

int temp = 100;

switch(temp)

{

case 10 : printf("10");

break;

case 10 : printf("10"); // won't compile!

break;

case 100 :printf("1000");

break;

default : printf("default");

break;

}

Break and Fall-Through in switch Blocks:

When case constants are evaluated from the top to down, and the first case

constant that matches the switch's expression is the execution entry point. In other words,

once a case constant is matched, C will execute the associated code block, and all subsequent

code blocks .

Example:

Page 51: Learn C Programming Step by Step

P a g e | 50

3. goto statement

The goto statement is used to alter the normal sequence of program execution by

transferring control to some other part of the program unconditionally. In its general form, the

goto statement is written as

goto label;

where the label is an identifier that is used to label the target statement to which

the control is transferred. Control may be transferred to anywhere within the current function.

The target statement must be labeled, and a colon must follow the label. Thus the target

statement will appear as

label:statement;

Each labeled statement within the function must have a unique label, i.e., no two statement

can have the same label.

The following program illustrates the use of goto statement.

Page 52: Learn C Programming Step by Step

P a g e | 51

4. For loop

For loop in C is the most general looping construct. The loop header contains three

parts: an initialization, a continuation condition, and step.

Syntax:

for (initialization, condition, step)

{

Statement 1;

Statement 2;

…………...

Statement n;

}

For statement contain three parts separated by two semicolons. The first part is

known as initialization. The variable called loop control variable or index variable is

initialized in this part.

The second part is known as the condition. The condition should be a value one. The

condition check can be a compound expression made up of relational expression connected

by logical AND, OR.

The third part is known as step. It should be an arithmetic expression. The

initialization need not be contained to a single variable. If more than one variable is used for

initialization they are separated by commas. The step can also applied to more than one

variable separated by commas.

When for statement is encountered at first index variable is get initialized. This

process is done only once during the execution of for statement. When condition is evaluated,

if it is true the body of the loop will be executed. If more than one statement has to be

executed it should end with a pair of braces. The condition of for loop is executed each time

at the beginning of the loop. After executing the body of the loop the step is executed, again

the condition is executed. If the condition become false it exit from the loop and control

transferred to the statement followed by the loop.

The following example executes 10 times by counting 0..9.

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

;

The following example illustrates the use of for loop.

Page 53: Learn C Programming Step by Step

P a g e | 52

Page 54: Learn C Programming Step by Step

P a g e | 53

5. while loop

The while statement is also a looping statement. The while loop evaluates the test

expression before every loop, so it can execute zero times if the condition is initially false. It

has the following syntax.

while (expression)

{

Statement 1;

Statement 2;

…………...

Statement n;

}

Here the initialization of a loop control variable is generally done before the loop

separately. The testing of the condition is done in while by evaluating the expression within

the parenthesis. If the evaluation result is true value, the block of statement within calibrates

is executed. If the evaluation result is false value the block of statements within the body of

loop is skipped and the loop execution get terminated with the control passing to the

statement immediately following the while construct. The increment or decrement of the loop

control variable is generally done within the body of the loop.

The following example illustrates the use of while loop.

Page 55: Learn C Programming Step by Step

P a g e | 54

6. do-while loop

This construct is also used for looping. In this case the loop condition is tested at the

end of the body of the loop. Hence the loop is executed al least one. The do-while is an

unpopular area of the language, most programmers’ tries to use the straight while if it is

possible.

Syntax of do while loop is

do

{

Statement 1;

Statement 2;

…………...

Statement n;

}

while(expression);

Here the block of statement following the do is executed without any condition

check. After this expression is evaluated and if it is true the block of statement in the body of

the loop is executed again. Thus the block of statement is repeatedly executed till the

expression is evaluated to false.

do-while construct is not used as often as the while loops or for loops in normal

case of iteration but there are situation where a loop is to be executed at least one, in such

cases this construction is very useful.

The following example illustrates the use of do-while loop.

Page 56: Learn C Programming Step by Step

P a g e | 55

7. break statement

The break statement is a jump instruction and can be used inside a switch construct,

for loop, while loop and do-while loop. The execution of break statement causes immediate

exit from the concern construct and the control is transferred to the statement following the

loop. In the loop construct the execution of break statement terminates loop and further

execution of the program is reserved with the statement following the body of the loop.

The following program illustrates the use of break statement.

Page 57: Learn C Programming Step by Step

P a g e | 56

8. continue statement

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.

The following program illustrates the use of continue statement.

Page 58: Learn C Programming Step by Step

P a g e | 57

9. Nested loop

In many cases we may use loop statement inside another looping statement. This

type of looping is called nested loop. In nested loop the inner loop is executed first and then

outer. The nested loop must be used to input or output multi-dimensional array elements.

The following program illustrates the use of Nested loop.

Page 59: Learn C Programming Step by Step

P a g e | 58

Arrays

Array is a data structure, which provides the facility to store a collection of data of

same type under single variable name. Just like the ordinary variable, the array should also be

declared properly. The declaration of array includes the type of array that is the type of value

we are going to store in it, the array name and maximum number of elements.

The type may be any valid type supported by C. Array names, like other variable

names, can contain only letter, digit and underscore characters. Array names cannot begin

with a digit character. I.e., The rule for giving the array name is same as the ordinary

variable. The size should be an individual constant. To refer to a particular location or

element in the array, we specify the name of the array and the index of the particular element

in the array. The index specifies the location of the element in the array. The array index

starts from zero. The maximum index value will be equal to the size of the array minus one.

The array index can be an integer variable for an integer constant.

Page 60: Learn C Programming Step by Step

P a g e | 59

1. One dimensional array in c

programming language : ID array

The declaration form of one-dimensional array is

Data_type array_name [size];

The following declares an array called ‘numbers’ to hold 5 integers and sets the

first and last elements. C arrays are always indexed from 0. So the first integer in ‘numbers’

array is numbers[0] and the last is numbers[4].

int numbers [5];

numbers [0] = 1; // set first element

numbers [4] = 5; // set last element

This array contains 5 elements. Any one of these elements may be referred to by

giving the name of the array followed by the position number of the particular element in

square brackets ([]). The first element in every array is the zeroth element.Thus, the first

element of array ‘numbers’is referred to as numbers[ 0 ], the second element of array

‘numbers’is referred to as numbers[ 1 ], the fifth element of array ‘numbers’is referred to as

numbers[ 4 ], and, in general, the n-th element of array ‘numbers’is referred to as numbers[ n

- 1 ].

Example:

Page 61: Learn C Programming Step by Step

P a g e | 60

It's a very common error to try to refer to non-existent numbers[ 5], element. C

does not do much hand holding. It is invariably up to the programmer to make sure that

programs are free from errors. This is especially true with arrays. C does not complain if you

try to write to elements of an array which do not exist!

For example: If you wrote:

numbers[ 5 ], = 6;

C would happily try to write 6 at the location which would have corresponded to

the sixth element, had it been declared that way. Unfortunately this would probably be

memory taken up by some other variable or perhaps even by the operating system. The result

would be either:

The value in the incorrect memory location would be corrupted with unpredictable

consequences.

The value would corrupt the memory and crash the program completely!

The second of these tends to be the result on operating systems with proper

memory protection. Writing over the bounds of an array is a common source of error.

Remember that the array limits run from zero to the size of the array minus one.

Out of bounds access

I would be doing well, that really shows the range of valid indices, please check often. 10

When the number of elements, all the indices of 10 or more is illegal. Also, whether any size

of negative indices is also illegal.

These errors are detected at compile time is not. It is an error at run time. However, there is

no guarantee that the error reliably. Sometimes works correctly (seems to be moving.) This is

the "luck ran" instead of "bad luck worked" so, please, as no doubt.

The best way to see these principles is by use of an example, so load the

program and display it on your monitor.

#include <stdio.h>

#include <conio.h>

int main( )

{

char name[7]; /* define a string of characters */

name[0] = 'A';

name[1] = 's';

name[2] = 'h';

name[3] = 'r';

name[4] = 'a';

name[5] = 'f';

name[6] = '\0'; /* Null character - end of text */

name[7] = ‘X’;

clrscr();

printf("My name is %s\n",name);

printf("First letter is %c\n",name[0]);

printf("Fifth letter is %c\n",name[4]);

Page 62: Learn C Programming Step by Step

P a g e | 61

printf("Sixth letter is %c\n",name[5]);

printf("Seventh letter is %c\n",name[6]);

printf("Eight letter is %c\n",name[7]);

getch();

return 0;

}

The elements of an array can also be initialized in the array declaration by

following the declaration with an equal sign and a comma-separated list (enclosed in braces)

of initializers.

The following program initializes an integer array with five values and prints the

array.

#include <stdio.h>

#include <conio.h>

int main()

{

int numbers[]={1,2,3,4,5};

int i;

clrscr();

printf("Array elements are\n");

for(i=0;i<=4;i++)

printf("%d\n",numbers[i]);

getch();

return 0;

}

If there are fewer initializers than elements in the array, the remaining elements

are initialized to zero. For example, the elements of the array n could have been initialized to

zero with the declaration

int n[ 10 ] = { 0 };

which explicitly initializes the first element to zero and initializes the remaining nine

elements to zero because there are fewer initializers than there are elements in the array. It is

important to remember that arrays are not automatically initialized to zero. The programmer

must at least initialize the first element to zero for the remaining elements to be automatically

zeroed. This method of initializing the array elements to 0 is performed at compile time for

static arrays and at run time for automatic arrays.

There are more complex uses of arrays, which I will address later along with pointers.

Page 63: Learn C Programming Step by Step

P a g e | 62

2. Two dimensional array

Two-dimensional array are those type of array, which has finite number of rows

and finite number of columns. The declaration form of 2-dimensional array is

Data_type Array_name [row size][column size];

The type may be any valid type supported by C. The rule for giving the array

name is same as the ordinary variable. The row size and column size should be an individual

constant.

The following declares a two-dimensional 3 by 3 array of integers and sets the

first and last elements to be 10.

int matrix [3][3];

matrix[0][0] = 10;

matrix[2][2] = 10;

The following Figure illustrates a two dimensional array, matrix. The array

contains three rows and tree columns, so it is said to be a 3-by-3 array. In general, an array

with m rows and n columns is called an m-by-n array.

[0] [1] [2]

[0] 10

[1]

[2] 10

Every element in array matrix is identified by an element name of the form

matrix[ i ][ j ]; matrix is the name of the array, and i and j are the subscripts that uniquely

identify each element in matrix . Notice that the names of the elements in the first row all

have a first subscript of 0; the names of the elements in the third column all have a second

subscript of 2.

In the case of Two-dimensional array, during declaration the maximum number of

rows and maximum number of column should be specified for processing all array

elements.

The implementation of the array stores all the elements in a single contiguous

block of memory. The other possible implementation would be a combination of several

distinct one-dimensional arrays. That’s not how C does it. In memory, the array is arranged

with the elements of the rightmost index next to each other. In other words, matrix[1][1]

comes right before matrix[1][2] in memory.

The following array:

Page 64: Learn C Programming Step by Step

P a g e | 63

[0] [1] [2]

[0] 1 2 3

[1] 4 5 6

[2] 7 8 9

would be stored:

1 2 3 4 5 6 7 8 9

Example:

Page 65: Learn C Programming Step by Step

P a g e | 64

3. Three dimensional array in c

programming

The declaration form of Three-dimensional array is

Data_type Array_name [size1][size2][size3];

Example:

Page 66: Learn C Programming Step by Step

P a g e | 65

String

A string in C is actually a character array. As an individual character variable

can store only one character, we need an array of characters to store strings. Thus, in C string

is stored in an array of characters. Each character in a string occupies one location in an

array. The null character ‘\0’ is put after the last character. This is done so that program can

tell when the end of the string has been reached. For example, the string ”I Like C

Programming” is stored as follows.

I L i k e C P r o g r a m m i n g \o

Since the string has 20 characters (including space), it requires an arrayof at least, size 21 to

store it.

Thus, in C, a string is a one-dimensional array of characters terminated a null

character. The terminating null character is important. In fact, a string not terminated by ‘\0’

is not really a string, but merely a collection of characters.

A string may contain any character, including special control characters, such

as \n, \t, \\ etc...

There is an important distinction between a string and a single character in C.

The convention is that single characters are enclosed by single quotes e.g. '*' and have the

type char. Strings, on the hand, are enclosed by double quotes e.g. "name" and have the type

"pointer to char" (char *) or array of char.

Strings can be declared in two main ways; one of these is as an array of

characters, the other is as a pointer to some pre-assigned array. Perhaps the simplest way of

seeing how C stores arrays is to give an extreme example which would probably never be

used in practice.

#include<stdio.h>

int main ()

{

char string[];

string[0] = 'C';

string[1] = 'P';

string[2] = 'r';

string[3] = 'o';

string[4] = 'g';

string[5] = 'r';

string[6] = 'a';

string[7] = 'm';

string[8] = 'm';

string[9] = 'i';

string[10]= 'n';

string[11] = 'g';

printf ("%s", string);

Page 67: Learn C Programming Step by Step

P a g e | 66

return 0;

}

This method of handling strings is perfectly acceptable, if there is time to

waste, but it is so laborious that C provides a special initialization service for strings, which

bypasses the need to assign every single character with a new assignment!.

The other way is use a pointer to some pre-assigned array.

#include<stdio.h>

int main ()

{

char str1[]=”I Like”;

char *str2=”C Programming”;

puts(str1);

puts(str2);

return 0;

}

Page 68: Learn C Programming Step by Step

P a g e | 67

1. strlen()

Syntax:

#include < string.h>

size_t strlen( char *str );

strlen(char *str) returns the length of the null terminated string pointed to by str. The null

terminator is not counted.

This function will return number of characters in the string provided as parameter to this

function. For example if we are providing "The world" as the string it will return 9. That

means it will take the blank spaces in between the words in the string into count. But the null

terminator is not counted. It will aslo take special characters like @,#,$,% etc into count.

consider this example str[30]="www.cprogrammingexpert.com";

It is stored like

str[0] <- 'w'

str[1] <- 'w'

str[2] <- 'w'

str[3] <- '.'

str[4] <- 'c'

str[5] <- 'p'

str[6] <- 'r'

str[7] <- 'o'

str[8] <- 'g'

str[9] <- 'r'

str[10] <-'a'

str[11] <-'m'

str[12] <-'m'

str[13] <-'i'

str[14] <-'n'

str[15] <-'g'

str[16] <- 'e'

str[17] <- 'x'

str[18] <- 'p'

str[19] <- 'e'

str[20] <- 'r'

str[21] <- 't'

str[22] <- '.'

str[23] <- 'c'

str[24] <- 'o'

str[25] <- 'm'

str[26] <- '\0'

str[27] <- 'garbage value'

str[28] <- 'garbage value'

str[29] <- 'garbage value'

Here strlen(str) equals 26. null terminator is not counted.

Example:

Page 69: Learn C Programming Step by Step

P a g e | 68

Page 70: Learn C Programming Step by Step

P a g e | 69

2. string function : strlwr()

Syntax:

char * strlwr(char *str)

strlwr(str) coverts str to all lowercase.

This function will convert all the uppercase characters in the string, which is provided as

parameter, into lowercase. It does not take care whether it is the starting letter or not. It will

convert every uppercase to lowercase.

For example

#include<stdio.h>

#include<conio.h>

int main()

{

char str[30]="www.CProgrammingExpert.com";

clrscr();

printf("\n\nstr : %s\n\n",str);

printf("strlwr(str) : %s\n",strlwr(str));

getch();

return 0;

}

here we declares the string str like this str[30]="www.CProgrammingExpert.com"; The string

str is a character array of size 30.The character is stored like this

str[0] <- 'w'

str[1] <- 'w'

str[2] <- 'w'

str[3] <- '.'

str[4] <- 'C'

str[5] <- 'P'

str[6] <- 'r'

str[7] <- 'o'

str[8] <- 'g'

str[9] <- 'r'

str[10] <-'a'

str[11] <-'m'

str[12] <-'m'

str[13] <-'i'

str[14] <-'n'

str[15] <-'g'

str[16] <- 'E'

str[17] <- 'x'

str[18] <- 'p'

str[19] <- 'e'

str[20] <- 'r'

str[21] <- 't'

str[22] <- '.'

str[23] <- 'c'

str[24] <- 'o'

str[25] <- 'm'

str[26] <- '\0'

Page 71: Learn C Programming Step by Step

P a g e | 70

str[27] <- 'garbage value'

str[28] <- 'garbage value'

str[29] <- 'garbage value'

when we use the function strlwr(str) it will convert all characters stored in the character array

str to lowercase.Then stored like this

str[0] <- 'w'

str[1] <- 'w'

str[2] <- 'w'

str[3] <- '.'

str[4] <- 'c'

str[5] <- 'p'

str[6] <- 'r'

str[7] <- 'o'

str[8] <- 'g'

str[9] <- 'r'

str[10] <-'a'

str[11] <-'m'

str[12] <-'m'

str[13] <-'i'

str[14] <-'n'

str[15] <-'g'

str[16] <- 'e'

str[17] <- 'x'

str[18] <- 'p'

str[19] <- 'e'

str[20] <- 'r'

str[21] <- 't'

str[22] <- '.'

str[23] <- 'c'

str[24] <- 'o'

str[25] <- 'm'

str[26] <- '\0'

str[27] <- 'garbage value'

str[28] <- 'garbage value'

str[29] <- 'garbage value'

so after using the function strlwr(str) the value of string str

is"www.cprogrammingexpert.com"

Example:

Page 72: Learn C Programming Step by Step

P a g e | 71

Page 73: Learn C Programming Step by Step

P a g e | 72

3. string function : strupr()

Syntax:

char * strupr(char *str);

strupr(str) coverts str to all uppercase. It returns a pointer to the original input string str.

This function will convert all the lowercase characters in the string, which is provided as

parameter, into uppercase. It will convert every lowercase to uppercase.

For example

#include<stdio.h>

#include<conio.h>

int main()

{

char str[30]="www.CProgrammingExpert.com";

clrscr();

printf("str : %s\n",str);

printf("strupr(str) : %s\n",strupr(str));

getch();

return 0;

}

here we declares the string str like this str[30]="www.CProgrammingExpert.com"; The string

string str is a character array of size 30.The character is stored like this

str[0] <- 'w'

str[1] <- 'w'

str[2] <- 'w'

str[3] <- '.'

str[4] <- 'C'

str[5] <- 'P'

str[6] <- 'r'

str[7] <- 'o'

str[8] <- 'g'

str[9] <- 'r'

str[10] <-'a'

str[11] <-'m'

str[12] <-'m'

str[13] <-'i'

str[14] <-'n'

str[15] <-'g'

str[16] <- 'E'

str[17] <- 'x'

str[18] <- 'p'

str[19] <- 'e'

str[20] <- 'r'

str[21] <- 't'

str[22] <- '.'

str[23] <- 'c'

str[24] <- 'o'

str[25] <- 'm'

str[26] <- '\0'

str[27] <- 'garbage value'

str[28] <- 'garbage value'

str[29] <- 'garbage value'

Page 74: Learn C Programming Step by Step

P a g e | 73

whe we use the function strupr(str) it will convert all characters stored in the character array str to

uppercase.Then stored like this

str[0] <- 'W'

str[1] <- 'W'

str[2] <- 'W'

str[3] <- '.'

str[4] <- 'C'

str[5] <- 'P'

str[6] <- 'R'

str[7] <- 'O'

str[8] <- 'G'

str[9] <- 'R'

str[10] <-'A'

str[11] <-'M'

str[12] <-'M'

str[13] <-'I'

str[14] <-'N'

str[15] <-'G'

str[16] <- 'E'

str[17] <- 'X'

str[18] <- 'P'

str[19] <- 'E'

str[20] <- 'R'

str[21] <- 'T'

str[22] <- '.'

str[23] <- 'C'

str[24] <- 'O'

str[25] <- 'M'

str[26] <- '\0'

str[27] <- 'garbage value'

str[28] <- 'garbage value'

str[29] <- 'garbage value'

so after using the function strupr(str) the value of string str

is"WWW.CPROGRAMMINGEXPERT.COM"

Example:

Page 75: Learn C Programming Step by Step

P a g e | 74

4. strcat()

Syntax:

#include<string.h>

char *strcat( char *str1, const char *str2 );

strcat(str1,str2) concatenates a copy of the string pointed to by str2 to the the

string pointed to by str1 and terminates str1 with a null. The first character of str2 overwrites

the null terminator originally ending sr1. The str2 is untouched by the operation.In this

function we will pass two arguments str1,str2 as parameters.

For example, Consider this program

#include<stdio.h>

#include<conio.h>

int main()

{

char str1[30]="www.cprogramming";

char str2[15]="expert.com";

clrscr();

printf("%d\t%d\nn",strlen(str1),strlen(str2));

printf("\n\nstrcat(str1,str2) : %s\n\n",strcat(str1,str2));

printf("\n\nstr1 : %s\t\tstr2 : %s\n\n",str1,str2);

getch();

return 0;

}

Here

str1[30]= www.cprogramming and str2[15]=expert.com

if we are using function as strcat(str1,str2) and print the output. It will be

www.cprogrammingexpert.com.

i.e the last character in the first parameter get erased and second parameter concatenated in

memory str1 is stored like this "www.cprogramming\0" and str2 like this "expert.com\0" after

concatenation str1 is "www.cprogrammingexpert.com\0" and str2 is"expert.com\0".

So make sure that the size of str1 is large enough to accomodate all the characters in str1 and

str2.

str1[0] <- 'w'

str1[1] <- 'w'

str1[2] <- 'w'

str1[3] <- '.'

str1[4] <- 'c'

str1[5] <- 'p'

str1[6] <- 'r'

str1[7] <- 'o'

str1[8] <- 'g'

str1[9] <- 'r'

str1[10] <-'a'

str1[11] <-'m'

str1[12] <-'m'

str1[13] <-'i'

str1[14] <-'n'

str1[15] <-'g'

Page 76: Learn C Programming Step by Step

P a g e | 75

str1[16] <- '\0'

str1[17] <- 'garbage value'

str1[18] <- 'garbage value'

str1[19] <- 'garbage value'

str1[20] <- 'garbage value'

str1[21] <- 'garbage value'

str1[22] <- 'garbage value'

str1[23] <- 'garbage value'

str1[24] <- 'garbage value'

str1[25] <- 'garbage value'

str1[26] <- 'garbage value'

str1[27] <- 'garbage value'

str1[28] <- 'garbage value'

str1[29] <- 'garbage value'

str2 is

str2[0] <- 'e'

str2[1] <- 'x'

str2[2] <- 'p'

str2[3] <- 'e'

str2[4] <- 'r'

str2[5] <- 't'

str2[6] <- '.'

str2[7] <- 'c'

str2[8] <- 'o'

str2[9] <- 'm'

str2[10] <- '\0'

str2[11] <- 'garbage value'

str2[12] <- 'garbage value'

str2[13] <- 'garbage value'

str2[14] <- 'garbage value'

After concatenation

str1[0] <- 'w'

str1[1] <- 'w'

str1[2] <- 'w'

str1[3] <- '.'

str1[4] <- 'c'

str1[5] <- 'p'

str1[6] <- 'r'

str1[7] <- 'o'

str1[8] <- 'g'

str1[9] <- 'r'

str1[10] <-'a'

str1[11] <-'m'

str1[12] <-'m'

str1[13] <-'i'

str1[14] <-'n'

str1[15] <-'g'

str1[16] <- 'e'

str1[17] <- 'x'

str1[18] <- 'p'

str1[19] <- 'e'

str1[20] <- 'r'

str1[21] <- 't'

str1[22] <- '.'

str1[23] <- 'c'

str1[24] <- 'o'

str1[25] <- 'm'

Page 77: Learn C Programming Step by Step

P a g e | 76

str1[26] <- '\0'

str1[27] <- 'garbage value'

str1[28] <- 'garbage value'

str1[29] <- 'garbage value'

In this example I have declared size of str1 equal to 30 and str2 equal to 15.

Now you may think why I have declared str1 as 30 and str2 as 15. It's just because I want you to

undestand the concepts .OK

So if you know exact size of the string declare that size to save memory. Here str1[27] is enough,

str2[11] is enough.

One more thing , what will happen if you are declaring the string like char *str1,*str2 , here no

garbage values will come.

Before concatenation size of str1 is 16 & str2 is 10 and a fter concatenation size of str1 is 26 & str2 is

10. so we Saved memory.

Example:

Page 78: Learn C Programming Step by Step

P a g e | 77

5. strncat()

Syntax:

#include<string.h>

char *strncat( char *str1, const char *str2,size_t count );

strncat(str1,str2,n) concatenates not more than n characters of the string pointed

to by str2 to the the string pointed to by str1 and terminates str1 with a null. The first

character of str2 overwrites the null terminator originally ending sr1. The str2 is untouched

by the operation.

Example:

Page 79: Learn C Programming Step by Step

P a g e | 78

6. strcpy()

Syntax:

#include<string.h>

char *strcpy( char *to, const char *from );

strcpy(str1,str2) copies the string pointed to by str2 to the string pointed to by

str1 and terminates str1 with a null. The str2 must be a pointer to a null terminated string.

Example:

Page 80: Learn C Programming Step by Step

P a g e | 79

7. strncpy()

Syntax:

#include<string.h>

char *strncpy( char *to, const char *from,size_t count );

strncpy(str1,str2,n) copies up to n characters from the string pointed to by str2 to

the string pointed to by str1 and terminates str1 with a null. The str2 must be a pointer to a

null terminated string.

Example:

Hi, There is a small

mistake in this

program. Do you

know ? Here is the

currect value of str1-

"experProgramming"

.

Page 81: Learn C Programming Step by Step

P a g e | 80

8. strcmp()

Syntax:

#include<string.h>

int strcmp( char *str1, char *str2 );

strcmp(str1,str2) compares str1 and str2 lexicographically .Returns a negative

value if str1<str2; 0 if str1 and str2 are identical; and positive value if str1>str2.

Example -1:

Example-2:

Page 82: Learn C Programming Step by Step

P a g e | 81

Example-3:

Page 83: Learn C Programming Step by Step

P a g e | 82

9. strcmpi()

Syntax:

#include<string.h>

int strcmpi( char *str1, char *str2 );

strcmpi(str1,str2) compares str1 and str2 lexicographically without regards to

case .Returns a negative value if str1<str2; 0 if str1 and str2 are identical; and positive value

if str1>str2.

Example:

Page 84: Learn C Programming Step by Step

P a g e | 83

10. strncmp()

Syntax:

#include<string.h>

int strncmp( char *str1, char *str2,int n );

strncmp(str1,str2,n) compares atmost n charactes of str2 to str1 lexicographically

.Returns a negative value if str1<str2; 0 if str1 and str2 are identical; and positive value if

str1>str2.

Example:

Page 85: Learn C Programming Step by Step

P a g e | 84

11. stricmp()

Syntax:

#include<string.h>

int stricmp( char *str1, char *str2 );

stricmp(str1,str2) compares str1 and str2 lexicographically without regards to

case .Returns a negative value if str1<str2; 0 if str1 and str2 are identical; and positive value

if str1>str2.

Example:

Page 86: Learn C Programming Step by Step

P a g e | 85

12. strncmpi()

Syntax:

#include<string.h>

int strncmpi( char *str1, char *str2 ,int n);

strncmpi(str1,str2,n) compares at most n characters of str2 to

str1,lexicographically,by ignoring case. Returns a negative value if str1<str2; 0 if str1 and

str2 are identical; and positive value if str1>str2.

Example:

Page 87: Learn C Programming Step by Step

P a g e | 86

13. strchr()

Syntax:

#include<string.h>

char *strchr( const char *str, int ch );

strchr(str,ch) finds ch in str. Returns a pointer to the first occurrence of the

character ch in str, if ch does not occur in str ,strchr returns NULL.

Example:

Page 88: Learn C Programming Step by Step

P a g e | 87

14. strnicmp()

Syntax:

#include<string.h>

int strnicmp( char *str1, char *str2 ,int n);

strnicmp(str1,str2,n) compares at most n characters of str2 to

str1,lexicographically,by ignoring case. Returns a negative value if str1<str2; 0 if str1 and

str2 are identical; and positive value if str1>str2.

Example:

Page 89: Learn C Programming Step by Step

P a g e | 88

15. strstr()

Syntax:

#include<string.h>

char *strstr( const char *str1, const char *str2 );

strstr(str1,str2) finds the first occurrence of substring str2 in str1.Returns a pointer

to the elements in str1 that contain str2, or NULL if str2 does not occur in str1.

Example:

Page 90: Learn C Programming Step by Step

P a g e | 89

16. strset()

It is one of many string functions available. For using string functions we need to include

string library.In this function we pass 2 parameters namely a string and a character. When

this function is called it will replace all the characters in the string by the specified character.

While counting it will take blank spaces also.

Syntax of strset function is

#include<string.h>

char *strset( const char *str,char ch );

strset(str,ch) set all character in str to ch. quits when the first null character is

found. Returns a pointer to str.

Example:

Page 91: Learn C Programming Step by Step

P a g e | 90

17. strnset()

Syntax:

#include<string.h>

char *strnset( const char *str,char ch ,int n);

strnset(str,ch,n) set the first n character of str to ch. quits when the first null

character is found. Returns a pointer to str.

Example:

Page 92: Learn C Programming Step by Step

P a g e | 91

18. strrev()

Syntax:

#include<string.h>

char *str( char *str);

strrev(str) reverses all characters in str(except for the terminating null ). Returns a

pointer to the reversed string.

Example:

Page 93: Learn C Programming Step by Step

P a g e | 92

Functions

A number of statements grouped into a single logical unit are called a function.

The use of function makes programming easier since repeated statements can be grouped into

functions. Splitting the program into separate function make the program more readable and

maintainable.

It is necessary to have a single function ‘main’ in every C program, along with

other functions used/defined by the programmer.

A function definition has two principal components: the function header and body

of the function. The function header is the data type of return value followed by function

name and (optionally) a set of arguments separated by commas and enclosed in parenthesis.

Associated type to which function accepts precedes each argument. In general terms function

header statement can be written as

return_type function_name (type1 arg1,type2 arg2,..,typen argn)

where return_type represents the data type of the item that is returned by the

function, function_name represents the name of the function, and type1,type2,…,typen

represents the data type of the arguments arg1,arg2,..,argn.

Example: Following function returns the sum of two integers.

int add(int p,int q)

{

return p+q; //Body of the function

}

Here p and q are arguments. The arguments are called formal arguments or formal

parameters, because they represent the name of the data item that is transferred into the

function from the calling portion of the program. The corresponding arguments in the

function call are called actual arguments or actual parameters, since they define the data

items that are actually transferred.

A function can be invoked whenever it is needed. It can be accessed by

specifying its name followed by a list of arguments enclosed in parenthesis and separated by

commas.

e.g., add(5,10);

The following condition must be satisfied for function call.

The number of arguments in the function calls and function declaration must be same.

The prototype of each of the argument in the function call should be same as the

corresponding parameter in the function declaration statement.

For example, the following program makes use of function that determine the sum of two

integer quantities.

Page 94: Learn C Programming Step by Step

P a g e | 93

The line of the function contains the function name, ‘add’ followed by formal

arguments p and q, enclosed in parenthesis. The formal arguments p and q represents the data

item that are transferred to the function from the calling portion of the program (i.e., add (a,

b)). In addition, the formal arguments p and q are preceded by the data type int. i.e., it only

accepts integers. When we execute this program the content of the variables a and b are

copied to the formal arguments p and q respectively and the function returns the sum of p and

q and is assigned to the variable c in the left side of the calling function.

A function may or may not return a value. A ‘return’ statement returns some

value to the calling function and it may be assigned to the variable in the left side of the

calling function. The return value can be a constant, variable, a user defined data structure, a

general expression, a pointer to function, or a function call. The return statement also causes

the program logic to return to the point from which the function was accessed. In general

term the return statement is written as

return expression;

If a function does not return a value, the return type in the function definition and

declaration is specified as void. The declaration for a prototype for a function that receive any

arguments from the calling function and does not return any value will have the format

void function_name (void);

The above program can be rewrite as

#include <stdio.h>

#include <conio.h>

int add(int p,int q); // function prototype

void display(int p, int q, int r); // function prototype

int main()

{

int a,b,c;

Page 95: Learn C Programming Step by Step

P a g e | 94

clrscr();

printf("Enter two numbers\n");

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

c=add(a,b);

display(a,b,c);

getch();

return 0;

}

int add(int p,int q) //This function returns sum of a and b.

{

return(p+q);

}

void display(int p, int q, int r). //This function returns nothing

{

printf("Sum of %d and %d is %d",p,q,r);

}

Page 96: Learn C Programming Step by Step

P a g e | 95

1. Pass by value

Arguments can be passed to a function by two methods, They are

1. pass by value

2. pass by reference

Function in C passes all arguments by value. 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.

Example:

Page 97: Learn C Programming Step by Step

P a g e | 96

2. Pass by Reference

When passing by reference technique is used, the address of the data item is passed

to the called function. Using & operator we can determine the address of the data item. Note

that function once receives a data item by reference, it acts on data item and the changes

made to the data item also reflects on the calling function. Here you don't need to return

anything to calling function.

Example:

Page 98: Learn C Programming Step by Step

P a g e | 97

3. Recursion

Recursive functions are those functions, which call itself within that function. A

recursive function must have the following type of statements.

A statement to test and determine whether the function is calling itself again.

A statement that calls the function itself and must be argument.

A conditional statement (if-else)

A return statement.

Example: Factorial of a number

This is the most famous program on recursion. Many versions of this program are

available. All programs differ only in checking conditions. I prefer to write like the following

one.

Page 99: Learn C Programming Step by Step

P a g e | 98

Storage Class

1. static storage class

A variable is declared to be static by prefixing its normal declaration with the

keyword static, as in

static int a;

since the property of a variable may be stated in any order we could also use

int static a;

Static variables can be declared within a function. These variables retain their values

from the previous call. i.e., the value that they had before returning from the function. This is

illustrated in the following example.

Page 100: Learn C Programming Step by Step

P a g e | 99

2. Register storage class

Physical storage space can be a variable that is the main storage. With access to the registers

in the CPU is faster than main memory, a register variable to register the specified variable is

the physical storage space of variables. However, they require that as much as possible to

ensure the register, the register guarantee is not necessarily secure.

Register variables are stored in the register of the microprocessor. The number of

variable which can be declared register are limited. This means that the variable has a

maximum size equal to the register size. If more variables are declared as register variable,

they are treated as auto variables. A program that uses register variables executes faster as

compared to similar program without register variable.

To declare a variable register storage class register specified.

register int n;

Example for register variables :

Page 101: Learn C Programming Step by Step

P a g e | 100

3. Automatic storage class or variables

Automatic variables are allocated space in the variable on the stack. To declare a

variable automatic storage class auto specified.

eg: auto int n;

When you declare a variable, if the omitted variable storage class is automatic.

eg: int n;

When you declare an automatic variable initialization to be made explicit initial value is

undefined.

The scope of an automatic variable is only for the block, or any block within the block, in

which it appears. All variables declared within a function are auto by default. A variable can

be defined as automatic by placing the keyword auto at the beginning of the variable

declaration.

Example: auto int a;

Page 102: Learn C Programming Step by Step

P a g e | 101

4. External Storage class or Global

variable

External variables are global to the file in which they are defined. External

variables are used only when all functions needed a particular variable. It retains the

assigned value within the scope. In the following program variable i is an external variable.

Page 103: Learn C Programming Step by Step

P a g e | 102

Structure

A structure is a user defined data type. We know that arrays can be used to

represent a group of data items that belong to the same type, such as int or float. However we

cannot use an array if we want to represent a collection of data items of different types using

a single name. A structure is a convenient tool for handling a group of logically related data

items.

The syntax of structure declaration is

struct structure_name

{

type element 1;

type element 2;

……………..

type element n;

};

In structure declaration the keyword struct appears first, this followed by

structure name. The member of structure should be enclosed between a pair of braces and it

defines one by one each ending with a semicolon. It can also be array of structure. There is an

enclosing brace at the end of declaration and it end with a semicolon.

We can declare structure variables as follows

struct structure_name var1,var2,…..,var n;

For Example:

To store the names, roll number and total mark of a student you can declare 3

variables. To store this data for more than one student 3 separate arrays may be declared.

Another choice is to make a structure. No memory is allocated when a structure is declared. It

just defines the “form” of the structure. When a variable is made then memory is allocated.

This is equivalent to saying that there's no memory for “int” , but when we declare an integer

that is. int var; only then memory is allocated. The structure for the above-mentioned case

will look like

struct student

{

int rollno;

char name[25];

float totalmark;

};

We can now declare structure variables stud1, stud2 as follows

struct student stud1,stud2;

Thus, the stud1 and stud2 are structure variables of type student. The above structure can

hold information of 2 students.

Page 104: Learn C Programming Step by Step

P a g e | 103

It is possible to combine the declaration of structure combination with that

of the structure variables, as shown below.

struct structure_name

{

type element 1;

type element 2;

……………..

type element n;

}var1,var2,…,varn;

The following single declaration is equivalent to the two declaration

presented in the previous example.

struct student

{

int rollno;

char name[25];

float totalmark;

} stud1, stud2;

The different variable types stored in a structure are called its members.

The structure member can be accessed by using a dot (.) operator, so the dot operator is

known as structure member operator.

Example:

In the above example stud1 is a structure variable of type student. To

access the member name, we would write

stud1.name

Similarly, stud1’s rollno and stud1’s totalmark can be accessed by writing

stud1.rollno And

stud1.totalmark

Initializing Structure Members

Structure members can be initialized at declaration. This much the same manner as the

element of an array; the initial value must appear in the order in which they will be assigned

to their corresponding structure members,enclosed in braces and seperated by commas .The

general form is

struct stucture_name var={val1,val2,val3…..};

Example:

#include <stdio.h>

#include<conio.h>

int main()

{

struct student

{

char *name;

int rollno;

float totalmark;

Page 105: Learn C Programming Step by Step

P a g e | 104

};

struct student stud1={"Ashraf",1,98};

struct student stud3= {"Rahul",3,97};

struct student stud2={"Vineeth",2,99};

clrscr();

printf("STUDENTS DETAILS:\nRoll number:%d\n\nName:%s\n\nTotel

mark:%.2f\n",stud1.rollno,stud1.name,stud1.totalmark);

printf("\nRoll number:%d\n\nName:%s\n\nTotel

mark:%.2f\n",stud2.rollno,stud2.name,stud2.totalmark);

printf("\nRoll number:%d\n\nName:%s\n\nTotel

mark:%.2f\n",stud3.rollno,stud3.name,stud3.totalmark);

getch();

return 0;

}

Array of structures:

It is possible to store a structure has an array element. i.e., an array in which

each element is a structure. Just as arrays of any basic type of variable are allowed, so are

arrays of a given type of structure. Although a structure contains many different types, the

compiler never gets to know this information because it is hidden away inside a sealed

structure capsule, so it can believe that all the elements in the array have the same type, even

though that type is itself made up of lots of different types.

The declaration statement is given below.

struct struct_name

{

type element 1;

type element 2;

……………..

type element n;

}array name[size];

Example:

struct student

{

int rollno;

char name[25];

float totalmark;

} stud[100];

In this declaration stud is a 100-element array of structures. Hence, each

element of stud is a separate structure of type student. An array of structure can be assigned

initial values just as any other array. So the above structure can hold information of 100

students.

program:

#include <stdio.h>

#include <conio.h>

Page 106: Learn C Programming Step by Step

P a g e | 105

int main()

{

struct student

{

int rollno;

char name[25];

int totalmark;

}stud[100];

int n,i;

clrscr();

printf("Enter total number of students\n\n");

scanf("%d",&n);

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

{

printf("Enter details of %d-th student\n",i+1);

printf("Name:\n");

scanf("%s",&stud[i].name);

printf("Roll number:\n");

scanf("%d",&stud[i].rollno);

printf("Total mark:\n");

scanf("%d",&stud[i].totalmark);

}

printf("STUDENTS DETAILS:\n");

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

{

printf("\nRoll number:%d\n",stud[i].rollno);

printf("Name:%s\n",stud[i].name);

printf("Totel mark:%d\n",stud[i].totalmark);

}

getch();

return 0;

}

Structure as structure member:

A structure can have one or more of its member as another structure, but a

structure cannot be member to itself when a structure is used as structure member. In such

situation, the declaration of the embedded structure must appear before the declaration of the

outer structure. For example

#include <stdio.h>

#include <conio.h>

int main()

{

struct dob

{

int day;

int month;

int year;

};

Page 107: Learn C Programming Step by Step

P a g e | 106

struct student

{

struct dob d;

int rollno;

char name[25];

int totalmark;

}stud[25];

int n,i;

clrscr();

printf("Enter total number of students\n\n");

scanf("%d",&n);

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

{

printf("\nEnter details of %d-th student\n\n",i+1);

printf("\nName:\n");

scanf("%s",&stud[i].name);

printf("\nRoll number:\n");

scanf("%d",&stud[i].rollno);

printf("\nTotal mark:\n");

scanf("%d",&stud[i].totalmark);

printf("\nDate of birth (Format:01 06 2010):\n");

scanf("%d%d%d",&stud[i].d.day,&stud[i].d.month,&stud[i].d.year);

}

printf("STUDENTS DETAILS:\n");

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

{

printf("\n\nRoll number:%d\n\n",stud[i].rollno);

printf("Name:%s\n\n",stud[i].name);

printf("Totel mark:%d\n\n",stud[i].totalmark);

printf("Date of birth:%d / %d / %d

\n\n",stud[i].d.day,stud[i].d.month,stud[i].d.year);

}

getch();

return 0;

}

Page 108: Learn C Programming Step by Step

P a g e | 107

Union

Union is a data type with two or more member similar to structure but in this

case all the members share a common memory location. The size of the union corresponds to

the length of the largest member. Since the member share a common location they have the

same starting address.

The real purpose of unions is to prevent memory fragmentation by arranging for

a standard size for data in the memory. By having a standard data size we can guarantee that

any hole left when dynamically allocated memory is freed will always be reusable by another

instance of the same type of union. This is a natural strategy in system programming where

many instances of different kinds of variables with a related purpose and stored dynamically.

A union is declared in the same way as a structure.The syntax of union

declaration is

union union_name

{

type element 1;

type element 2;

……………..

type element n;

};

This declares a type template. Variables are then declared as:

union union_name x,y,z;

For example, the following code declares a union data type called Student

and a union variable called stud:

union student

{

int rollno;

float totalmark;

};

union student stud;

It is possible to combine the declaration of union combination with that of

the union variables, as shown below.

union union_name

{

type element 1;

type element 2;

……………..

type element n;

}var1,var2,…,varn;

The following single declaration is equivalent to the two declaration

presented in the previous example.

Page 109: Learn C Programming Step by Step

P a g e | 108

union student

{

int rollno;

float totalmark;

}x,y,z;

Exercise: Compare structure and Union

Structure:

Union:

Page 110: Learn C Programming Step by Step

P a g e | 109

Page 111: Learn C Programming Step by Step

P a g e | 110

Pointers

Pointer is a variable that represents the location of a data item, such as

variable or an array element. Within the computer’s memory, every stored data item occupies

one or more contiguous memory cells. The number of memory cells required to store a data

item depends on the type of the data item. For example, a single character will typically be

stored in one byte of memory; an integer usually requires two contiguous bytes, a floating-

point number usually requires four contiguous bytes, and a double precision usually requires

eight contiguous bytes.

Suppose v is a variable that represents some particular data item. The

compiler will automatically assign memory cells to this data item. The data item can then be

accessed if we know the address of the first memory cell. The address of v’s memory location

can be determined by the expression &v, where & is the unary operator, called the address

operator, that evaluates the address of its operand.

Now let us assign the address of v to another variable pv. Thus pv = &v;

This new variable is called pointer to v. since it “points to” the location where v is stored in

address, not its value. Thus pv is referred to as a pointer variable. The relationship between

pv and v is illustrated in the following figure.

Address of V-----------> Value of V

The data item represented by v. (i.e. the data item stored in v’s memory cells)

can be accessed by the expression *pv where * is a unary operator called the indication

operator, that operates only on a pointer variable. Therefore, *pv and v both represent the

same data item.

The address operator (&) and indirection operator(*) are unary operators and

they are the members of the same precedence group as the other unary operators. The address

operator (&) must act upon operands that associated with unique address, such as ordinary

variable or single array element. Thus the address operators cannot act upon arithmetic

expressions. The indirection operator can only act upon operands that are pointers (e.g.,

pointer variables).

Pointer declaration:

Pointer variables, like all other variables, must be declared before, they may

be used in C program. When a pointer variable is declared, the variable name must be

preceded by an asterisk(*). This identifies the fact that the variable is a pointer. The data type

that appears in the declaration refers to the object of the pointer. i.e. the data item that is

stored in the address represented by the pointer, rather than the pointer itself. Thus a pointer

declaration may be written in general terms as :

Data-type *ptr;

Where ptr is the name of the pointer variable, and data-type refers to the data type of the

pointer object.

Page 112: Learn C Programming Step by Step

P a g e | 111

For example, a C program contains the following declarations.

int i,*ptri;

float f,*ptrf;

The first line declares i to be an integer type variable and ptri to be a pointer

variable whose object is an integer quantity. The second line declares f to be a floating-point

type variable and ptrf to be a pointer variable whose object is a floating point quantity.

Within a variable declaration, a pointer variable can be initialized by

assigning in the address of another variable, remember that the variable whose address is

assigned to the pointer variable must have been declared earlier in the program, for example,

int i;

int *ptri=&i;

The first line declares i to be integer type variable and the second line

declares ptri to be a pointer variable whose object is an integer point quantity. In addition, the

address of i is initially assigned to ptri.

The following program illustrates the use of pointer variable.

Operation possible with pointers

C language allows arithmetic operations performed on pointer variables.

The arithmetic operations available for use with pointer can be classified as

Page 113: Learn C Programming Step by Step

P a g e | 112

Unary operator: ++ (increment) and --

Binary operator; +(addition) and –(subtraction)

The size of pointer variable depends on the data type of the variable pointed

to by the pointer.

Example:

If the pointer to an integer is incremented using the ++ operator, then the

address contained in the pointer is incremented by two and not one, assuming that an integer

occupies two bytes in memory. Similarly if the pointer points to a floating point variable the

use of ++ operator increments the address by four. In general a pointer to some data

type d_type when incremented by an integer value i then the result will have the following

value.

The following program illustrates this.

I think you have already studied functions, now let's see how it works with

pointers.

Page 114: Learn C Programming Step by Step

P a g e | 113

Page 115: Learn C Programming Step by Step

P a g e | 114

Dynamic memory allocation

So far we are working with fixed variables, we do not release the user to create

different variables according to their interest. It's a bit difficult to explain well, so give an

example: imagine you want to do a text encoder, you do not know how much space you will

need in memory until the user gets the text, which can be a word or an entire book. The

solution is to put a rookie char [10000], but even so we can be short, and if you have to

decode a word, it goes up too much space. We need to change the variables and create them

according to what happens, right? That is what this lesson.

ie, Dynamic memory allocation is the practice of assigning memory locations to

variables during execution of the program by explicit request of the programmer. Dynamic

allocation is a unique feature to C (amongst high level languages). It enables us to create data

types and structures of any size and length to suit our programs need within the program.

For example, to use arrays, dynamic memory allocation and use, eliminating the

need to determine the size of the array at declaration time. What do I say it is that extra space

does not have to. Areas that could use up to 1000 minutes, but you know, actually do not

know how much is used, the worst case, might well end up without one. In such cases, to

specify precisely the number of elements in the declaration is a very difficult time. If too

much waste of memory, and the less accessible outside of the array, may result in an error.

Dynamically allocated memory is freed when finished should not be used without.

When released, this area no longer use that system to manage memory (OS) and I'll tell it to.

When you exit the program without a release, essentially freed automatically. But I say with

certainty, it should be freed by calling a dedicated function explicitly.

Finally, the dynamically allocated memory area, the area is secured in a location

different from the usual definition of a variable. There is also the name depending on the role

of memory space and just go. Used in the dynamic memory allocation area is called the heap.

In contrast, the variables are usually allocated to the location of the stack. Variables are

allocated on the heap, even if it was secured out of the scope, continues to exist. For example,

in function, if you create a dynamic variable, but missing out the function and will continue

to exist on the heap.

The functions malloc (), realloc (), calloc () and free (), the Library functions

stdlib.h, malloc.h or are responsible for this task. All data are stored in the free store (heap),

which is limited to 64k a stack in the beginning, this varies from machine. All variables were

declared so far on the stack, now you tell me where to go, in an indirect way.

The following functions are used in c for purpose of memory management.

1. malloc()

2. calloc()

3. realloc()

4. free()

Page 116: Learn C Programming Step by Step

P a g e | 115

1.malloc()

The malloc() function dynamically allocates memory when required. This function

allocates ‘size’ byte of memory and returns a pointer to the first byte or NULL if there is

some kind of error.span>

Format is as follows.

void * malloc (size_t size);

Specifies in bytes the size of the area you want to reserve the argument. It returns the address

as the return value of the dynamically allocated area. In addition, returns NULL if it fails to

secure the area. The failure to ensure that the situation is usually that is out of memory.

The return type is of type void *, also receive the address of any type. The fact is used as

follows.

double * p = (double *) malloc (sizeof (double));

The size of the area using the sizeof operator like this. The return value is of type void *,

variable in the receiving side can be the pointer of any type in the host language C language

called C + +, the pointer type to other type void * is, without casting, so can not be assigned,

Use a cast. In C, a pointer type to void * type from another, so that the cast

automatically, there is no need to explicitly cast originally.Of course, should not write

because not explicitly given as well as portability to C + +, I wrote better.

In addition, the secured area is unknown at this point that's on it? That is the same as a

normal state to declare a local variable. Thus, with reference values ??must not be left

without initialization.

With this feature, you get a pointer to an allocated block of memory. Its structure is:

code:

pointer = (type) malloc (size in bytes);

An example:

code:

int * p;

p = (int *) malloc (sizeof (int));

* p = 5;

First we declare a pointer, which is still pointing nowhere. Then the pointer, not the content

but the pointer itself is equal to a pointer type int that contains the memory address space for

an int. Sizeof () gets the space it occupies what you want, if you put int in, such as 2 bytes,

because we have assigned two bytes. This feature also serves to get the size of pointers,

variables, or whatever it takes.

Finally, now that the pointer is contained, we give a value.

Page 117: Learn C Programming Step by Step

P a g e | 116

For example:

int *ptr = malloc(sizeof(int) * 10); // allocates 10 ints!

If it is unable to find the requested amount of memory, malloc() function returns

NULL. So you should really check the result for errors:

int *ptr = malloc(sizeof(int) * 5000);

if (ptr == NULL)

{

printf(" Out of memory!\n");

exit(1);

}

There are only two ways to get allocated memory back. They are exit from the

program and calling free() to free function. If your program runs a while and keeps

malloc()ing and never free()ing when it should, it is said to “leak” memory. Make sure to

avoid memory leaks! free() that memory when you are done with it!

The following example illustrates the use of malloc() function.

Page 118: Learn C Programming Step by Step

P a g e | 117

Page 119: Learn C Programming Step by Step

P a g e | 118

2. calloc() function

The calloc function is used to allocate storage to a variable while the program is

running. 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 and it allocates memory block equivalent to num * size . The function returns a pointer

to the beginning of the allocated storage area in memory. 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.

calloc function is used to reserve space for dynamic arrays. Has the following form.

void * calloc (size_t n, size_t size);

Number of elements in the first argument specifies the size in bytes of one element to the

second argument. A successful partitioning, that address is returned, NULL is returned on

failure.

For example, an int array of 10 elements can be allocated as follows.

int * array = (int *) calloc (10, sizeof (int));

Note that this function can also malloc, written as follows.

int * array = (int *) malloc (sizeof (int) * 10);

However, the malloc function, whereas the area reserved to the states that are undefined, the

area allocated by the calloc function contains a 0. In fact, the calloc function is internally may

be a function that calls malloc. After securing function by malloc, the area is filled with 0.

ptr = malloc(10 * sizeof(int)); is just like this:

ptr = calloc(10, sizeof(int));

The following example illustrates the use of

Page 120: Learn C Programming Step by Step

P a g e | 119

calloc() function.

When you release the space allocated by calloc function, use the free function of course.

Page 121: Learn C Programming Step by Step

P a g e | 120

3. realloc()

With the function realloc, you can change the size of the allocated area once. Has the

following form.

void * realloc (void * ptr, size_t size);

The first argument specifies the address of an area that is currently allocated to the size in

bytes of the modified second argument. Change the size, the return value is returned in re-

allocated address space. Otherwise 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.

The address of the source address changed, but the same could possibly be different, even if

the different areas of the old style, because it is automatically released in the function realloc,

for the older areas it is not necessary to call the free function. However, if the function fails

and returns NULL, realloc, the older area is to remain still valid. Therefore, the first pointer

argument of the function realloc, both can be NULL pointer return value is not returned.

# Include

int main (void)

{

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 can not use / * To do something * /

free (p2);

return 0;

}

The realloc function is a very feature-rich functions. This is not the pros, cons and rather may

be better. For example, if a NULL pointer to the first argument passed to the malloc function

with the same behavior as the size specified in the second argument. Meanwhile, the second

argument to zero, the operation to free the space pointed to by the free function specified in

the first argument.

In other words, whatever the arguments, it is the sister supposed to mean something to the

result, which may not have to be an error with the error should really be something. In

particular, even in very common use, such as the following:

Page 122: Learn C Programming Step by Step

P a g e | 121

char * p2 = realloc (p1, size);

Happened, if the variable size is zero, this is not the same behavior as the function becomes

free. If it is NULL p1, is the handling function malloc. NULL and 0 respectively when and

what behavior is undefined.

In addition, the pointer argument to realloc function first must point to a secure area using

one of the functions malloc / calloc / realloc (if a NULL pointer may be, in which case the

above equal to the malloc function and so on).

Quite complex because, you have put a sample implementation of realloc function to aid

understanding.

void * realloc (void * ptr, size_t size)

{

char * p;

if (ptr == NULL)

{

return malloc (size); if the first argument is NULL / * * / function which works the same as

malloc }

if (size == 0)

{

free (ptr); second argument is 0 / * * / function which works the same as free

return NULL; * / return NULL because no new areas to be reserved * /

}

p = malloc (size); using the function / * malloc, * / a space equivalent to the size of the newer

if (p == NULL) {return NULL; if the function fails} / * malloc, return NULL. The original

area * / remain

memcpy (p, ptr, size); the data in the source area / * * / to be copied to newly allocated space

free (ptr); source area / * the * / to be released

return p; * / return the address of the beginning of a new space * / }

Here are the points you need to remember.

The contents of the object will remain unaltered up to the lesser of the new and old

sizes.

If the new size of the memory object would require movement of the object, the space

for the previous instantiation of the object is freed.

If the new size is larger, the contents of the newly allocated portion of the object are

unspecified.

If size is zero and ptr isn't a null pointer, the object pointed to is freed.

If the space can't be allocated, the object remains unaltered.

If ptr is a null pointer, realloc() acts like malloc() for the specified size.

Here's an example ,learn this example and then try applying the same idea to write your own

programs.

Page 123: Learn C Programming Step by Step

P a g e | 122

Page 124: Learn C Programming Step by Step

P a g e | 123

4. Dynamic memory allocation : free()

function

Next, how to release the reserved area, which will use the function free. Has also been

declared in stdlib.h, which has the following form.

void free (void * ptr);

The argument specifies the address of a dynamically allocated area. You can then free up the

space. Specify an address outside the area should not be dynamically allocated. Also, if you

specify a NULL (or NULL if the same holds for a given pointer variable), the free function is

guaranteed to do nothing at all. In addition, if you try to re-release has already been freed

space, so do not know what would be, and should never be.

In addition, the space freed by the function free, guarantee that there is no data remains

intact. Thus, if once released, should not be accessing the same area.

So, an example program that uses functions malloc and free functions in practice.

# Include

# Include

int main (void)

{

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 1;

}

* P = 150;

printf ("% d \ n", * p);

free (p); * / free area * /

return 0;

}

Critical applications such that the product should look into whether the failure to secure the

area. The method is to check the return value of malloc function as above. However, sample

programs, etc. are often omitted. Because such is unlikely to cause a shortage of modern

computer memory, that is not impossible.

In addition, the area again, once released, so that no access would, immediately after the

function, free, often take precautions to keep the pointer to NULL.

free (p);

p = NULL;

Page 125: Learn C Programming Step by Step

P a g e | 124

function free, attempt to free the same area more than once but should not, because nothing

happens when you specify a NULL, and that it's safe if you put it like this.

Of course, between the malloc() and the free(), you can do anything with the memory your

twisted little heart desires.

Let's see a simple example of the management of malloc and free:

# Include

int main ()

{

int bytes;

char * text;

printf ("How many bytes you want to book");

scanf ("% i", & bytes);

text = (char *) malloc (bytes);

/ * Check if the operation was successful * /

if (text)

{

printf ("Reserved memory:% i bytes =% i =% i Kbytes Mbytes \ n", bytes, bytes/1024, bytes /

(1024 * 1024 )) ;

printf ("The block starts at:% p \ n", text);

/ * Now free the memory * /

free (text);

}

else

printf ("Could not allocate memory \ n") ;

}

This example asks how much memory you want to book, if it can be shown how much

memory is reserved and where begins the block. Failure to achieve stated meniante the

message: "Failed to allocate memory."

Let's try this example reserving 1000 bytes:

How many bytes you want to book: 1000 Reserved Memory: 1000 bytes = 0 kb = 0 Mbytes

The block begins at: 90868

Try a few times by increasing the size of memory you want to book. If you 32Mbytes of

RAM type the following:

How many bytes you want to reserve: 32000000 Could not allocate memory Malloc has been

unable to reserve as much memory and returns (null) so we are warned that the operation

could not be performed.

Program:

Page 126: Learn C Programming Step by Step

P a g e | 125

Page 127: Learn C Programming Step by Step

P a g e | 126

File

1. fopen()

Declaration: FILE * fopen (const char *filename, const char *mode);

The fopen () function opens a file whose name is pointed to by ‘filename’ and

returns the stream that is associated with it. The type of operation that will be allowed on the

file are defined by the vale of mode. The legal values of modes are shown in the following

table.

File Type Meaning

“r” Open an existing file for reading only

“w” Open a new file for writing only. If a file with the specified file-name currently exists,

it will be destroyed and a new file created in its place.

“a”

Open an existing file for appending (i.e., for adding new information at the end of the

file). If a file with the specified file-name currently does not exist, a new file will be

created.

“r+” Open an existing file for both reading and writing.

“w+” Open a new file for both reading and writing. If a file with the specified file-name

currently exists, it will be destroyed and a new file created in its place.

“a+” Open an existing file for both reading and appending. If a file with the specified file-

name currently does not exist, a new file will be created.

If fopen () is successful in opening the specified file, a FILE pointer is

returned. If the file cannot be opened, a NULL pointer is required. The following code uses

fopen () to open a file named TEST for output.

FILE *fptr;

fptr = fopen(“TEST”,”w”);

Although the preceding code is technically correct, the following code fragment illustrates

the correct method of opening the file.

FILE *fptr;

if ((fptr = fopen (“TEST”,”w”))==NULL)

{

printf (“Cannot open file\n”);

exit (1);

}

Page 128: Learn C Programming Step by Step

P a g e | 127

This method detects any error in opening a file, such as write-protected or a

full disk before attempting to write to it. If no file by that name exists, one will be created.

Opening a file for read operations require that the file exists.

Page 129: Learn C Programming Step by Step

P a g e | 128

2. fclose()

Declaration: int fclose (FILE *stream);

The fclose function closes the file associated with stream and flushes its buffer

(i.e., it writes any data still remaining in the disk buffer to the file). After a call to fclose(),

stream is no longer connected with the file, and any automatically allocated buffers are de

allocated.

If fclose () is successful, zero is returned; otherwise EOF is returned.

For example, the following code opens and close a file:

#include<stdio.h>

#include<stdlib.h>

int main()

{

FILE *fptr;

If((fptr = fopen(“TEST”,”w”))==NULL)

{

printf(“Cannot open file\n”);

exit(1);

}

if(fclose(fptr))

pritf(“File close error\n”);

return o;

}

Page 130: Learn C Programming Step by Step

P a g e | 129

3. fputc()

Declaration: int fputc(int ch,FILE *stream);

The fputc() function writes the character ch to the specified stream at the current

file position and then advance the file position indicator. Even though the ch is declared to be

an int , it is converted by fputc() into an unsigned char.

The value returned by the fputc() is the value of the character written . if an

error occurs, EOF is returned.

For example, the following program writes to the specified stream.

#include <stdio.h>

#include<stdlib.h>

int main()

{

FILE *fptr;

char text[100];

int i=0;

clrscr();

printf(“Enter a text:\n”);

gets(text);

if((fptr = fopen(“TEST”,”w”))==NULL)

{

printf(“Cannot open file\n”);

exit(1);

}

while(text[i]!=’\0’)

fputc(text[i++],fptr);

if(fclose(fptr))

pritf(“File close error\n”);

getch();

return 0;

}

Page 131: Learn C Programming Step by Step

P a g e | 130

4. fgetc()

Declaration: int fgetc(FILE *stream);

The fgetc() function returns the next character from the specified input stream

and increments the file position indicator. The character is read as an unsigned char that is

converted to an integer. If the end-of-file is reached, fgetc() returns EOF. If fgetc()

encounters an error, EOF is also returned.

For example, the following program reads and displays the content of text

file.

#include<stdio.h>

#include<stdlib.h>

int main()

{

FILE *fptr;

If((fptr = fopen(“TEST”,”r”))==NULL)

{

printf(“Cannot open file\n”);

exit(1);

}

while((c=fgetc(fptr))!=EOF)

puchar(c);

if(fclose(fptr))

pritf(“File close error\n”);

return 0;

}

Page 132: Learn C Programming Step by Step

P a g e | 131

5. fputs()

Declaration: char * fputs(const char *str , FILE *stream);

The fputs() function writes the content of the string pointed to by str to the

specified stream. The null terminator is not written. The fputs() function returns non negative

on success and EOF on failure.

For example, the following program uses fputs() to write a string into a file.

#include<stdio.h>

#include<stdlib.h>

int main()

{

FILE *fptr;

char text[100];

int i=0;

clrscr();

printf(“Enter a text:\n”);

gets(text);

if((fptr = fopen(“TEST”,”w”))==NULL)

{

printf(“Cannot open file\n”);

exit(1);

}

fputs(text,fptr);

if(fclose(fptr))

pritf(“File close error\n”);

getch();

return 0;

}

Page 133: Learn C Programming Step by Step

P a g e | 132

6. fgets()

Declaration: char * fgets(char *str,int num, FILE *stream);

The fgets() function reads up to num-1character from stream and store them into

a character array pointed to by str. Characters are read until either a newline or an EOF is

received or until the specified limit is reached. After the character has been read, a null is

stored in the array immediately after the last character is read. A newline character will be

retained and will be a part of the array pointed to by str.

If successful, fgets() returns str; a null pointer is returned upon failure. If a

read error occurs, the content of the array pointed to by str are indeterminate.

For example, the following program uses fgets() to display the content of a file.

#include<stdlib.h>

#include <stdio.h>

int main()

{

FILE *fptr;

char text[100];

clrscr();

if((fptr = fopen(“TEST”,”r”))==NULL)

{

printf(“Cannot open file\n”);

exit(1);

}

fgets(text,100,fptr);

puts(text);

if(fclose(fptr))

pritf(“File close error\n”);

getch();

return 0;

}

Page 134: Learn C Programming Step by Step

P a g e | 133

7. fscanf()

Declaration: fscanf (FILE *stream, const char *format,…..);

The fscanf function works exactly like the scanf function except that it reads the

information from the stream specified by stream instead of standard input device.

Page 135: Learn C Programming Step by Step

P a g e | 134

8. fprintf()

Declaration: fprintf (FILE *stream, const char *format,…..);

The fprintf() function outputs the values of the arguments that makes up the

argument list as specified in the format string to the stream pointed to by stream. The

operations of the format control string and command are identical to those in printf().

The following program uses the fprintf() and fscanf() function to prepare the

results of ‘n’ students.

#include<stdio.h>

int main()

{

int regno,m[5],tot,I,j,k,n;

char name[15];

float avg;

FILE * fptr;

if((fptr = fopen(“MARK”,”w”))==NULL)

{

printf(“Cannot open file\n”);

exit(1);

}

clrscr();

printf(“How many students?”);

scanf(“%d”,&n);

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

{

clrscr();

printf(“Enter the details of Student-%d\n\n”,i+1);

printf(“Name?”);

scanf(%[^\n],name);

printf(“Register Number?”);

scanf(%d,&regno);

for(tot=0,j=0;j<5;++j)

{

printf(“Mark in paper-%d?”,j+1);

scanf(%d,&m[j]);

tot+=m[j];

}

avg=(float)tot/5.0;

fprintf(fptr,”%15s%d%d%d%d%d%d%d%f\n”,name,regno,m[0], m[1],m[2],

m[3], m[4],tot,avg);

}

clrscr();

fclose(fptr);

if((fptr = fopen(“MARK”,”r”))==NULL)

{

printf(“Cannot open file\n”);

Page 136: Learn C Programming Step by Step

P a g e | 135

exit(1);

}

printf(“NAME\t\tReg.No\TM1 M2 M3 M4 M5 TOTAL AVERAGE RES”);

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

{

fscanf(fptr,”%-15s%d%d%d%d%d%d%d%f”,&name,&regno,&m[0],

&m[1],&m[2], &m[3], &m[4],&tot,&avg);

printf(”%15s%d%d%d%d%d%d%d%f\n”,name,regno,m[0], m[1],m[2], m[3],

m[4],tot,avg);

if(avg>35.0)

printf(“Passed”);

else

printf(“Failed”);

}

fclose(fptr);

getch();

return 0;

}

Page 137: Learn C Programming Step by Step

P a g e | 136

9. putc()

Declaration: int putc(int ch, FILE *stream);

The putc() function writes the character ch to the specified stream at the

current file position and then advance the file position indicator. Even though the ch is

declared to be an int, it is converted by putc() into an unsigned char.

The value returned by the putc() is the value of the character written . if an error

occurs, EOF is returned. The putc() and fputc() are identical.

For example, the following program writes a string to the specified stream.

#include <stdio.h>

#include <stdlib.h>

void main()

{

FILE *fptr;

char text[100];

int i=0;

clrscr();

printf(“Enter a text:\n”);

gets(text);

if((fptr = fopen(“TEST”,”w”))==NULL)

{

printf(“Cannot open file\n”);

exit(1);

}

while(text[i]!=’\0’)

putc(text[i++],fptr);

if(fclose(fptr))

pritf(“File close error\n”);

getch();

}

Page 138: Learn C Programming Step by Step

P a g e | 137

10. getc()

Declaration: int getc(FILE *stream);

The getc() function returns the next character from the specified input stream

and increment file position indicator. The character is read as an unsigned char that is

converted to an integer.

If the end-of-file is reached, getc() returns EOF. If getc() encounters an error,

EOF is also returned. The function getc() and fgetc() are identical.

For example, the following program reads and displays the contents of a text

file.

#include <stdio.h>

#include <stdlib.h>

int main()

{

FILE *fptr;

char c;

clrscr();

if((fptr = fopen(“TEST”,”r”))==NULL)

{

printf(“Cannot open file\n”);

exit(1);

}

while((c=getc(fptr))!=EOF)

putchar(c);

if(fclose(fptr))

pritf(“File close error\n”);

getch();

return 0;

}

Page 139: Learn C Programming Step by Step

P a g e | 138

Graphics

The following functions compose the Borland Graphics Interface and are usually available

for 16 bit DOS applications. Use them to create onscreen graphics with text. They are defined

in graphics.h.

#include<stdio.h>

#include<conio.h>

#include<graphics.h>

int main()

{

int gd=DETECT,gm;

initgraph(&gd,&gm,"f:\\tc\\bgi");

getch();

closegraph(); /* closes down the graphics system */

return 0;

}

#include<stdio.h>

#include<conio.h>

#include<graphics.h>

int main()

{

int gd=DETECT,gm,error;

initgraph(&gd,&gm,"f:\\tc\\bgi");

error = graphresult();

if (error != grOk)

{

printf("Graphics error occurred");

printf("Press any key to halt:");

getch(); /* wait for a key */

exit(1);

}

#include<stdio.h>

#include<conio.h>

#include<graphics.h>

int main()

{

int gd=DETECT,gm,error;

initgraph(&gd,&gm,"f:\\tc\\bgi");

error = graphresult();

if (error != grOk)

{

printf("Graphics error occurred");

printf("Press any key to halt:");

getch();

exit(1);

}

outtext("Welcome to Borland Graphics Interface");

/* output the message */

getch();

closegraph();

return 0;

}

Page 140: Learn C Programming Step by Step

P a g e | 139

//outtextxy

#include<stdio.h>

#include<conio.h>

#include<graphics.h>

int main()

{

int gd=DETECT,gm,error;

initgraph(&gd,&gm,"f:\\tc\\bgi");

error = graphresult();

if (error != grOk)

{

printf("Graphics error occurred");

printf("Press any key to halt:");

getch();

exit(1);

}

outtextxy(175,250,"Welcome to Borland Graphics Interface");

getch();

closegraph();

return 0;

}

#include<stdio.h>

#include<conio.h>

#include<graphics.h>

//outtextxy

int main()

{

int gd=DETECT,gm,error;

initgraph(&gd,&gm,"f:\\tc\\bgi");

error = graphresult();

if (error != grOk)

{

printf("Graphics error occurred");

printf("Press any key to halt:");

getch();

exit(1);

}

setbkcolor(BLUE);

outtextxy(175,250,"Welcome to Borland Graphics Interface");

getch();

closegraph();

return 0;

}

#include<stdio.h>

#include<conio.h>

#include<graphics.h>

int main()

{

int gd=DETECT,gm,i,error,maximumcolor;

initgraph(&gd,&gm,"f:\\tc\\bgi");

error = graphresult();

if (error != grOk)

{

printf("Graphics error occurred");

printf("Press any key to halt:");

Page 141: Learn C Programming Step by Step

P a g e | 140

getch();

exit(1);

}

maximumcolor = getmaxcolor();

for (i=0; i<=maximumcolor;i++)

{

setbkcolor(i);

outtextxy(175,250,"Welcome to Borland Graphics Interface");

outtextxy(getmaxx()-250,getmaxy()-40,"www.CProgrammingExpert.com");

getch();

}

getch();

closegraph();

return 0;

}

#include<stdio.h>

#include<conio.h>

#include<graphics.h>

int main()

{

int gd=DETECT,gm,i,error,maximumcolor;

char message[80];

initgraph(&gd,&gm,"f:\\tc\\bgi");

error = graphresult();

if (error != grOk)

{

printf("Graphics error occurred");

printf("Press any key to halt:");

getch();

exit(1);

}

maximumcolor = getmaxcolor();

for (i=0; i<=maximumcolor;i++)

{

setbkcolor(i);

sprintf(message, "Background color: %d",i); /* create a message string */

outtextxy(250, 240,message);

outtextxy(getmaxx()-250,getmaxy()-40,"www.CProgrammingExpert.com");

getch();

}

getch();

closegraph();

return 0;

}

#include<stdio.h>

#include<conio.h>

#include<graphics.h>

int main()

{

int gd=DETECT,gm,i,error,maximumcolor;

char message[80];

initgraph(&gd,&gm,"f:\\tc\\bgi");

error = graphresult();

if (error != grOk)

{

printf("Graphics error occurred");

printf("Press any key to halt:");

getch();

Page 142: Learn C Programming Step by Step

P a g e | 141

exit(1);

}

maximumcolor = getmaxcolor();

for (i=0; i<=maximumcolor;i++)

{

cleardevice(); /* clear the screen */

setbkcolor(i);

sprintf(message, "Background color: %d",i);

outtextxy(250, 240,message);

outtextxy(getmaxx()-250,getmaxy()-40,"www.CProgrammingExpert.com");

getch();

}

getch();

closegraph();

return 0;

}

#include<stdio.h>

#include<conio.h>

#include<graphics.h>

int main()

{

int gd=DETECT,gm,i,error,maximumcolor;

char message[80];

initgraph(&gd,&gm,"f:\\tc\\bgi");

error = graphresult();

if (error != grOk)

{

printf("Graphics error occurred");

printf("Press any key to halt:");

getch();

exit(1);

}

setbkcolor(BLUE);

maximumcolor = getmaxcolor();

for (i=0; i<=maximumcolor;i++)

{

cleardevice();

setcolor(i);

sprintf(message, "Graphics color: %d",i);

outtextxy(250, 240,message);

outtextxy(getmaxx()-250,getmaxy()-40,"www.CProgrammingExpert.com");

getch();

}

getch();

closegraph();

return 0;

}

#include<stdio.h>

#include<conio.h>

#include<graphics.h>

int main()

{

int gd=DETECT,gm,i,j=0,error,maximumcolor;

char message[80];

initgraph(&gd,&gm,"f:\\tc\\bgi");

error = graphresult();

if (error != grOk)

Page 143: Learn C Programming Step by Step

P a g e | 142

{

printf("Graphics error occurred");

printf("Press any key to halt:");

getch();

exit(1);

}

setbkcolor(BLUE);

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

{

/* select the text style, direction, and size */

settextstyle(SANS_SERIF_FONT, HORIZ_DIR, i);

sprintf(message, "Size: %d", i);

outtextxy(1,j, message);

/* advance to the next text line */

j += textheight(message);

}

getch();

closegraph();

return 0;

}

/* textwidth example */

#include<stdio.h>

#include<conio.h>

#include<graphics.h>

int main()

{

int gd=DETECT,gm,i,j=0,k=0,error,maximumcolor;

char message[80];

initgraph(&gd,&gm,"f:\\tc\\bgi");

error = graphresult();

if (error != grOk)

{

printf("Graphics error occurred");

printf("Press any key to halt:");

getch();

exit(1);

}

setbkcolor(BLUE);

j = getmaxy() / 2;

settextjustify(LEFT_TEXT, CENTER_TEXT);

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

{

settextstyle(SANS_SERIF_FONT, HORIZ_DIR, i);

sprintf(message, "Size: %d", i);

outtextxy(k, j, message);

/* advance to the end of the text */

k+= textwidth(message);

}

getch();

closegraph();

return 0;

}

#include<stdio.h>

#include<conio.h>

#include<graphics.h>

int main()

{

int gd=DETECT,gm,error;

char range[80];

Page 144: Learn C Programming Step by Step

P a g e | 143

initgraph(&gd,&gm,"f:\\tc\\bgi");

error = graphresult();

if (error != grOk)

{

printf("Graphics error occurred");

printf("Press any key to halt:");

getch();

exit(1);

}

setbkcolor(BLUE);

sprintf(range, "X values range from 0..%d", getmaxx());

outtextxy( getmaxx()/2,getmaxy()/2 ,range);

outtextxy(getmaxx()-250,getmaxy()-40,"www.CProgrammingExpert.com");

getch();

closegraph();

return 0;

}

#include<stdio.h>

#include<conio.h>

#include<graphics.h>

int main()

{

int gd=DETECT,gm,error;

char range[80];

initgraph(&gd,&gm,"f:\\tc\\bgi");

error = graphresult();

if (error != grOk)

{

printf("Graphics error occurred");

printf("Press any key to halt:");

getch();

exit(1);

}

setbkcolor(BLUE);

sprintf(range, "Y values range from 0..%d", getmaxy());

outtextxy( getmaxx()/2,getmaxy()/2 ,range);

outtextxy(getmaxx()-250,getmaxy()-40,"www.CProgrammingExpert.com");

getch();

closegraph();

return 0;

}

#include<stdio.h>

#include<conio.h>

#include<graphics.h>

//delay

int main()

{

int gd=DETECT,gm,error,i;

char message[80];

initgraph(&gd,&gm,"f:\\tc\\bgi");

error = graphresult();

if (error != grOk)

{

printf("Graphics error occurred");

Page 145: Learn C Programming Step by Step

P a g e | 144

printf("Press any key to halt:");

getch();

exit(1);

}

setbkcolor(BLUE);

for(i=0;i<=getmaxy();i++)

{

cleardevice();

sprintf(message, ".<<---(x=0,y=%d) :: www.CProgrammingExpert.com",i);

outtextxy( 0,i ,message);

delay(100);

}

getch();

closegraph();

return 0;

}

#include<stdio.h>

#include<conio.h>

#include<graphics.h>

//delay

int main()

{

int gd=DETECT,gm,error,i;

char message[80];

initgraph(&gd,&gm,"f:\\tc\\bgi");

error = graphresult();

if (error != grOk)

{

printf("Graphics error occurred");

printf("Press any key to halt:");

getch();

exit(1);

}

setbkcolor(BLUE);

for(i=0;i<=getmaxx();i++)

{

cleardevice();

sprintf(message, ".<<---(x=%d,y=10) :: www.CProgrammingExpert.com",i);

outtextxy( i,10 ,message);

delay(100);

}

getch();

closegraph();

return 0;

}

#include<stdio.h>

#include<conio.h>

#include<graphics.h>

int main()

{

int gd=DETECT,gm,i,error;

char message[80];

initgraph(&gd,&gm,"f:\\tc\\bgi");

error = graphresult();

if (error != grOk)

Page 146: Learn C Programming Step by Step

P a g e | 145

{

printf("Graphics error occurred");

printf("Press any key to halt:");

getch();

exit(1);

}

setbkcolor(BLUE);

for(i=1;i<=150;i+=10)

{

cleardevice();

arc (310,250,360-i, (360-i)+150,i);

//void arc (int x, int y, int startangle, int endangle, int radius);

outtextxy(getmaxx()-200,getmaxy()-100,"Center:(310,250)");

sprintf(message, "Radius : %d",i);

outtextxy(getmaxx()-200,getmaxy()-80,message);

sprintf(message, "Start angle : %d ",360-i);

outtextxy(getmaxx()-200,getmaxy()-60,message);

sprintf(message, "End angle : %d",(360-i)+150);

outtextxy(getmaxx()-200,getmaxy()-40,message);

getch();

}

cleardevice();

for(i=1;i<=150;i+=10)

arc (310,250,360-i, (360-i)+150,i);

outtextxy(getmaxx()-250,getmaxy()-40,"www.CProgrammingExpert.com");

getch();

closegraph();

return 0;

}

#include<stdio.h>

#include<conio.h>

#include<graphics.h>

int main()

{

int gd=DETECT,gm,error;

initgraph(&gd,&gm,"f:\\tc\\bgi");

error = graphresult();

if (error != grOk)

{

printf("Graphics error occurred");

printf("Press any key to halt:");

getch();

exit(1);

}

setbkcolor(BLUE);

bar (320,250, 250, 10);

outtextxy(getmaxx()-200,getmaxy()-100,"Left : 320");

outtextxy(getmaxx()-200,getmaxy()-80,"Top : 250");

outtextxy(getmaxx()-200,getmaxy()-60,"Right : 250");

outtextxy(getmaxx()-200,getmaxy()-40,"Bottom : 10");

outtextxy(getmaxx()-250,getmaxy()-20,"www.CProgrammingExpert.com");

getch();

closegraph();

return 0;

}

Page 147: Learn C Programming Step by Step

P a g e | 146

#include<stdio.h>

#include<conio.h>

#include<graphics.h>

int main()

{

int gd=DETECT,gm,error;

initgraph(&gd,&gm,"f:\\tc\\bgi");

error = graphresult();

if (error != grOk)

{

printf("Graphics error occurred");

printf("Press any key to halt:");

getch();

exit(1);

}

setbkcolor(BLUE);

bar3d(320,250, 250, 50,35,125);

outtextxy(getmaxx()-200,getmaxy()-140,"Left : 250");

outtextxy(getmaxx()-200,getmaxy()-120,"Top : 250");

outtextxy(getmaxx()-200,getmaxy()-100,"Right : 250");

outtextxy(getmaxx()-200,getmaxy()-80,"Bottom : 50");

outtextxy(getmaxx()-200,getmaxy()-60,"Depth : 35");

outtextxy(getmaxx()-200,getmaxy()-40,"Top Flag : 125");

outtextxy(getmaxx()-250,getmaxy()-20,"www.CProgrammingExpert.com");

getch();

closegraph();

return 0;

}

#include<stdio.h>

#include<conio.h>

#include<graphics.h>

int main()

{

int gd=DETECT,gm,i,error;

char message[80];

initgraph(&gd,&gm,"f:\\tc\\bgi");

error = graphresult();

if (error != grOk)

{

printf("Graphics error occurred");

printf("Press any key to halt:");

getch();

exit(1);

}

setbkcolor(BLUE);

for(i=10;i<=210;i+=10)

{

cleardevice();

circle (320, 250,i);

outtextxy(getmaxx()-200,getmaxy()-60,"Center : (320,250)");

sprintf(message, "Radius : %d",i);

outtextxy(getmaxx()-200,getmaxy()-40,message);

outtextxy(getmaxx()-250,getmaxy()-20,"www.CProgrammingExpert.com");

getch();

}

Page 148: Learn C Programming Step by Step

P a g e | 147

cleardevice();

for(i=10;i<=210;i+=10)

circle (320, 250,i);

outtextxy(getmaxx()-250,getmaxy()-20,"www.CProgrammingExpert.com");

getch();

closegraph();

return 0;

}

#include<stdio.h>

#include<conio.h>

#include<graphics.h>

int main()

{

int gd=DETECT,gm,error;

int poly[10],maxx, maxy;

initgraph(&gd,&gm,"f:\\tc\\bgi");

error = graphresult();

if (error != grOk)

{

printf("Graphics error occurred");

printf("Press any key to halt:");

getch();

exit(1);

}

setbkcolor(BLUE);

maxx = getmaxx();

maxy = getmaxy();

poly[0] = 30; /* first vertex */

poly[1] = maxy / 2;

poly[2] = maxx - 30; /* second vertex */

poly[3] = 30;

poly[4] = maxx - 75; /* third vertex */

poly[5] = maxy - 30;

poly[6] = maxx / 2; /* fourth vertex */

poly[7] = maxy / 2;

poly[8] = poly[0]; /* drawpoly doesn't automatically close */

poly[9] = poly[1]; /* the polygon, so we close it */

drawpoly(5, poly); /* draw the polygon */

outtextxy(getmaxx()-250,getmaxy()-20,"www.CProgrammingExpert.com");

getch();

closegraph();

return 0;

}

#include<stdio.h>

#include<conio.h>

#include<graphics.h>

int main()

{

int gd=DETECT,gm,poly[10],maxx, maxy,i,error;

initgraph(&gd,&gm,"f:\\tc\\bgi");

error = graphresult();

if (error != grOk)

{

printf("Graphics error occurred");

Page 149: Learn C Programming Step by Step

P a g e | 148

printf("Press any key to halt:");

getch();

exit(1);

}

setbkcolor(BLUE);

maxx = getmaxx();

maxy = getmaxy();

poly[0] = 30;

poly[1] = maxy / 2;

poly[2] = maxx - 30;

poly[3] = 30;

poly[4] = maxx - 75;

poly[5] = maxy - 30;

poly[6] = maxx / 2;

poly[7] = maxy / 2;

poly[8] = poly[0]; /* drawpoly doesn't automatically close */

poly[9] = poly[1];

for (i=EMPTY_FILL; i<="" pre="">

#include<stdio.h>

#include<conio.h>

#include<graphics.h>

int main()

{

int gd=DETECT,gm,error,i;

initgraph(&gd,&gm,"f:\\tc\\bgi");

error = graphresult();

if (error != grOk)

{

printf("Graphics error occurred");

printf("Press any key to halt:");

getch();

exit(1);

}

setbkcolor(BLUE);

line(0, 0, getmaxx(), getmaxy()); /* draw a line */

outtextxy(getmaxx()-250,getmaxy()-20,"www.CProgrammingExpert.com");

getch();

closegraph();

return 0;

}

Page 150: Learn C Programming Step by Step

P a g e | 149

#include<stdio.h>

#include<conio.h>

#include<graphics.h>

int main()

{

int gd=DETECT,gm,i,j,error;

char message[80];

initgraph(&gd,&gm,"f:\\tc\\bgi");

error = graphresult();

if (error != grOk)

{

printf("Graphics error occurred");

printf("Press any key to halt:");

getch();

exit(1);

}

setbkcolor(BLUE);

for(i=50,j=100;i<=100;i+=10,j+=20)

{

cleardevice();

ellipse (getmaxx()/2,getmaxy()/2,0,360,j+75, j); //<<<<<<<<<

line(getmaxx()/2,getmaxy()/2,(getmaxx()/2)+j+75,getmaxy()/2);

line(getmaxx()/2,getmaxy()/2,getmaxx()/2,(getmaxy()/2)-j);

sprintf(message, "Center (%d,%d)",getmaxx()/2,getmaxy()/2);

outtextxy(getmaxx()-200,getmaxy()-120,message);

outtextxy(getmaxx()-200,getmaxy()-100,"Start agle : 0");

outtextxy(getmaxx()-200,getmaxy()-80,"End angle : 360");

sprintf(message, "xradius: %d ",j+75);

outtextxy(getmaxx()-200,getmaxy()-60,message);

sprintf(message, "yradius : %d",j);

outtextxy(getmaxx()-200,getmaxy()-40,message);

outtextxy(getmaxx()-250,getmaxy()-20,"www.CProgrammingExpert.com");

getch();

}

cleardevice();

for(i=50,j=100;i<=100;i+=10,j+=20)

ellipse (getmaxx()/2,getmaxy()/2,0,360,j+75,j);

outtextxy(getmaxx()-250,getmaxy()-20,"www.CProgrammingExpert.com");

getch();

closegraph();

return 0;

}

#include<stdio.h>

#include<conio.h>

#include<graphics.h>

int main()

{

Page 151: Learn C Programming Step by Step

P a g e | 150

int gd=DETECT,gm,i,error;

initgraph(&gd,&gm,"f:\\tc\\bgi");

error = graphresult();

if (error != grOk)

{

printf("Graphics error occurred");

printf("Press any key to halt:");

getch();

exit(1);

}

setbkcolor(BLUE);

/* loop through the fill patterns */

for (i = EMPTY_FILL; i < USER_FILL; i++)

{

/* set fill pattern */

setfillstyle(i, getmaxcolor());

/* draw a filled ellipse */

fillellipse(getmaxx() / 2, getmaxy() / 2,200, 150);

outtextxy(getmaxx()-250,getmaxy()-20,"www.CProgrammingExpert.com");

getch();

}

getch();

closegraph();

return 0;

}

#include<stdio.h>

#include<conio.h>

#include<graphics.h>

/* floodfill example */

#include <stdlib.h>

int main()

{

int gd=DETECT,gm,i,error;

initgraph(&gd,&gm,"f:\\tc\\bgi");

error = graphresult();

if (error != grOk)

{

printf("Graphics error occurred");

printf("Press any key to halt:");

getch();

exit(1);

}

setbkcolor(BLUE);

setcolor(getmaxcolor()); /* select drawing color */

setfillstyle(SOLID_FILL, getmaxcolor()); /* select fill color */

rectangle(0, 0, getmaxx(), getmaxy()); /* draw a border around the screen

*/

circle(getmaxx() / 3, getmaxy() /2, 50);

Page 152: Learn C Programming Step by Step

P a g e | 151

circle(getmaxx()-20, 10, 50);

circle(100, 100, 50);

circle(getmaxx() / 2, 20, 100);

circle(getmaxx()-75, getmaxy()-25, 200);

circle(20, getmaxy()-20, 25);

getch();

floodfill(2, 2, getmaxcolor()); /* fill in bounded region */

outtextxy(getmaxx()-250,getmaxy()-20,"www.CProgrammingExpert.com");

getch();

closegraph();

return 0;

}

#include<stdio.h>

#include<conio.h>

#include<graphics.h>

/* getarccoords example */

int main()

{

int gd=DETECT,gm,error,stangle = 90, endangle = 360;

struct arccoordstype info;

char message1[80], message2[80];

initgraph(&gd,&gm,"f:\\tc\\bgi");

error = graphresult();

if (error != grOk)

{

printf("Graphics error occurred");

printf("Press any key to halt:");

getch();

exit(1);

}

setbkcolor(BLUE);

setcolor(getmaxcolor());

arc(getmaxx() / 2, getmaxy() / 2, stangle, endangle, 100); /* draw arc */

getarccoords(&info);

/* convert arc information into strings */

sprintf(message1, "*- (%d, %d)", info.xstart, info.ystart);

sprintf(message2, "*- (%d, %d)", info.xend, info.yend);

outtextxy(info.xstart, info.ystart, message1);

outtextxy(info.xend, info.yend, message2);

outtextxy(getmaxx()-250,getmaxy()-20,"www.CProgrammingExpert.com");

getch();

closegraph();

return 0;

}

Page 153: Learn C Programming Step by Step

P a g e | 152

#include<stdio.h>

#include<conio.h>

#include<graphics.h>

/* getaspectratio example */

int main()

{

int gd=DETECT,gm,error,xasp, yasp;

initgraph(&gd,&gm,"f:\\tc\\bgi");

error = graphresult();

if (error != grOk)

{

printf("Graphics error occurred");

printf("Press any key to halt:");

getch();

exit(1);

}

setbkcolor(BLUE);

setcolor(getmaxcolor());

getaspectratio(&xasp, &yasp); /* get current aspect ratio settings */

circle( getmaxx() / 2, getmaxy() / 2, 100);

getch();

cleardevice();

setaspectratio(xasp/2, yasp);

circle( getmaxx() / 2, getmaxy() / 2, 100); /* draw wide circle */

getch();

cleardevice();

setaspectratio(xasp, yasp/2);

circle( getmaxx() / 2, getmaxy() / 2, 100);

getch();

cleardevice();

setaspectratio(xasp, yasp);

circle( getmaxx() / 2, getmaxy() / 2, 100);

outtextxy(getmaxx()-250,getmaxy()-20,"www.CProgrammingExpert.com");

getch();

closegraph();

return 0;

}

#include<stdio.h>

#include<conio.h>

#include<graphics.h>

Page 154: Learn C Programming Step by Step

P a g e | 153

/* getfillpattern example */

int main()

{

int gd=DETECT,gm,error;

char pattern[8] = {0x00, 0x70, 0x20,0x27, 0x25, 0x27, 0x04, 0x04};

initgraph(&gd,&gm,"f:\\tc\\bgi");

error = graphresult();

if (error != grOk)

{

printf("Graphics error occurred");

printf("Press any key to halt:");

getch();

exit(1);

}

setbkcolor(BLUE);

setcolor(getmaxcolor());

setfillpattern(pattern,getmaxcolor()); /* select a user-defined fill

pattern */

bar(30, 30, getmaxx()-30, getmaxy()-30);

outtextxy(getmaxx()-250,getmaxy()-20,"www.CProgrammingExpert.com");

getch();

getfillpattern(pattern); /* get the current user-defined fill pattern */

pattern[0] -= 5; /* alter the pattern we grabbed */

pattern[1] -= 10;

pattern[2] += 10;

pattern[3] -= 15;

setfillpattern(pattern, getmaxcolor());

/* fill the screen with the new pattern */

bar(30, 30, getmaxx()-30, getmaxy()-30);

outtextxy(getmaxx()-250,getmaxy()-20,"www.CProgrammingExpert.com");

getch();

closegraph();

return 0;

}

#include<stdio.h>

#include<conio.h>

#include<graphics.h>

/* getbkcolor example */

int main()

{

int gd=DETECT,gm,error,color;

char name[35];

initgraph(&gd,&gm,"f:\\tc\\bgi");

error = graphresult();

if (error != grOk)

{

printf("Graphics error occurred");

printf("Press any key to halt:");

getch();

Page 155: Learn C Programming Step by Step

P a g e | 154

exit(1);

}

setbkcolor(BLUE);

setcolor(getmaxcolor());

settextjustify(CENTER_TEXT, CENTER_TEXT);

color = getbkcolor();

itoa(color, name, 10); /* convert color value into a string */

strcat(name, " is the current background color.");

/* display a message */

outtextxy(getmaxx() / 2, getmaxy() / 2, name);

outtextxy(getmaxx()-125,getmaxy()-20,"www.CProgrammingExpert.com");

getch();

closegraph();

return 0;

}

#include<stdio.h>

#include<conio.h>

#include<graphics.h>

#include

/* getpixel example */

#define PIXEL_COUNT 1000

#define DELAY_TIME 100 /* in milliseconds */

int main()

{

int gd=DETECT,gm,error,i, x, y, color, maxcolor, seed;

initgraph(&gd,&gm,"f:\\tc\\bgi");

error = graphresult();

if (error != grOk)

{

printf("Graphics error occurred");

printf("Press any key to halt:");

getch();

exit(1);

}

setbkcolor(BLUE);

maxcolor = getmaxcolor() + 1;

while (!kbhit())

{

seed = random(32767);

srand(seed); /* seed the random number generator */

for (i=0; i<="" pre="">

Page 156: Learn C Programming Step by Step

P a g e | 155

#include<stdio.h>

#include<conio.h>

#include<graphics.h>

//clearviewport()

int main()

{

int gd=DETECT,gm,error,height;

initgraph(&gd,&gm,"f:\\tc\\bgi");

error = graphresult();

if (error != grOk)

{

printf("Graphics error occurred");

printf("Press any key to halt:");

getch();

exit(1);

}

setbkcolor(BLUE);

setcolor(getmaxcolor());

height = textheight("l");

outtextxy(0, 0, "* <-- (0, 0) in default viewport");

setviewport(150, 150, getmaxx()-150, getmaxy()-150, 1); /* create a new

viewport */

outtextxy(0, 0, "* <-- (0, 0) in new viewport");

outtextxy(0, 2*height, "Press any key to clear viewport:");

getch();

clearviewport(); /* clear the viewport */

outtextxy(0, 0, "Press any key to quit:");

outtextxy(getmaxx()-300,getmaxy()-10,"www.CProgrammingExpert.com");

getch();

closegraph();

return 0;

}

#include<stdio.h>

#include<conio.h>

#include<graphics.h>

//settextjustify

int main()

{

int gd=DETECT,gm,error;

initgraph(&gd,&gm,"f:\\tc\\bgi");

error = graphresult();

if (error != grOk)

{

printf("Graphics error occurred");

printf("Press any key to halt:");

getch();

exit(1);

}

Page 157: Learn C Programming Step by Step

P a g e | 156

setbkcolor(BLUE);

settextjustify(CENTER_TEXT, CENTER_TEXT);

outtextxy(getmaxx() / 2, getmaxy() / 2, "Press a key to close the graphics

system:");

outtextxy(getmaxx()-150,getmaxy()-20,"www.CProgrammingExpert.com");

getch();

closegraph();

printf("Hi,We're now back in text mode.\n");

printf("Press any key to halt:");

getch();

return 0;

}

#include<stdio.h>

#include<conio.h>

#include<graphics.h>

//detectgraph

#include

/* the names of the various cards supported */

char *dname[] = { "requests detection",

"a CGA",

"an MCGA",

"an EGA",

"a 64K EGA",

"a monochrome EGA",

"an IBM 8514",

"a Hercules monochrome",

"an AT&T 6300 PC",

"a VGA",

"an IBM 3270 PC"

};

int main()

{

int gd=DETECT,gm,error;

initgraph(&gd,&gm,"f:\\tc\\bgi");

error = graphresult();

if (error != grOk)

{

printf("Graphics error occurred");

printf("Press any key to halt:");

getch();

exit(1);

}

setbkcolor(BLUE);

clrscr();

printf("You have %s video display card.\n", dname[gd]);

outtextxy(getmaxx()-250,getmaxy()-20,"www.CProgrammingExpert.com");

printf("Press any key to halt:");

getch();

return 0;

}

Page 158: Learn C Programming Step by Step

P a g e | 157

#include<stdio.h>

#include<conio.h>

#include<graphics.h>

/* getcolor example */

int main()

{

int gd=DETECT,gm,error;

int color, midx, midy;

char colname[35];

initgraph(&gd,&gm,"f:\\tc\\bgi");

error = graphresult();

if (error != grOk)

{

printf("Graphics error occurred");

printf("Press any key to halt:");

getch();

exit(1);

}

setbkcolor(BLUE);

setcolor(getmaxcolor());

settextjustify(CENTER_TEXT, CENTER_TEXT);

color = getcolor(); /* get the current drawing color */

itoa(color, colname, 10); /* convert color value into a string */

strcat(colname, " is the current drawing color.");

outtextxy(getmaxx() / 2, getmaxy() / 2, colname);

outtextxy(getmaxx()-150,getmaxy()-20,"www.CProgrammingExpert.com");

getch();

closegraph();

return 0;

}

#include<stdio.h>

#include<conio.h>

#include<graphics.h>

/* getdrivername example */

int main()

{

Page 159: Learn C Programming Step by Step

P a g e | 158

int gd=DETECT,gm,error;

char *drivername;

initgraph(&gd,&gm,"f:\\tc\\bgi");

error = graphresult();

if (error != grOk)

{

printf("Graphics error occurred");

printf("Press any key to halt:");

getch();

exit(1);

}

setbkcolor(BLUE);

setcolor(getmaxcolor());

drivername = getdrivername(); /* get the name of the device driver in use

*/

settextjustify(CENTER_TEXT, CENTER_TEXT);

strcat(drivername," is currently loaded driver");

outtextxy(getmaxx() / 2, getmaxy() / 2, drivername); /* output the name of

the driver */

outtextxy(getmaxx()-150,getmaxy()-20,"www.CProgrammingExpert.com");

getch();

closegraph();

return 0;

}

#include<stdio.h>

#include<conio.h>

#include<graphics.h>

int main()

{

int gd=DETECT,gm,error;

struct fillsettingstype fillinfo;

char message1[50], message2[50];

char *fillname[] = { "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" }; /* The names of the fill styles supported

*/

initgraph(&gd,&gm,"f:\\tc\\bgi");

error = graphresult();

if (error != grOk)

{

printf("Graphics error occurred");

printf("Press any key to halt:");

getch();

exit(1);

}

setbkcolor(BLUE);

getfillsettings(&fillinfo); /* get info about current fill pattern and

color */

Page 160: Learn C Programming Step by Step

P a g e | 159

sprintf(message1, "%s is the fill style.", fillname[fillinfo.pattern]);

sprintf(message2, "%d is the fill color.", fillinfo.color);

settextjustify(CENTER_TEXT, CENTER_TEXT);

outtextxy(getmaxx() / 2, (getmaxy() / 2)-2*textheight("l"), message1);

outtextxy(getmaxx() / 2, (getmaxy() / 2)+2*textheight("l"), message2);

outtextxy(getmaxx()-150,getmaxy()-20,"www.CProgrammingExpert.com");

getch();

closegraph();

return 0;

}

#include<stdio.h>

#include<conio.h>

#include<graphics.h>

int main()

{

int gd=DETECT,gm,error,mode;

char strnumber[80], strmode[80];

initgraph(&gd,&gm,"f:\\tc\\bgi");

error = graphresult();

if (error != grOk)

{

printf("Graphics error occurred");

printf("Press any key to halt:");

getch();

exit(1);

}

setbkcolor(BLUE);

mode = getgraphmode(); /* get mode number and name strings */

sprintf(strnumber, "%d is the current mode number.", mode);

sprintf(strmode, "%s is the current graphics mode.", getmodename(mode));

settextjustify(CENTER_TEXT, CENTER_TEXT);

outtextxy(getmaxx() / 2, getmaxy() / 2, strnumber);

outtextxy(getmaxx() / 2, (getmaxy() / 2)+2*textheight("l"), strmode);

outtextxy(getmaxx()-150,getmaxy()-20,"www.CProgrammingExpert.com");

getch();

closegraph();

return 0;

}

Page 161: Learn C Programming Step by Step

P a g e | 160

#include<stdio.h>

#include<conio.h>

#include<graphics.h>

int main()

{

int gd=DETECT,gm,error;

struct linesettingstype lineinfo;

char linestyle[80], linepattern[80], linewidth[80];

char *linename[] = { "SOLID_LINE", "DOTTED_LINE", "CENTER_LINE",

"DASHED_LINE", "USERBIT_LINE" };

/* the names of the line styles supported */

initgraph(&gd,&gm,"f:\\tc\\bgi");

error = graphresult();

if (error != grOk)

{

printf("Graphics error occurred");

printf("Press any key to halt:");

getch();

exit(1);

}

setbkcolor(BLUE);

getlinesettings(&lineinfo); /* get information about current line settings

*/

sprintf(linestyle, "%s is the line style.", linename[lineinfo.linestyle]);

/* convert line information into strings */

sprintf(linepattern, "0x%X is the user-defined line

pattern.",lineinfo.upattern);

sprintf(linewidth, "%d is the line thickness.", lineinfo.thickness);

settextjustify(CENTER_TEXT, CENTER_TEXT);

outtextxy(getmaxx() / 2,getmaxy() / 2, linestyle);

outtextxy(getmaxx() / 2, (getmaxy() / 2)+2*textheight("l"), linepattern);

outtextxy(getmaxx() / 2, (getmaxy() / 2)+4*textheight("l"), linewidth);

outtextxy(getmaxx()-150,getmaxy()-20,"www.CProgrammingExpert.com");

getch();

closegraph();

return 0;

}

#include<stdio.h>

#include<conio.h>

#include<graphics.h>

int main()

{

int gd=DETECT,gm,error;

char colstr[80];

initgraph(&gd,&gm,"f:\\tc\\bgi");

error = graphresult();

if (error != grOk)

{

printf("Graphics error occurred");

printf("Press any key to halt:");

Page 162: Learn C Programming Step by Step

P a g e | 161

getch();

exit(1);

}

setbkcolor(BLUE);

sprintf(colstr, "This mode supports colors 0..%d", getmaxcolor());

/* grab the color info. and convert it to a string */

settextjustify(CENTER_TEXT, CENTER_TEXT);

outtextxy(getmaxx() / 2,getmaxy() / 2, colstr);

outtextxy(getmaxx()-150,getmaxy()-20,"www.CProgrammingExpert.com");

getch();

closegraph();

return 0;

}

#include<stdio.h>

#include<conio.h>

#include<graphics.h>

int main()

{

int gd=DETECT,gm,error;

char modestr[80];

initgraph(&gd,&gm,"f:\\tc\\bgi");

error = graphresult();

if (error != grOk)

{

printf("Graphics error occurred");

printf("Press any key to halt:");

getch();

exit(1);

}

setbkcolor(BLUE);

sprintf(modestr, "This driver supports modes 0..%d",getmaxmode());

/* grab the mode info. and convert it to a string */

settextjustify(CENTER_TEXT, CENTER_TEXT);

outtextxy(getmaxx() / 2,getmaxy() / 2, modestr);

outtextxy(getmaxx()-150,getmaxy()-20,"www.CProgrammingExpert.com");

getch();

closegraph();

return 0;

}

Page 163: Learn C Programming Step by Step

P a g e | 162

#include<stdio.h>

#include<conio.h>

#include<graphics.h>

int main()

{

int gd=DETECT,gm,error,mode;

char strnumber[80], strmode[80];

initgraph(&gd,&gm,"f:\\tc\\bgi");

error = graphresult();

if (error != grOk)

{

printf("Graphics error occurred");

printf("Press any key to halt:");

getch();

exit(1);

}

setbkcolor(BLUE);

mode = getgraphmode(); /* get mode number and name strings */

sprintf(strnumber, "%d is the current mode number.", mode);

sprintf(strmode, "%s is the current graphics mode.",getmodename(mode));

settextjustify(CENTER_TEXT, CENTER_TEXT);

outtextxy(getmaxx() / 2, getmaxy() / 2, strnumber);

outtextxy(getmaxx() / 2, (getmaxy() / 2)+2*textheight("W"), strmode);

outtextxy(getmaxx()-150,getmaxy()-20,"www.CProgrammingExpert.com");

getch();

closegraph();

return 0;

}

#include<stdio.h>

#include<conio.h>

#include<graphics.h>

int main()

{

int gd=DETECT,gm,error;

initgraph(&gd,&gm,"f:\\tc\\bgi");

error = graphresult();

if (error != grOk)

{

printf("Graphics error occurred");

printf("Press any key to halt:");

getch();

exit(1);

}

setbkcolor(BLUE);

setwritemode(XOR_PUT); /* select XOR drawing mode */

line(0, 0, getmaxx(), getmaxy());

getch();

line(0, 0, getmaxx(), getmaxy()); /* erase the line by drawing over it */

getch();

Page 164: Learn C Programming Step by Step

P a g e | 163

setwritemode(COPY_PUT); /* select overwrite drawing mode */

line(0, 0, getmaxx(), getmaxy());

outtextxy(getmaxx()-250,getmaxy()-20,"www.CProgrammingExpert.com");

getch();

closegraph();

return 0;

}

#include<stdio.h>

#include<conio.h>

#include<graphics.h>

int main()

{

int gdriver = EGA, gmode = EGAHI, error,height;

initgraph(&gdriver,&gmode,"f:\\tc\\bgi");

error = graphresult();

if (error != grOk)

{

printf("Graphics error occurred");

printf("Press any key to halt:");

getch();

exit(1);

}

setbkcolor(BLUE);

height = textheight("l");

setactivepage(1); /* select the off screen page for drawing */

circle(getmaxx()/2,getmaxy()/2,150); /* draw a circle on page #1 */

settextjustify(CENTER_TEXT, CENTER_TEXT);

/* output a message on page #1 */

outtextxy(getmaxx() / 2, getmaxy() / 2, "This is page #1:");

outtextxy(getmaxx() / 2, (getmaxy() / 2)+height, "Press any key to

halt:");

outtextxy(getmaxx()-150,getmaxy()-20,"www.CProgrammingExpert.com");

setactivepage(0); /* select drawing to page #0 */

ellipse (getmaxx()/2,getmaxy()/2,0,360,150, 100);

outtextxy(getmaxx() / 2, getmaxy() / 2, "This is page #0.");

outtextxy(getmaxx() / 2, (getmaxy() / 2)+height, "Press any key to view

page #1:");

outtextxy(getmaxx()-150,getmaxy()-20,"www.CProgrammingExpert.com");

getch();

/* select page #1 as the visible page */

setvisualpage(1);

getch();

closegraph();

return 0;

}

Page 165: Learn C Programming Step by Step

P a g e | 164

#include<stdio.h>

#include<conio.h>

#include<graphics.h>

int main()

{

int gd=DETECT,gm,error,a,b,result;

initgraph(&gd,&gm,"f:\\tc\\bgi");

error = graphresult();

if (error != grOk)

{

printf("Graphics error occurred");

printf("Press any key to halt:");

getch();

exit(1);

}

setbkcolor(BLUE);

outtextxy(getmaxx()-250,getmaxy()-20,"www.CProgrammingExpert.com");

circle(getmaxx()/2,getmaxy()/2,175);

settextjustify(CENTER_TEXT, CENTER_TEXT);

outtextxy(getmaxx() / 2, getmaxy() / 2, "Press a key to close the graphics

system:");

getch();

closegraph(); /* closes down the graphics system */

printf("*****We're now back in text mode.*****\n\n");

printf("Enter two numbers\n");

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

result=a+b;

printf("\nSum of %d and %d is %d\n\nOK!",a,b,result);

getch();

return 0;

}

#include<stdio.h>

#include<conio.h>

#include<graphics.h>

int main()

{

int gd=DETECT,gm,error,i;

initgraph(&gd,&gm,"f:\\tc\\bgi");

error = graphresult();

if (error != grOk)

{

printf("Graphics error occurred");

Page 166: Learn C Programming Step by Step

P a g e | 165

printf("Press any key to halt:");

getch();

exit(1);

}

setbkcolor(BLUE);

settextstyle(TRIPLEX_FONT, HORIZ_DIR, 4);

moveto(getmaxx() / 2, getmaxy() / 2); /* move to the text starting

position */

outtext("Norm ");

setusercharsize(1, 2, 1, 1); outtext("Short "); /* make the text 1/2 the

normal width */

setusercharsize(3, 1, 1, 1); outtext("Wide"); /* make the text 3 times

normal width */

settextstyle(GOTHIC_FONT, HORIZ_DIR, 1);

outtextxy(getmaxx()/2,getmaxy()-30,"www.CProgrammingExpert.com");

getch();

closegraph();

return 0;

}

#include<stdio.h>

#include<conio.h>

#include<graphics.h>

/* the names of the text styles supported */

char *styles[] = { "DEFAULT font", "TRIPLEX font",

"SMALL font", "SANS SERIF_font",

"GOTHIC_font", "SCRIPT font","SIMPLEX font",

"TRIPLEX SCRIPT font","COMPLEX font",

"EUROPEAN font","BOLD font"};

int main()

{

int gd=DETECT,gm,error,i,style,size = 1;

initgraph(&gd,&gm,"f:\\tc\\bgi");

error = graphresult();

if (error != grOk)

{

printf("Graphics error occurred");

printf("Press any key to halt:");

getch();

exit(1);

}

setbkcolor(BLUE);

settextjustify(CENTER_TEXT, CENTER_TEXT);

for (i=DEFAULT_FONT; i<=BOLD_FONT; i++)

/* loop through the available text styles */

{

cleardevice();

if (i == TRIPLEX_FONT)

size = 3;

settextstyle(i, HORIZ_DIR, size); /* select the text style */

outtextxy( getmaxx() / 2, getmaxy() / 2,styles[i]);

Page 167: Learn C Programming Step by Step

P a g e | 166

outtextxy(getmaxx()-250,getmaxy()-25,"www.CProgrammingExpert.com");

getch();

}

closegraph();

return 0;

}

#include<stdio.h>

#include<conio.h>

#include<graphics.h>

int main()

{

int gd=DETECT,gm,error,i, height, j=0;

struct palettetype type;

initgraph(&gd,&gm,"f:\\tc\\bgi");

error = graphresult();

if (error != grOk)

{

printf("Graphics error occurred");

printf("Press any key to halt:");

getch();

exit(1);

}

setbkcolor(BLUE);

getpalette(&type); /* grab a copy of the palette */

for (i=0; i<="" pre="">

#include<stdio.h>

#include<conio.h>

#include<graphics.h>

int main()

{

int gd=DETECT,gm,error,x,y;

initgraph(&gd,&gm,"f:\\tc\\bgi");

error = graphresult();

if (error != grOk)

{

printf("Graphics error occurred");

printf("Press any key to halt:");

getch();

exit(1);

Page 168: Learn C Programming Step by Step

P a g e | 167

}

setbkcolor(BLUE);

x=getmaxx() / 2;

y=getmaxy() / 2;

settextjustify(CENTER_TEXT, CENTER_TEXT);

rectangle(x-175, y-50, x+175, y+50);

outtextxy(getmaxx()-150,getmaxy()-20,"www.CProgrammingExpert.com");

outtextxy(x, y, "Press any key to exit graphics");

getch();

restorecrtmode(); /* restore system to text mode */

printf("We're now in text mode.\n");

printf("Press any key to return to graphics mode:");

getch();

setgraphmode(getgraphmode()); /* return to graphics mode */

settextjustify(CENTER_TEXT, CENTER_TEXT);

setbkcolor(BLUE);

outtextxy(x, y, "We're back in graphics mode.");

outtextxy(getmaxx()-150,getmaxy()-20,"www.CProgrammingExpert.com");

outtextxy(x, y+2*textheight("l"), "Press any key to return to text

mode:");

getch();

restorecrtmode(); /* restore system to text mode */

printf("We're now in text mode.\n");

printf("Press any key to halt:");

getch();

closegraph();

return 0;

}

#include<stdio.h>

#include<conio.h>

#include<graphics.h>

char *linename[] = { "SOLID_LINES", "DOTTED_LINES",

"CENTER_LINES","DASHED_LINES", "USERBIT_LINES" };

/* The names of the line styles supported */

int main()

{

int gd=DETECT,gm,error,i;

int style, midx, midy, userpat;

char stylename[25],message[25];

initgraph(&gd,&gm,"f:\\tc\\bgi");

error = graphresult();

if (error != grOk)

{

printf("Graphics error occurred");

printf("Press any key to halt:");

getch();

exit(1);

}

setbkcolor(BLUE);

midx = getmaxx() / 2;

Page 169: Learn C Programming Step by Step

P a g e | 168

midy = getmaxy() / 2;

userpat = 1;

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

{

for (style=SOLID_LINE; style<=USERBIT_LINE; style++)

{

sprintf(message, "Line thickness : %d",i);

outtextxy(midx-75, midy-100, message);

setlinestyle(style, userpat, i); /* select the line style */

strcpy(stylename, linename[style]); /* convert style into a string */

rectangle(10, 10, getmaxx()-10, getmaxy()-10);

line(10, 10, midx-10, midy);

line(midx-10, midy, getmaxx()-10,getmaxy()-10);

line(midx-10, midy, getmaxx()-10,10);

line(midx-10, midy,10,getmaxy()-10);

outtextxy(midx, midy, stylename);

outtextxy(getmaxx()-250,getmaxy()-20,"www.CProgrammingExpert.com");

getch();

cleardevice();

}

getch();

}

closegraph();

return 0;

}

#include<stdio.h>

#include<conio.h>

#include<graphics.h>

int main()

{

int gd=DETECT,gm,error, color, maxcolor, height,y = 10;

char msg[80];

initgraph(&gd,&gm,"f:\\tc\\bgi");

error = graphresult();

if (error != grOk)

{

printf("Graphics error occurred");

printf("Press any key to halt:");

getch();

exit(1);

}

setbkcolor(BLUE);

maxcolor = getmaxcolor();

height = 2 * textheight("l");

for (color=1; color<=maxcolor; color++) /* display the default colors */

{

setcolor(color);

sprintf(msg, "Color: %d", color);

outtextxy((getmaxx()/2)-50, y, msg);

Page 170: Learn C Programming Step by Step

P a g e | 169

outtextxy(getmaxx()-250,getmaxy()-20,"www.CProgrammingExpert.com");

y += height;

}

getch();

for (color=1; color<=maxcolor; color++) /* red out the colors one by one

*/

{

setpalette(color, RED);

outtextxy(getmaxx()-250,getmaxy()-20,"www.CProgrammingExpert.com");

getch();

}

closegraph();

return 0;

}

#include<stdio.h>

#include<conio.h>

#include<graphics.h>

#define BUFSIZE 1000 /* internal graphics buffer size */

int main()

{

int gd=DETECT,gm,i,error;

int x, y, oldsize;

char msg[80];

oldsize = setgraphbufsize(BUFSIZE);

/* Set size of internal graphics buffer before calling initgraph*/

initgraph(&gd,&gm,"f:\\tc\\bgi");

error = graphresult();

if (error != grOk)

{

printf("Graphics error occurred");

printf("Press any key to halt:");

getch();

exit(1);

}

setbkcolor(BLUE);

x = getmaxx() / 2;

y = getmaxy() / 2;

sprintf(msg, "Graphics buffer size: %d", BUFSIZE);

settextjustify(CENTER_TEXT, CENTER_TEXT);

outtextxy(x, y-25, msg);

sprintf(msg, "Old graphics buffer size: %d", oldsize);

outtextxy(x, y+2*textheight("l"), msg);

outtextxy(getmaxx()-250,getmaxy()-20,"www.CProgrammingExpert.com");

getch();

closegraph();

return 0;

}

Page 171: Learn C Programming Step by Step

P a g e | 170

#include<stdio.h>

#include<conio.h>

#include<graphics.h>

/* the names of the fill styles supported */

char *fname[] = { "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" };

int main()

{

int gd=DETECT,gm,error,i;

int style, midx, midy;

char stylestr[40];

initgraph(&gd,&gm,"f:\\tc\\bgi");

error = graphresult();

if (error != grOk)

{

printf("Graphics error occurred");

printf("Press any key to halt:");

getch();

exit(1);

}

setbkcolor(BLUE);

midx = getmaxx() / 2;

midy = getmaxy() / 2;

for (style = EMPTY_FILL; style < USER_FILL; style++)

{

setfillstyle(style, getmaxcolor()); /* select the fill style */

strcpy(stylestr, fname[style]); /* convert style into a string */

/* fill a bar */

bar3d(midx-125, midy-125, midx+10, midy, 10, 10);

outtextxy(midx+10, midy, stylestr);

outtextxy(getmaxx()-250,getmaxy()-20,"www.CProgrammingExpert.com");

getch();

cleardevice();

}

getch();

closegraph();

return 0;

}

Page 172: Learn C Programming Step by Step

P a g e | 171

#include<stdio.h>

#include<conio.h>

#include<graphics.h>

int main()

{

int gd=DETECT,gm,error,left, top, right, bottom;

initgraph(&gd,&gm,"f:\\tc\\bgi");

error = graphresult();

if (error != grOk)

{

printf("Graphics error occurred");

printf("Press any key to halt:");

getch();

exit(1);

}

setbkcolor(BLUE);

left = getmaxx() / 2 -200;

top = getmaxy() / 2 - 200;

right = getmaxx() / 2 + 200;

bottom = getmaxy() / 2 + 200;

rectangle(left,top,right,bottom); /* draw a rectangle */

outtextxy(getmaxx()-250,getmaxy()-20,"www.CProgrammingExpert.com");

getch();

closegraph();

return 0;

}

#include<stdio.h>

#include<conio.h>

#include<graphics.h>

int main()

{

int gd=DETECT,gm,error, midx, midy, i;

int stangle = 0, endangle = 270, xrad = 200, yrad = 150;

initgraph(&gd,&gm,"f:\\tc\\bgi");

error = graphresult();

if (error != grOk)

{

printf("Graphics error occurred");

printf("Press any key to halt:");

getch();

exit(1);

}

setbkcolor(BLUE);

midx = getmaxx() / 2;

midy = getmaxy() / 2;

for (i=EMPTY_FILL; i<="" pre="">

Page 173: Learn C Programming Step by Step

P a g e | 172

#include<stdio.h>

#include<conio.h>

#include<graphics.h>

int main()

{

int gd=DETECT,gm,error,low, high;

char moderange[80];

initgraph(&gd,&gm,"f:\\tc\\bgi");

error = graphresult();

if (error != grOk)

{

printf("Graphics error occurred");

printf("Press any key to halt:");

getch();

exit(1);

}

setbkcolor(BLUE);

getmoderange(gd, &low, &high); /* get the mode range for this driver */

sprintf(moderange, "This driver supports modes %d..%d", low, high);

/* convert mode range info. into strings */

settextjustify(CENTER_TEXT, CENTER_TEXT);

outtextxy(getmaxx() / 2, getmaxy() / 2, moderange);

outtextxy(getmaxx()-150,getmaxy()-20,"www.CProgrammingExpert.com");

getch();

closegraph();

return 0;

}

#include<stdio.h>

#include<conio.h>

#include<graphics.h>

int main()

{

int gd=DETECT,gm,error;

char palettesize[80];

initgraph(&gd,&gm,"f:\\tc\\bgi");

error = graphresult();

if (error != grOk)

{

printf("Graphics error occurred");

printf("Press any key to halt:");

getch();

exit(1);

Page 174: Learn C Programming Step by Step

P a g e | 173

}

setbkcolor(BLUE);

sprintf(palettesize, "The palette has %d modifiable

entries.",getpalettesize());

/* convert palette size info into string */

settextjustify(CENTER_TEXT, CENTER_TEXT);

outtextxy(getmaxx() / 2, getmaxy() / 2, palettesize);

outtextxy(getmaxx()-150,getmaxy()-20,"www.CProgrammingExpert.com");

getch();

closegraph();

return 0;

}

#include<stdio.h>

#include<conio.h>

#include<graphics.h>

int main()

{

int gd=DETECT,gm,error,i,j = 10,height;

struct palettetype pal;

char palettesize[80], paletteval[20];

initgraph(&gd,&gm,"f:\\tc\\bgi");

error = graphresult();

if (error != grOk)

{

printf("Graphics error occurred");

printf("Press any key to halt:");

getch();

exit(1);

}

setbkcolor(BLUE);

getpalette(&pal); /* grab a copy of the palette */

sprintf(palettesize, "The palette has %d modifiable entries.",pal.size);

/* convert palette info into strings */

outtextxy(getmaxx()/2-175, j, palettesize);

if (pal.size != 0)

{

height = textheight("l");

j += 2*height;

outtextxy(getmaxx()/2-125, j, "Here are the current values:");

j += 2*height;

for (i=0; i<="" pre="">

Page 175: Learn C Programming Step by Step

P a g e | 174

#include<stdio.h>

#include<conio.h>

#include<graphics.h>

char *clip[] = { "OFF", "ON" };

int main()

{

int gd=DETECT,gm,error, midx, midy, ht;

struct viewporttype viewinfo;

char topstr[80], botstr[80], clipstr[80];

initgraph(&gd,&gm,"f:\\tc\\bgi");

error = graphresult();

if (error != grOk)

{

printf("Graphics error occurred");

printf("Press any key to halt:");

getch();

exit(1);

}

setbkcolor(BLUE);

midx = getmaxx() / 2;

midy = getmaxy() / 2;

getviewsettings(&viewinfo); /* get information about current viewport */

sprintf(topstr, "(%d, %d) is the upper left viewport

corner.",viewinfo.left, viewinfo.top);

sprintf(botstr, "(%d, %d) is the lower right viewport

corner.",viewinfo.right, viewinfo.bottom);

sprintf(clipstr, "Clipping is turned %s.", clip[viewinfo.clip]);

settextjustify(CENTER_TEXT, CENTER_TEXT);

ht = textheight("W");

outtextxy(midx, midy, topstr);

outtextxy(midx, midy+2*ht, botstr);

outtextxy(midx, midy+4*ht, clipstr);

outtextxy(getmaxx()-150,getmaxy()-20,"www.CProgrammingExpert.com");

getch();

closegraph();

return 0;

}

#include<stdio.h>

#include<conio.h>

#include<graphics.h>

int main()

{

int gd=DETECT,gm,error,i;

char msg[80];

initgraph(&gd,&gm,"f:\\tc\\bgi");

error = graphresult();

if (error != grOk)

{

Page 176: Learn C Programming Step by Step

P a g e | 175

printf("Graphics error occurred");

printf("Press any key to halt:");

getch();

exit(1);

}

setbkcolor(BLUE);

moveto(getmaxx() / 2, getmaxy() / 2); /* move to the screen center point

*/

sprintf(msg, "<-(%d, %d) is the here.", getx(), gety());

outtext(msg);

outtextxy(getmaxx()-250,getmaxy()-20,"www.CProgrammingExpert.com");

getch();

closegraph();

return 0;

}

#include<stdio.h>

#include<conio.h>

#include<graphics.h>

int main()

{

int gd=DETECT,gm,error;

char msg[80];

initgraph(&gd,&gm,"f:\\tc\\bgi");

error = graphresult();

if (error != grOk)

{

printf("Graphics error occurred");

printf("Press any key to halt:");

getch();

exit(1);

}

setbkcolor(BLUE);

moveto(getmaxx() / 2-100, getmaxy() / 2+25); /* move to the screen center

point */

sprintf(msg, "<-(%d, %d) is the here.", getx(), gety());

outtext(msg);

outtextxy(getmaxx()-250,getmaxy()-20,"www.CProgrammingExpert.com");

getch();

closegraph();

return 0;

}

Page 177: Learn C Programming Step by Step

P a g e | 176

#include<stdio.h>

#include<conio.h>

#include<graphics.h>

int main()

{

int gd=DETECT,gm,error;

initgraph(&gd,&gm,"f:\\tc\\bgi");

error = graphresult();

if (error != grOk)

{

printf("Graphics error occurred");

printf("Press any key to halt:");

getch();

exit(1);

}

setbkcolor(BLUE);

setlinestyle(DOTTED_LINE, 0, 3);

rectangle(10, 10, getmaxx()-10,getmaxy()-10);

outtextxy(getmaxx()/2-100, getmaxx()/3, "Before default values are

restored.");

outtextxy(getmaxx()-250,getmaxy()-30,"www.CProgrammingExpert.com");

getch();

graphdefaults(); /* restore default values for everything */

cleardevice();

rectangle(10, 10, getmaxx()-10,getmaxy()-10);

/* output rectangle with default settings */

outtextxy(getmaxx()/2-100, getmaxy()/3, "After restoring default

values.");

outtextxy(getmaxx()-250,getmaxy()-30,"www.CProgrammingExpert.com");

getch();

closegraph();

return 0;

}

#include<stdio.h>

#include<conio.h>

#include<graphics.h>

#define NONSENSE -50

int main()

{

int gd=NONSENSE,gm,error;

initgraph(&gd,&gm,"f:\\tc\\bgi");

error = graphresult();

if (error != grOk)

{

Page 178: Learn C Programming Step by Step

P a g e | 177

printf("Graphics error: %s\n", grapherrormsg(error));

printf("Press any key to halt:");

getch();

exit(1);

}

setbkcolor(BLUE);

rectangle(10, 10, getmaxx()-10,getmaxy()-10);

outtextxy(getmaxx()-250,getmaxy()-20,"www.CProgrammingExpert.com");

getch();

closegraph();

return 0;

}

#include<stdio.h>

#include<conio.h>

#include<graphics.h>

#define ARROW_SIZE 10

void draw_arrow(int x, int y);

int main()

{

int gd=DETECT,gm,error,i;

void *arrow;

int x, y, maxx;

unsigned int size;

initgraph(&gd,&gm,"f:\\tc\\bgi");

error = graphresult();

if (error != grOk)

{

printf("Graphics error occurred");

printf("Press any key to halt:");

getch();

exit(1);

}

setbkcolor(BLUE);

maxx = getmaxx();

x = 0;

y = getmaxy() / 2;

draw_arrow(x, y); /* draw the image to be grabbed */

size = imagesize(x, y-ARROW_SIZE, x+(4*ARROW_SIZE), y+ARROW_SIZE);

/* calculate the size of the image */

arrow = malloc(size); /* allocate memory to hold the image */

getimage(x, y-ARROW_SIZE, x+(4*ARROW_SIZE), y+ARROW_SIZE, arrow);

/* grab the image */

while (!kbhit()) /* repeat until a key is pressed */

{

putimage(x, y-ARROW_SIZE, arrow, XOR_PUT); /* erase old image */

x += ARROW_SIZE;

if (x >= maxx)

x = 0;

putimage(x, y-ARROW_SIZE, arrow, XOR_PUT); /* plot new image */

Page 179: Learn C Programming Step by Step

P a g e | 178

outtextxy(getmaxx()-250,getmaxy()-20,"www.CProgrammingExpert.com");

}

free(arrow);

closegraph();

return 0;

}

void draw_arrow(int x, int y)

{

moveto(x, y); /* draw an arrow on the screen */

linerel(4*ARROW_SIZE, 0);

linerel(-2*ARROW_SIZE, -1*ARROW_SIZE);

linerel(0, 2*ARROW_SIZE);

linerel(2*ARROW_SIZE, -1*ARROW_SIZE);

}

#include<stdio.h>

#include<conio.h>

#include<graphics.h>

int main()

{

int gd=DETECT,gm,error;

char message[80];

initgraph(&gd,&gm,"f:\\tc\\bgi");

error = graphresult();

if (error != grOk)

{

printf("Graphics error occurred");

printf("Press any key to halt:");

getch();

exit(1);

}

setbkcolor(BLUE);

moveto(100,100); /* move the CP to location (100,100) */

sprintf(message, " (%d, %d)", getx(), gety());

/* create and output a message at (100,100) */

outtextxy(100,100, message);

linerel(200, 200);

/* draw line to a point a relative distance away from current CP*/

sprintf(message, " (%d, %d)", getx(), gety());

/* create and output a message at CP */

outtext(message);

outtextxy(getmaxx()-250,getmaxy()-20,"www.CProgrammingExpert.com");

getch();

closegraph();

return 0;

}

Page 180: Learn C Programming Step by Step

P a g e | 179

#include<stdio.h>

#include<conio.h>

#include<graphics.h>

int main()

{

int gd=DETECT,gm,error;

char msg[80];

initgraph(&gd,&gm,"f:\\tc\\bgi");

error = graphresult();

if (error != grOk)

{

printf("Graphics error occurred");

printf("Press any key to halt:");

getch();

exit(1);

}

setbkcolor(BLUE);

moveto(100, 100); /* move the CP to location (100,100) */

sprintf(msg, " (%d, %d)", getx(), gety()); /* create and output a message

at (100,100) */

outtextxy(100,100, msg);

lineto(200, 200); /* draw a line to (100,100) */

sprintf(msg, " (%d, %d)", getx(), gety()); /* create and output a message

at CP */

outtext(msg);

outtextxy(getmaxx()-250,getmaxy()-20,"www.CProgrammingExpert.com");

getch();

closegraph();

return 0;

}

#include<stdio.h>

#include<conio.h>

#include<graphics.h>

/* moverel example */

int main()

{

int gd=DETECT,gm,error;

char msg[80];

initgraph(&gd,&gm,"f:\\tc\\bgi");

Page 181: Learn C Programming Step by Step

P a g e | 180

error = graphresult();

if (error != grOk)

{

printf("Graphics error occurred");

printf("Press any key to halt:");

getch();

exit(1);

}

setbkcolor(BLUE);

moveto(100,100);

putpixel(getx(), gety(), getmaxcolor()); /* plot a pixel at the CP */

sprintf(msg, " (%d, %d)", getx(), gety());

outtextxy(100,100, msg);

moverel(200, 200);

putpixel(getx(), gety(), getmaxcolor()); /* plot a pixel at the CP */

sprintf(msg, " (%d, %d)", getx(), gety());

/* create and output a message at CP */

outtext(msg);

outtextxy(getmaxx()-250,getmaxy()-20,"www.CProgrammingExpert.com");

getch();

closegraph();

return 0;

}

#include<stdio.h>

#include<conio.h>

#include<graphics.h>

int main()

{

int gd=DETECT,gm,error,i;

char msg[80];

initgraph(&gd,&gm,"f:\\tc\\bgi");

error = graphresult();

if (error != grOk)

{

printf("Graphics error occurred");

printf("Press any key to halt:");

getch();

exit(1);

}

setbkcolor(BLUE);

moveto(100,100);

putpixel(getx(), gety(), getmaxcolor());

sprintf(msg, " (%d, %d)", getx(), gety());

outtextxy(100,100, msg);

moveto(200,200);

putpixel(getx(), gety(), getmaxcolor());

sprintf(msg, " (%d, %d)", getx(), gety());

outtext(msg);

outtextxy(getmaxx()-250,getmaxy()-20,"www.CProgrammingExpert.com");

getch();

Page 182: Learn C Programming Step by Step

P a g e | 181

closegraph();

return 0;

}

#include<stdio.h>

#include<conio.h>

#include<graphics.h>

int main()

{

int gd=DETECT,gm,error,stangle = 45, endangle = 135, radius = 200;

initgraph(&gd,&gm,"f:\\tc\\bgi");

error = graphresult();

if (error != grOk)

{

printf("Graphics error occurred");

printf("Press any key to halt:");

getch();

exit(1);

}

setbkcolor(BLUE);

setfillstyle(EMPTY_FILL, getmaxcolor()); /* set fill style and draw a pie

slice */

pieslice(getmaxx() / 2, getmaxy() / 2, stangle, endangle, radius);

outtextxy(getmaxx()-250,getmaxy()-20,"www.CProgrammingExpert.com");

getch();

closegraph();

return 0;

}

#include<stdio.h>

#include<conio.h>

#include<graphics.h>

//outtext

int main()

{

int gd=DETECT,gm,error;

initgraph(&gd,&gm,"f:\\tc\\bgi");

error = graphresult();

Page 183: Learn C Programming Step by Step

P a g e | 182

if (error != grOk)

{

printf("Graphics error occurred");

printf("Press any key to halt:");

getch();

exit(1);

}

setbkcolor(BLUE);

for (i=SOLID_FILL; i<="" pre="">

Page 184: Learn C Programming Step by Step

P a g e | 183

C Preprocessor

Preprocessor directives are actually the instructions to the compiler itself. They

are not translated but are operated directly by the compiler. Note that preprocessor statements

begin with a #symbol, and are NOT terminated by a semicolon. Traditionally, preprocessor

statements are listed at the beginning of the source file.They are also termed as macros.

The most common preprocessor directives are

include directive

define directive

1.include directive:

The include directive is used to include files like as we include header files in

the beginning of the program using #include directive like

#include<stdio.h>

#include<conio.h>

2.define directive:

It is used to assign names to different constants or statements which are to be

used repeatedly in a program. These defined values or statement can be used by main or in

the user defined functions as well. They are used for

a. defining a constant

b. defining a statement

c. defining a mathematical expression

For example

#define PI 3.141593

#define TRUE 1

#define floatingpointno float

Let us take a look at an example to understand how to use preprocessors in C

Programming.

Page 185: Learn C Programming Step by Step

P a g e | 184

Page 186: Learn C Programming Step by Step

P a g e | 185

Standard C Library Functions in c

programming language

The C, C + + has many features, when using the standard library functions, increasing the

portability of programs.

Standard functions are divided into groups, all functions that belong together are declared in

the header file (the one that says xxx.h), the letter "h" for header in English and is called

heading.

To include any function belonging to these headers should write lines of code as shown as an

example:

# Include

I designed this table to study the function libraries are obviously I've found in my books and

systems.

LIBRARIES AND USE DESCRIPTIONS

Library

Name Description

assert.h Is to provide a definition of the assert macro, which prints an error message

and aborts the program

alloc.h There are functions to allocate, free memory, or obtain information from the

memory blocks.

ctype.h The functions that allow us to know the nature of a character, or to convert

uppercase to lowercase and vice versa and integer values to ASCII codes.

dir.h This lets you sort, create, modify, move and delete directories

errno.h Represent the numbers of error, an error occurs then you can query the

value of the system varianble deerrno for more information about this error.

float.h Define the limits of the floating-point types

limits.h Define the boundaries of different types of integers

math.h Contains the standard math functions used in C and C + +

setjmp.h Defines the type of jmp_buf for some functions.

Page 187: Learn C Programming Step by Step

P a g e | 186

signal.h Contains state functions.

stdarg.h Defines functions that can be called with different numbers of arguments, so

that they can write f (a) f (a, b).

stdef.h Define some special types

stdio.h Incorporate functions - Out E / S standard, types and macros

stlib.h Declare functions that are useful for different purposes, especially searching

and sorting.

string.h This file contains functions for handling strings.

time.h Contains functions related to dates and times

Page 188: Learn C Programming Step by Step

P a g e | 187

c programming examples

===========

1.

main()

{

}

========================

2.

void main()

{

}

========================

3.

int main()

{

return 0;

}

========================

4.

int main ()

{

printf ("Welcome to C language");

return 0;

}

========================

5.

#include <stdio.h>

#include <conio.h>

int main ()

{

clrscr();

printf (“Welcome to C language”);

return 0;

}

========================

6.

Page 189: Learn C Programming Step by Step

P a g e | 188

#include <stdio.h>

#include <conio.h>

int main ()

{

clrscr();

printf (“Welcome to C language”);

getch();

retun 0;

}

========================

String: strlen()

#include <stdio.h>

#include <conio.h>

int main()

{

char str[30]="C PROGRAMMING";

clrscr();

printf("\n\nstr : %s\n\n",str);

printf("\nLength of the string, strlen(str) is %d\n",strlen(str));

getch();

return 0;

}

========================

String: strlwr()

#include <stdio.h>

#include <conio.h>

int main()

{

char str[30]="C PROGRAMMING";

clrscr();

printf("\n\nstr : %s\n\n",str);

printf("strlwr(str) : %s\n",strlwr(str));

getch();

return 0;

}

========================

String: strupr()

#include <stdio.h>

#include <conio.h>

int main()

{

char str[30]="C Programming";

clrscr();

printf("\n\nstr : %s\n\n",str);

printf("strupr(str) : %s\n",strupr(str));

getch();

return 0;

}

========================

String: strcat()

Page 190: Learn C Programming Step by Step

P a g e | 189

#include <stdio.h>

#include <conio.h>

int main()

{

char str1[25]="I LIKE ";

char str2[15]="C PROGRAMMIG";

clrscr();

printf("\n\nstr1 : %s\t\t\tstr2 : %s\n\n",str1,str2);

printf("\n\nstrcat(str1,str2) : %s\n\n",strcat(str1,str2));

printf("\n\nstr1 : %s\t\tstr2 : %s\n\n",str1,str2);

getch();

return 0;

}

========================

String: strncat()

#include <stdio.h>

#include <conio.h>

int main()

{

char str1[25]="I LIKE ";

char str2[13]="C PROGRAMMIG";

clrscr();

printf("\n\nBEFORE:\n\nstr1 : %s\t\t\tstr2 : %s\n\n",str1,str2);

printf("\n\nstrncat(str1,str2,5) : %s\n\n",strncat(str1,str2,5));

printf("\n\nAFTER:\n\nstr1 : %s\t\tstr2 : %s\n\n",str1,str2);

getch();

return 0;

}

========================

String: strcpy()

#include <stdio.h>

#include <conio.h>

int main()

{

char str1[15]="I LIKE ";

char str2[15]="C PROGRAMMIG";

clrscr();

printf("\n\nBEFORE:\n\nstr1 : %s\t\t\tstr2 : %s\n\n",str1,str2);

strcpy(str1,str2);

printf("\n\nAFTER:\n\nstr1 : %s\t\tstr2 : %s\n\n",str1,str2);

getch();

return 0;

}

========================

String: strncpy()

#include <stdio.h>

#include <conio.h>

int main()

{

char str1[25]="I LIKE ";

char str2[15]="C PROGRAMMIG";

clrscr();

Page 191: Learn C Programming Step by Step

P a g e | 190

printf("\n\nBEFORE:\n\nstr1 : %s\t\t\tstr2 : %s\n\n",str1,str2);

strncpy(str1,str2,4);

printf("\n\nAFTER:\n\nstr1 : %s\t\tstr2 : %s\n\n",str1,str2);

getch();

return 0;

}

========================

String: strcmp()

#include <stdio.h>

#include <conio.h>

int main()

{

char str1[]="I LIKE";

char str2[]="C Expert";

int i;

clrscr();

i=strcmp(str1,str2);

if(i==0)

printf("\n\nstr1 and str2 are identical");

else if(i<0)

printf("\n\nstr1< str2");

else

printf("\n\nstr1< str2");

getch();

return 0;

}

========================

Page 192: Learn C Programming Step by Step

P a g e | 191

Reference

1. http://www.cprogramming.com/

2. http://www.cprogrammingexpert.com/

3. Let us C - Yeshwant Kanetkar

4. The C programming Language - Brian W. Kernighan and Dennis M. Ritchie


Recommended