93
Programming In C Language| 2010 Page No :1 Prepared By, Rushabh P Madhu (9662140014) WHAT IS A LANGUAGE ? Language is a collection of words and symbols which can be used to perform certain task or activities and to establish a communication between person to person. In the same manner computer languages are the collection of predefine key words which can be used to perform certain task and to communicate between to entities like between two machines or between human and computers or computers and others peripherals. There are three different level of programming languages. They are (1) Machine languages (Low level) (2) Assembly languages (3) Procedure Oriented languages (High level) (4) Fourth Generation languages (4 GLS) (1) Machine Languages :- Computers are made of No. of electronic components and they all are two – state electronic components means they understand only the 0 – (pulse) and 1 (non – pulse). Therefore the instruction given to the computer must be written using binary numbers. 1and 0. Computers do not understand English or any other language but they only understand or respond to binary numbers (0 and 1). So each computer has its own Machine languages. (2) Assembly Languages :- As it was very tedious to understand and remember 0’s representing numerous data and instruction. So to resolve this problem mnemonics codes were developed. For example add is used as symbolic code to represent addition. SUB is used for subtraction. They are the symbolic representation of certain combination of binary numbers for example : S U B Which represents certain actions as computer understand only Machine language instructions a program written in Assembly Language must be translated into Machine languages. Before it can be executed this translation if done by another program called assembler. This assembler will translate mnemonic codes into Machine languages. (3) Procedure Oriented Languages In earlier assembly languages assembler programs produced only one Machine languages instruction for every assembly languages instruction. So to resolve this problem now assembler were introduced. Which can produce several machine level instructions for one assembly language instruction. Thus programmer was

Programming In C Language| 2010 · PDF fileProgramming In C Language| 2010 Page No :1 Prepared By, Rushabh P Madhu (9662140014) WHAT IS A LANGUAGE ? Language is

Embed Size (px)

Citation preview

Page 1: Programming In C Language| 2010 · PDF fileProgramming In C Language| 2010 Page No :1 Prepared By, Rushabh P Madhu (9662140014) WHAT IS A LANGUAGE ? Language is

Programming In C Language| 2010

Page No

:1 Prepared By, Rushabh P Madhu (9662140014)

� WHAT IS A LANGUAGE ?

Language is a collection of words and symbols which can be used to perform certain task or activities and to establish a communication between person to person.

In the same manner computer languages are the collection of predefine key words which can be used to perform certain task and to communicate between to entities like between two machines or between human and computers or computers and others peripherals.

There are three different level of programming languages. They are

(1) Machine languages (Low level)

(2) Assembly languages

(3) Procedure Oriented languages (High level)

(4) Fourth Generation languages (4 GLS)

(1) Machine Languages :-

Computers are made of No. of electronic components and they all are two – state electronic components means they understand only the 0 – (pulse) and 1 (non – pulse). Therefore the instruction given to the computer must be written using binary numbers. 1and 0.

Computers do not understand English or any other language but they only understand or respond to binary numbers (0 and 1). So each computer has its own Machine languages.

(2) Assembly Languages :-

As it was very tedious to understand and remember 0’s representing numerous data and instruction. So to resolve this problem mnemonics codes were developed. For example add is used as symbolic code to represent addition. SUB is used for subtraction. They are the symbolic representation of certain combination of binary numbers

for example : S U B

Which represents certain actions as computer understand only Machine language instructions a program written in Assembly Language must be translated into Machine languages. Before it can be executed this translation if done by another program called assembler. This assembler will translate mnemonic codes into Machine languages.

(3) Procedure Oriented Languages

In earlier assembly languages assembler programs produced only one Machine languages instruction for every assembly languages instruction. So to resolve this problem now assembler were introduced. Which can produce several machine level instructions for one assembly language instruction. Thus programmer was

Page 2: Programming In C Language| 2010 · PDF fileProgramming In C Language| 2010 Page No :1 Prepared By, Rushabh P Madhu (9662140014) WHAT IS A LANGUAGE ? Language is

Programming In C Language| 2010

Page No

:2 Prepared By, Rushabh P Madhu (9662140014)

relieve from the task of writing and instruction for every machine operation performed. These languages contains set of words and symbols and one can write program with the combination of these keywords. These languages are also called high level languages. Basic, Fortran, Pascal and COBOL. The most important characteristic of high level languages is that it is machine independent and a program written in high level languages can be run on any computers with different architecture with no modification or very little modification.

� WHAT IS LANGUAGE TRANSLATORS?

As we know that computer understand only the instruction written in the Machine

language. Therefore a program written in any other language should be translated to Machine language. For this purpose special programs are available they are called translators or language processors. This special programs accept the user program and check each statement and produces a corresponding set of Machine language instructions. There are two types of Translators.

(1) Compiler :-

A Compiler checks the entire program written by user and if it is free from error and mistakes then produces a complete program in Machine language known as object program. But if it founds some error in program then it does not execute the single statement of the program. So compiler translate whole program in Machine language before it starts execution.

(2) Interpreters :-

Interpreters performs the similar job like compiler but in different way. It translates (Interprets) one statement at a time and if it is error – free then executes that statement. This continues till the last statement in the program has been translated and executed. Thus Interpreter translates and executes the statement before it goes to next statement. When it founds some error in statement it will immediately stop the execution of the program.

Since compiler of Interpreter can translate only a particular language for which it is designed one has to use different compiler for different languages.

Difference of Compiler – Interpreter :-

Error finding is much easier in Interpreter because it checks and executes each statement at a time. So wherever it fine some error it will stop the execution. Where Compiler first check all the statement for error and provide lists of all the errors in the program. Interpreter take more time for the execution of a program compared to Compilers because it translates and executes each statement one by one.

� WRITE A NOTE ON C LANGUAGE :-

� C Language is programming language. C Language is Middle level language.

Page 3: Programming In C Language| 2010 · PDF fileProgramming In C Language| 2010 Page No :1 Prepared By, Rushabh P Madhu (9662140014) WHAT IS A LANGUAGE ? Language is

Programming In C Language| 2010

Page No

:3 Prepared By, Rushabh P Madhu (9662140014)

� C Language is highly structure programming language.

� C Language is developed by Dennis Ritchie in 1972 at Bell laboratory and now bell laboratory is know as a AT&T laboratory.

� The root of all modern language is ALGOL, introduce in early 1960. At this time people started thinking for general purpose language. Therefore an international committee was formed to develop such a language. As a result CPL (Combined Programming Language) was developed at Cambridge.

� Then BCPL (Basic Combined Programming Language) came with the solution of CPL. Meanwhile Ken Thompson has develop ‘Language B’ as a simplification.

� Dennis Ritchie develop C Language combining and with perfect solution of BCPL and B. He added his own logic in it.

� C Language becomes powerful language to solve the general purpose problem. so Dennis Ritchie get achievement in creating ‘C language’.

� FEATURES OF C LANGUAGE

There are several reasons why many computer professionals feel that C is at the top of the list :

• FLEXIBLILITY:

C is a powerful and flexible language. C is used for projects as diverse as operating system, word processor, graphics, spreadsheets and even compilers for other language. C is a popular language preferred by professional programmers. As a result, a wide variety of C compilers and helpful accessories are available.

• PORTABILITY:

C is a portable language. Portable means that a C program written for one computer system can be run on another system with little or no modification. Portability is enhanced by the ANSI standard by C, the set of rules for C compilers.

• COMPACTNESS:

C is a language of few words, containing only a handful terms, called keywords, which serve as the base on which the language’s functionality is built. You might think that a language with more keyword would be more powerful. This isn’t true. As you will find that it can be programmed to do any task.

• REUSABILITY:

C is modular, C code can and should be written in routine called functions. These functions can be reused in other applications or programs. By passing pieces of information to the function, you can create useful, reusable code.

� PROVE C AS MIDDLE LEVEL LANGUAGE

All programming languages can be divided into two categories:

• Problem oriented languages or high languages :

Page 4: Programming In C Language| 2010 · PDF fileProgramming In C Language| 2010 Page No :1 Prepared By, Rushabh P Madhu (9662140014) WHAT IS A LANGUAGE ? Language is

Programming In C Language| 2010

Page No

:4 Prepared By, Rushabh P Madhu (9662140014)

Examples of languages falling in this category are FORTRAN, BASIC, Pascal, etc. These languages have been designed to give a better programming efficiency, faster program development. Generally these languages have better programming capability but they are less capable to deal with hardware or Hardware related programming.

• Machine oriented languages of Low Level Languages :

Examples of languages falling in this category are Assembly language and Machine Language. This languages have been designed to give a better machine efficiency i.e. faster program execution. Generally these languages have better hardware programming capability but it is very difficult and tedious to do create complex application like and business application or some commercial application

• C as Middle Level Language :

C stands in between these two categories. That’s why it is called a Middle Level Language, since it was designed to have both; a relatively good programming efficiency (as compared to Machine Oriented Language) and a relatively good machine efficiency (as compared to Problem Oriented Language).

Page 5: Programming In C Language| 2010 · PDF fileProgramming In C Language| 2010 Page No :1 Prepared By, Rushabh P Madhu (9662140014) WHAT IS A LANGUAGE ? Language is

Programming In C Language| 2010

Page No

:5 Prepared By, Rushabh P Madhu (9662140014)

1. What is Flowchart?

� “Algorithm is a step by step description of how to arrive at a solution to a given problem.”

� “Algorithm can be define as a sequence of instruction that when executed in the specified sequence, the desired result will be obtained.”

� In order to qualify as an algorithm, a sequence of instruction must posses the following characteristics :”

o Each instruction should be precise and unambiguous.

o Each instruction should be executed in a finite time.

o One or more instruction should not be repeated infinitely. This ensures that algorithm will ultimately terminate.

o After executing the instruction (when the algorithm terminates), the desired result are obtained.

[ Example of Algorithm ]

1. What is Flowchart?

Ans.

• Flow chart is a step by step procedure which is used to solve complex program.

• It is a pictorial representation. It is same as algorithm.

• It is represented in symbols.

• It can be read from top to bottom and left to right.

• Symbols are simple and easy to learn. These are very important planning and working

tools in programming.

• After the programming is completed, the flowchart is very important tool for the programmers for tracing the flow of information and logical sequence in a program.

• This helps a new programmer to understand the logic that is used by some other programmer to solve a problem.

[ Example of Flowchart ]

� 2. Advantages of Flowchart.

Ans :- The following are the advantages of the flow chart: -

• Provide better communication.

It provide better communication. The teachers, students, programmer, computer operators and users can get ideas and description of algorithms very quickly and easily.

• Help in algorithm design.

A flowchart can be easily drawn in comparison to writing a program and testing it. The program flow can be easily shown with the help of flowchart. Different algorithm can be easily experimented with flowchart.

Page 6: Programming In C Language| 2010 · PDF fileProgramming In C Language| 2010 Page No :1 Prepared By, Rushabh P Madhu (9662140014) WHAT IS A LANGUAGE ? Language is

Programming In C Language| 2010

Page No

:6 Prepared By, Rushabh P Madhu (9662140014)

• Check program logic.

With the help of flowchart we can see the portion of the program. So accuracy in logic flow is maintained.

• Modification becomes easy.

If u want to some modification in your existing program then it is possible with the

help of flowchart. You can modify your program without disturbing the program

flow.

2. Root of C Language :

� BASIC STRUCTURE OF C PROGRAM

C program can be viewed a s group of building blocks called functions. A function is a subroutine that may include one or more statement designed to perform a specific task.

Page 7: Programming In C Language| 2010 · PDF fileProgramming In C Language| 2010 Page No :1 Prepared By, Rushabh P Madhu (9662140014) WHAT IS A LANGUAGE ? Language is

Programming In C Language| 2010

Page No

:7 Prepared By, Rushabh P Madhu (9662140014)

Any C program may contain one or more section as shown below :

Documentation Section:

This section contains set of comments lines consist of details like program name, author name and purpose or functionality of the program.

Link Section:

This section consist of instructions to be given to the compiler to link functions from the system library. For example if you want to use some mathematical function then you have to define ink for math.h file in link section.

For Example:- # include<stdio.h>

# include<math.h>

Definition Section:

This section defines all the symbolic constants. For example PI=3.14. By defining symbolic constant one can use these symbolic constant instead of constant value.

Example :- # define PI 3.14

# define Temp 35

Global Declaration Section :

This section contains the declaration of variables which are used by more then more then one function of the program.

Main Function Section :

A main() function is a heart of any ‘C’ language program. Any C program is made up of 1 or more then 1 function. If there is only 1 function in the program then it must be the main program. An execution of any C program starts with main() function.

Subprogram Or Sub Function Section :

They are the code section which are define outside the boundary of main function. This

function can be called from any point or anywhere from the program. Generally they are

define to solve some frequent tasks.

� DATA TYPES IN C :

C language has very rich set of data types. At presently we will go through some of the basic data types available in C.

1. Fundamental Data type (Primary Data type) :

2. Derived Data type :

3. User Define Data type :

Primary Data type of ANSI C is further divided into two part.

A. Integral

Page 8: Programming In C Language| 2010 · PDF fileProgramming In C Language| 2010 Page No :1 Prepared By, Rushabh P Madhu (9662140014) WHAT IS A LANGUAGE ? Language is

Programming In C Language| 2010

Page No

:8 Prepared By, Rushabh P Madhu (9662140014)

B. Floating Point

Integral : Integral data type further divided into two parts.

1. Integer :- (integer divided into three parts)

2. Character :- [1] Short integer :-

� short integer has two parts.

� singed short integer and unsigned short integer. � short integer can occupies one byte (8 bits) of memory.

� when short integer is signed it can store -128 to 127.

� when short integer is unsigned it can store 0 to 255.

To print the value of Short integer you have to use %hd code in printf() function and to scan value of Short integer we have to use %hd code.

[2] Integer :-

� Most commonly used data type is integer.

� It has also two parts.

� Singed integer and unsigned integer. � Integer can occupies two byte (18 bits) of memory.

� When integer is signed it can store -32768 to 32767

� When integer is unsigned it can store 0 to 65535

[3] Long Integer :-

� It has also two parts singed long integer and unsigned long integer.

� Long integer can occupies 4 byte (32 bits) of memory.

� when long integer is signed it can store -2147483638 to 2147473637

� when long integer is unsigned it can store 0 to 4294967295

B. Character

Character data type can store one character at a time. When we want to store any string we have to take an array of character. Character occupies one bite of memory.

Example:- char ch=’a’;

II. Floating point :-

Floating point data type is also known as a Real data type. It can store the value which has fraction parts. Floating point is further divided into three parts.

1.Float :-

Float data type occupies 4 byte of memory means 32 bits of memory with 6 digit precision. We can store a value in float data type which has 6 decimal point value. Float is use to store variables like avg, percentage.

Example:-float perc ,average;

2.Double :-

Page 9: Programming In C Language| 2010 · PDF fileProgramming In C Language| 2010 Page No :1 Prepared By, Rushabh P Madhu (9662140014) WHAT IS A LANGUAGE ? Language is

Programming In C Language| 2010

Page No

:9 Prepared By, Rushabh P Madhu (9662140014)

Double can occupies can hold 8 byte of memory means it can hold 64 bits of memory with 10 digit precision.

Example:- double perc ,average;

3.Long double:-

This data type is use when high precision of data is required. This data type is use in scientific calculation. Long double can occupies 10 byte of memory. Example:-long double temp;

(2) Derived Data type:-

Derived data types are those which are provided by C’ Language to us. In general we are using Array and Pointer which are Derived Data type of C language.

(3) User Define Data type:-

C’ Language also provide facility to create our own new data type using typedef. We can create User Define Data Type using Following

Syntax:- typedef <language Datatype> <newDatatypename>

Example:- typedef int number;

Here now we can create a variable of integer type by using numeric Keyword.

Example:- numeric a,b,sum;

� Tokens Of C Language

C has Six types of Tokens.

� Variable / Identifier:

A variable is a named data storage location in your computer’s memory. By using a variable’s name in your program, you are, in effect, referring to the data stored there.

VARIABLE NAMING CONVENTION

To use variables in your C programs, you must know ho to create variable names in C,variables names must adhere to the following rules:

• The name can contain letters, digits, and the underscore character(_).

• The first character of the name must be a letter. The underscore is also a legal first

Page 10: Programming In C Language| 2010 · PDF fileProgramming In C Language| 2010 Page No :1 Prepared By, Rushabh P Madhu (9662140014) WHAT IS A LANGUAGE ? Language is

Programming In C Language| 2010

Page No

:10 Prepared By, Rushabh P Madhu (9662140014)

character, but its use is not recommended.

• Case matters (that is uppercase and lowercase letters). Thus, the names count and Count refer to two different variables.

• C keywords can’t be used as variable names. A keyword is a word that is part of the C language.

� KEYWORDS

There are words with specific meaning to “C” language system. They are known as keywords of “C” language. Keyword must not be used as variable names. There are 32 keywords in “C” language. Which are as under :

Auto Break Continue Case Const Char

Do Goto Double Else Enum Extern

Float For Long Register Return Short

Sizeof Void While Volatile Union Struct

Typedef Switch Unsigned Extern Signed etc.

� OPERATORS

Operator is symbol, which represents, a particular operation that can be performed on some data. The data itself (which can be either a variable or a constant) is called the “operand”. The operator thus operates on operand. They are Classified as

Arithmetic:- ‘+’- plus, ’-‘subtraction , ‘*’-multiplication ,’/’division ,’%’modulo

‘>’greater than, ’<’ less than. ‘>=’greater than or

equal to

Relational:-

‘<=’ less than or equal to, ’==’equal to , ’!=’ not equal to

Logical :- && logical AND, ’||’ logical OR , ’!’ logical NOT

& bitwise AND, ’|’ bitwise OR , ’^’ bitwise exclusive OR

Bitwise:-

‘<<’ shift left, ‘>>’shift right

Conditional :- “? : “(exp1 ? exp2 :exp3)

Incre.&

decre.:- ++, --

Assingnment:- “=” Single equal to

Special :- “,” comma operator and sizeof() operator

� Special symbols:-

Page 11: Programming In C Language| 2010 · PDF fileProgramming In C Language| 2010 Page No :1 Prepared By, Rushabh P Madhu (9662140014) WHAT IS A LANGUAGE ? Language is

Programming In C Language| 2010

Page No

:11 Prepared By, Rushabh P Madhu (9662140014)

Special symbols are the simple symbol that we often use in ‘C Language’. Some

of the special symbols are following :

, Comma . period : Colon

; Semicolon ? Question mark * Asterisk

“ Double quote ‘ single quote ( Left Parenthesis

) Right Parenthesis [ Left bracket ] Right bracket

_ Underscore sign + plus - minus sign

> Closing angle bracket

< Opening anglebracket

{ Right brace

} Left brace # Number sign $ Dollar sign

% Percentage sign ! Exclamation mark \ Backslash

/ Slash sign ~ Tilde | Vertical bar

� String:- String is an Array of Character Data type. Ex:- char nm[25];

� Constant & string:- Constant means fixed value that can not be changed.

Numric Constant Character Constants

Integer Real single character string Constant

12,24,3648 -0.15242 ‘a’,’A’,z’,’Z’ “Hello”

-12,-916 0.25486,-252.55 ‘0’,’1’,’5’ “well done”

Increment and Decrement Operators :

“C” offers two special operator ++ and – called increment and decrement operators, respectively. There are “unary” operators since they operator on only one operand. The operand has to be a variable and not a constant. Thus the expression a++ is valid as 6++ is invalid. The use of these operates resulting incrementing or decrementing value of the variable is 1. So the expression a++ increment the value of a by 1 and the expression a- - decrements a by 1. These operators can be used either before or after their operand. (i.e. in either “prefix” or “postfix” position) so we can have a++(postfix) and ++a (prefix). Prefix and postfix have some effect if they are used in an isolated statement. For example, the effect of the following statements would be same :

a++;

++a;

However prefix and postfix operators have different effects when used in association with

Page 12: Programming In C Language| 2010 · PDF fileProgramming In C Language| 2010 Page No :1 Prepared By, Rushabh P Madhu (9662140014) WHAT IS A LANGUAGE ? Language is

Programming In C Language| 2010

Page No

:12 Prepared By, Rushabh P Madhu (9662140014)

some other operator in “c” statement. For example, if we assume the value of a variable to be 5 and then assign that new value to b. The effect is exactly same. If the following two statements have been executed :

b = a++;

b =++a;

On the other had, execution of the statement b = a++; will be first set the value of b to 5 and then increases the value of a to 6. The effect is now same as if the following statement had been executed :

b = a; b= a+1;

[ Note : First precedence : R->L associatively)

Conditional operators :

Simple conditional operations can be carried out with the conditional operator (?:) An expression that makes the use of the conditional operator is called a conditional expression. Conditional operators are also known as turnery operators.

Syntax: (condition) ? true : false

Exp1 ? Exp2 : Exp3

Here if condition is evaluated as true then value of exp2 will be return and if condition is

evaluated as false then exp3 will be return.

For example :- T=(I<0) ? 0 : 100

If I variable value is less then 0 then condition is evaluated as true and T will be assigned with 0 but if I variable value is greater then 0 then condition is evaluated as false and 100 will be assign to variable T.

For example:-

Printf(“%d”, (I<0) ? 0:100);

Sizeof () Operator :

The size of a compile time operator and when used with an operand, it returns the number of bytes the operand occupies. The operand may be variable, a constant or a data type qualifies.

M = sizeof(sum);

N= sizeof(long int);

K= sizeof(253L);

The size of operator is normally used to determine the length of array and structures, when their sizes are not known to the programmer. It is used to allocate memory space dynamically to variable during execution of a program.

� DATA INPUT AND OUTPUT

Page 13: Programming In C Language| 2010 · PDF fileProgramming In C Language| 2010 Page No :1 Prepared By, Rushabh P Madhu (9662140014) WHAT IS A LANGUAGE ? Language is

Programming In C Language| 2010

Page No

:13 Prepared By, Rushabh P Madhu (9662140014)

As we know that any c program is made up of 1 or more then 1 function. Likewise it use some functions for input output process. The most common function are printf() and scanf().

Printf() function :

Printf() function is use to display something on the console or to display the value of some variable on the console The general syntax for printf() function is as follows. Printf() function is a member of Stdio.h (Standartd Input Output HeaderFile).

Syntax :- printf(<”format string”>,<list of variables>);

To print some message on the screen

Printf(“God is great”); //Thiswill print message ‘God is great’ on the screen or Console.

More Examples: Output:

printf(“\nIndia is the best”); India is the best

printf(“\nVande Matram”); Vande Matram

printf(“\nJay Hind”); Jay Hind

To print the value of some variable on the screen Integer Variable :

int a=10;

printf(“%d”,a);

Here %d is format string to print some integer value and a is the integer variable whose value will be printed by printf() function. This will print value of a “10” on the screen. You can make this output interactive by writing them

int a=10;

Printf(“a=%d”,a);

This will print “a=10” on the screen To print multiple variable’s value one can use printf() function in following way.

int p=1000,r=10,n=5;

Printf(“amount=%d rate=%d yeat=%d”,p,r,n);

This will print “amount=1000 rate=10 year=5” on the screen.

To Print the value of Float Variable on Screen :

float per=70.20;

printf(“Percentage=%f”,per);

Here %f is format string to print some float(real) value and per is the float variable whose

value will be printed by printf() function. This will print value of a “Percentage=70.20” on the screen.

Page 14: Programming In C Language| 2010 · PDF fileProgramming In C Language| 2010 Page No :1 Prepared By, Rushabh P Madhu (9662140014) WHAT IS A LANGUAGE ? Language is

Programming In C Language| 2010

Page No

:14 Prepared By, Rushabh P Madhu (9662140014)

To Print the value of Character Variable :

char ans=’Y’;

printf(“Answer=%c”,ans);

Here %c is format string to print single character value and ans is the character variable whose value will be printed by printf() function. This will print value of a “Answer=Y” on the screen. Suppose we want to print “Amar” on the screen with character variable.

Char c1=’A’,c2=’m’,c3=’a’,c4=’r’ ;

Printf(“Name = %c %c %c %c”,c1,c2,c3,c4);

This will print “Name=A m a r” on the screen.

You can use single printf() function to print different data type variable’s value also.

Example

int rno=10;

Char res=’P’;

Float per=75.70;

Printf(“Rollno=%d Result=%c Percentage=%f”,rno,res,per);

This will print message “Rollno=10 Result=P Percentage=75.70” on the screen.

Scanf() Function :

Scanf() function is use to read data from keyboard and to store that data in the variables. The general syntax for scanf() function is as follows.

Syntax :- Scanf(“Format String”,&variable);

Here format string is used to define which type of data it is taking as input this format string can be %c for character, %d for integer variable and %f for float variable. Where as variable the name of memory location or name of the variable and & sign is an operator that tells the compiler the address of the variable where we want to store the value. One can take multiple input of variable with single scanf() function but it is recommended that there should be one variable input with one scanf() function.

Scanf(“Format string1,format string2”,&variable1,&variable2);

For Integer Variable :

int rollno;

Scanf(“%d”,&rollno);

Printf(“Enter rollno=”);

Here in scanf() function %d is a format string for integer variable and &rollno will give the address of variable rollno to store the value at variable rollno location..

For Float Variable :

Page 15: Programming In C Language| 2010 · PDF fileProgramming In C Language| 2010 Page No :1 Prepared By, Rushabh P Madhu (9662140014) WHAT IS A LANGUAGE ? Language is

Programming In C Language| 2010

Page No

:15 Prepared By, Rushabh P Madhu (9662140014)

float per;

Printf(“Enter Percentage=”);

Scanf(“%f”,&per);

Here in scanf() function %f is a format string for float variable and &per will give the address of variable per to store the value at variable per location.

For Character Variable :

Char ans;

Printf(“Enter answer=”);

Scanf(“%c”,&ans);

Here in scanf() function %c is a format string for character variable and &ans will give the address of variable ans to store the value at variable ans location.

Single character input – the getchar function :

Single characters can be entered into the computer using the “C” library function getchar. The getchar function is a part of the standard “C” language I/O library. It returns a single character from a standard input device (typically a keyboard). The function does not required any arguments through a pair of empty parentheses must follow the word getchar. In general terms, a reference to the getchar function is written as.

Character variable=getchar();

Where character variable refers to some previously declared character variable. A “C” program contains the following statements.

char c;

c=getchar();

The first statement declares that c is a character type variable. The second statement causes a single character to be entered from the standard input device and then assigned to c. If an end-of file condition is encountered when reading character with the getchar function, the value of the symbolic constant EOF will automatically be returned. The detection of EOF in this manner offers a convenient way to detect an end of file, whenever and wherever it may occur. Appropriate corrective action can be taken. The getchar function can also be used to read multi character strings, by reading one character at a time a multiples loop.

Single character output – The putchar function:

Single character can be displayed (i.e. written out of the computer) using the C library function putchar.T he putchar function, like getchar is a part of the standard “C” language I/O library. It transmits a single character to a standard output device. The character being transmitted will normally be represented as a character-type variable. It must be expressed as an argument to the function, enclosed in parentheses following the word putchar. In general a reference to

Page 16: Programming In C Language| 2010 · PDF fileProgramming In C Language| 2010 Page No :1 Prepared By, Rushabh P Madhu (9662140014) WHAT IS A LANGUAGE ? Language is

Programming In C Language| 2010

Page No

:16 Prepared By, Rushabh P Madhu (9662140014)

the putchar function is written as Putchar (character variable) Where character variable refers to some previously declared character variable.

A “C” program contains the following statements.:

char c=’a’;

putchar(c);

The first statement declares that c is character type variable. The second statement causes the current value of c to be transmitted to the standard output device where it will be displayed. The putchar function can be used to output a one-dimensional, character type array. Each character can then be written separately within a loop.

� Write a note on Backslash Characters :-

C supports some special backslash character constant that are used in output functions. The ‘\n’ is used for new line character. A list of such backslash character constants are given in the following table. This character combinations are known as escape sequences.

Constant Meaning

‘\a’ Alert

‘\n\ New line

‘\v’ Vertical tab

‘\t’ Horizontal tab

‘\b’ Back space

‘\f’ Form feed

‘ \’ ‘ Single quote

‘ \’’ ‘ Double quote

‘\?’ Question mark

’\\’ backslash

‘\0’ Null

� DECISION CONTROL STRUCTURE :

We have seen that a C program is a set of statements which are normally execute in the order in which they appear. This happen when no option or no repetition of certain calculation are necessary. However, in practice, we have a number of situation where we may have to change their order of execution of statements based on certain condition, or repeat a group of statement until certain specified conditions are met. This involves a kind of decision making to see whether a particular condition has occurred or not and then direct the computer to execute certain statements accordingly.

C Language provides following statements as a Decision Making in C.

Page 17: Programming In C Language| 2010 · PDF fileProgramming In C Language| 2010 Page No :1 Prepared By, Rushabh P Madhu (9662140014) WHAT IS A LANGUAGE ? Language is

Programming In C Language| 2010

Page No

:17 Prepared By, Rushabh P Madhu (9662140014)

1. Simple IF

2. If ….Else…

3. If ….Elseif…elseif…else

4. Nested Of If..

5. Switch case

Simple IF :-

The if statement is a powerful decision making statement and it is used to control the flow of execution of statement. It is a two way decision statement and it used in conjunction with an expression.

The general form of if condition is following :-

Syntax: Example

if(test expression)

{

Block of Statements ;

}

printf(“enter any number”);

scanf(“%d”,&no);

if(no==10)

{

printf(“you have enter ten:”);

}

From the above syntax we can see that if the test condition becomes true A block of statement between the if is execute otherwise it will not execute. And cursor go to the next statement after the condition.

If else statement:-

The if else statement is extention of the simple if statement. The general form of if else condition is following :-

Syntax: Example

if(test expression)

{

True Part;

}

else

{

False Part;

}

printf(“enter any number”);

scanf(“%d”,&no);

if(no>0)

{

printf(“No is Positive:”);

}

else

{

printf(“No is Positive:”);

}

From the above example we can see that if the test condition becomes true true part is execute otherwise False part is execute And then cursor go to the next statement after the condition.

The else if ladder :-

Page 18: Programming In C Language| 2010 · PDF fileProgramming In C Language| 2010 Page No :1 Prepared By, Rushabh P Madhu (9662140014) WHAT IS A LANGUAGE ? Language is

Programming In C Language| 2010

Page No

:18 Prepared By, Rushabh P Madhu (9662140014)

There is another way of putting ifs together when multi-path decisons are involved. A multi-path decison is a chainif ifs in which statement associated with each else is an if. The genaral form of else if ladder is following:

Syntax: Example

if(test expression)

{

statement-Block-1;

}

elseif (test expression-2)

{

statement-Block-2;

}

elseif (test expression-3)

{

statement-Block-3;

}

else

{

default block;

}

printf(“enter Percentage :”);

scanf(“%d”,&per);

if(per>=70)

{

printf(“Distinction:”);

}

elseif(per>=60)

{

printf(“First Class:”);

}

elseif(per>=50)

{

printf(“Second Class:”);

}

elseif(per>=40)

{

printf(“Pass Class:”);

}

else

{ printf(“Fail”);

}

Here Block 1,2,3 may contain one or more statement. This construct is know as a else-if ladder. If condition 1,2,3 becomes false, then the statement-4 will be executed. Depending upon the true condition, the statement block will be executed. Subsequently the control goes to the next statement.

Nesting of if else statement:-

When a series of statement is involved, we may have to use more than one if else statement in nested form as shown below :-

Syntax: Example

if(<test expression-1>) printf(“Enter any Three value :”);

Page 19: Programming In C Language| 2010 · PDF fileProgramming In C Language| 2010 Page No :1 Prepared By, Rushabh P Madhu (9662140014) WHAT IS A LANGUAGE ? Language is

Programming In C Language| 2010

Page No

:19 Prepared By, Rushabh P Madhu (9662140014)

{ if (<test expression-2>)

{ Block-1;

}

else

{ Block – 2;

}

}

else

{ if (<test expression-3>)

{ Block-3;

} else

{ Block – 4;

}

}

scanf(“%d %d %d”,&v1,v2,v3);

if(v1>v2)

{ if (v1>v3)

{ printf(“v1 is max:”);

} else

{ printf(“v3 is max:”);

}

}else

{ if(v2>v3)

{ printf(“V2 is Max :”);

} else

{ printf(“V3 is Max:”);

}

}

In the above example we can see that if the test condition-1 becomes it check whether the conditin-2 is true, if it find true block of statement –1 is execute and if condition become false it check if the condition-3 is true, if it find true it execute block of statent-2.And if condition-1 and condition-2 both become false it execute a block of statenent-3 is execute.

Switch statement :-

We can use multiple if’s when we have many alternatives, However, the complexity of a program increases dramatically when a number of alternatives increases. The program become difficult to read and follow. Therefore C had built in many statement known as a switch. The switch statement tests the value of a given variable or expression against a list of case values and when a match is found, a block of statements associated with that case is executed. The syntax of switch statement is following:

Syntax: Examples:

switch(<expression>)

{

case value-1:

block-1

break;

case value-2:

block-2

break;

case value-3:

block-3

break;

..........

Printf(“Enter Percentage :”);

Scanf(“%d”,&p);

Switch(per/10)

{

case 9: case 8: case 7:

Printf(“Distinction”);

case 6:

Printf(“First”);

case 5:

Printf(“Second”);

case 4:

Printf(“Pass”);

Page 20: Programming In C Language| 2010 · PDF fileProgramming In C Language| 2010 Page No :1 Prepared By, Rushabh P Madhu (9662140014) WHAT IS A LANGUAGE ? Language is

Programming In C Language| 2010

Page No

:20 Prepared By, Rushabh P Madhu (9662140014)

…......

Default

default block

}

default :

Printf(“Result is Fail”);

}

The expression must be either in integer or any character. The break statement at the end of each case block signal the end of particular case and causes and exit from the switch statement. The default is optional case. When present, it will be executed if the value of expression does not match with the any case.

� LOOP CONTROL STRUCTURE

If we want to perform certain action for no of times(More than one time) or we want to execute same statement or a group of statement repeatedly then we can use different type of loop structure available in C.

Looping :-

“ Looping is the process to execute a block of statements more than one time or until the specified condition in not becomes false. ”

There are Two types of Loop:

Entry Controlled Loop:-

Entry Controlled Loop Checks the Condition First and then execute a block of statement as long as the condition is becomes true.

Exit Controlled Loop:

Exit Controlled Loop Checks the Condition at Last so before the condition is checked at least one time loop is execute. And if the condition is true then block of statement is execute as long as the condition becomes true.

Page 21: Programming In C Language| 2010 · PDF fileProgramming In C Language| 2010 Page No :1 Prepared By, Rushabh P Madhu (9662140014) WHAT IS A LANGUAGE ? Language is

Programming In C Language| 2010

Page No

:21 Prepared By, Rushabh P Madhu (9662140014)

Basically there are 3 types of loop structure available in C

(1) While loop (2) Do..while (3) For loop

While statement :

The while loop is an entry-controlled loop. The test condition is evaluated and if the condition is true, then the body of the lop is executed. After the execution of the body, the test condition is again evaluated and if it is true, the body is executed once again. This process of repeated execution of the body continues until the test condition is become false. When the condition becomes falls control is transferred to a statement after the loop’s statement.

Syntax: Example:

Initialization;

While(exp)

{

statement 1;

statement 2;

increment/ decrement;

}

Int i=1;

While(i<=10)

{

Printf(“ i= %d”,i);

I=i+1;

}

Exit Controlled Loop

Entry Controlled Loop

Condition

Next Statement Next Statement

True True

False

False

Condition

Page 22: Programming In C Language| 2010 · PDF fileProgramming In C Language| 2010 Page No :1 Prepared By, Rushabh P Madhu (9662140014) WHAT IS A LANGUAGE ? Language is

Programming In C Language| 2010

Page No

:22 Prepared By, Rushabh P Madhu (9662140014)

The part of while statement, which contains the statement, is called the body of the loop. Body of the loop may have one or more statements. The braces are needed only if the body contains two or more statements. However, it is a good practice to use braces even if the body has only one statement. Suppose we want to display the consecutive digits 0,1,2,3,…10 above example is use.

Do-While statement :

The do statement is same as while statement with some little difference. In the do loop test condition is evaluated at the bottom of the loop do.......while is called Exit controlled loop. In do loop the statement written between the do loop is at least one time execute. On reaching the do statement, the body of the loop is evaluate and at the bottom test condition is evaluated, if it is true the body of the do is once again evaluated. This process is continued until the test condition becomes falls :

Syntax : Example:-

Do

{

statement1;

statement2;

increment/decrement operator;

} while(expression);

int i=1;

do

{

Printf(“%d”,i);

I=i+1;

}while(i<=10);

FOR statement :

The for statement is another entry controller that provides a more concise loop control

structure. The general form of the for loop is :

Syntax : Example:

For(initialization, test condition,

increment)

{

statement 1;

statement 2;

}

For(i=1;i<=10;i++)

{

Printf(“%d”,i);

}

This for loop is executed 10 times and prints the digits 1 to 10 in one line.

The execution of the for statement is as follows :

1. Initialization of the control variables is done first, using assignments statement such as I=0 and count=0. The variables I and count are known as loop controls.

2. The value of the control variables is tested using the test condition. The test condition is relational expression, such as I>0 or I<10 that determines when the

Page 23: Programming In C Language| 2010 · PDF fileProgramming In C Language| 2010 Page No :1 Prepared By, Rushabh P Madhu (9662140014) WHAT IS A LANGUAGE ? Language is

Programming In C Language| 2010

Page No

:23 Prepared By, Rushabh P Madhu (9662140014)

loop is terminated and the execution continues with statement that immediately follows the loop.

3. When the body of the loop is executed, the control is transferred back to the for statement either evaluating the last statement is the loop. Now, the control variable is incremented using and assignment statement such as I=I+1 and if the new value of the control is satisfied under test condition, then the body of the loop is executed. This process continues till the value of the control variable fails to satisfy the test-condition. The three sections within parentheses must be separated by a semicolons. Note that there is no semicolon at end of the increment section x++.

The for statement allows for negative increments. For example, the loop discussed above can be written as follows:

For(x=9; x>=0; x--)

{ Printf(“%d”,x0

Printf(“/n”);

}

This loop is also executed 10 times. But the output would be from 9 to 0 instead of 0 to 9. Note that, braces are optional when the body of the loop contains only one statement.

Additional features of for loop :

The for loop in C has several capabilities that are not found in the other loop constructs. For example, more than one variable can be initialized at a time in the for statement.

For(n=1,m=50; n<m; n++, m--)

{

p=m/n;

printf(“%d%d%d \n”,n,m,p);

}

This is perfectly valid. The multiple arguments in the increment section are separated by commands. The third feature is that the test condition may have nay compound relation and the testing need not be limited only to the loop control variable. Consider the example below :

Sum=0;

For(I=1;I<20 && sum<100; I++)

{

sum=sum+I;

printf((“%d \n”, sum);

}

The loop uses a compound test condition with the control variable; and external variable sum. The loop is executed as long as both the conditions I<20 and sum<100 are true. The sum is evaluated inside the loop. It is also permissible

Page 24: Programming In C Language| 2010 · PDF fileProgramming In C Language| 2010 Page No :1 Prepared By, Rushabh P Madhu (9662140014) WHAT IS A LANGUAGE ? Language is

Programming In C Language| 2010

Page No

:24 Prepared By, Rushabh P Madhu (9662140014)

to use expressions in the assignment statements of initialization and increment sections, For example, a statement of the type.

� BREAK STATEMENT:

The break statement is used to terminate loops or to exit a switch. The break statement will break or terminate the inner-most loop. It can be used within a while, a do-while, a for or a switch statement. The break statement is written simply as break; Without any embedded expressions or statement. For example,

For(I=1; I<=10; I++)

{ if(I==5)

break;

printf(“\nI=%d”,I);

}

The output will be 1,2,3,4 and then break will terminate this loop and stop the execution of the for loop.

� CONTINUE STATEMENT

The continue statement is used to skip or to bypass some step or iteration of looping structure. It does not terminate the loop but just skip or bypass the particular sequence of the loop structure. It is simply written as continue.

For(I=1; I<=10; I++)

{

if(I==5)

continue;

printf(“\nI=%d”,I);

}

The output of the above program will be 1,2,3,4,6,7,8,9,10. The 5th iteration of the loop will be skipped as we have define the continue for that iteration. So it will not print the value ‘5’.

� THE 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. In its general for the goto statement is written as goto label; Where label is an identifier used to label the target statement to which control will be transferred.

Control may be transferred to any other statement within the program. The target statement must be labeled and the label must be followed by a color. Thus the target statement will appear as label : statement. Each labeled statement within the program must have unique label, i.e. no two statement can have same label.

C support the goto statement to branch unconditionally from one point to another in the program. Although it may not be essential to use the goto statement in highly structured programming like C.

Page 25: Programming In C Language| 2010 · PDF fileProgramming In C Language| 2010 Page No :1 Prepared By, Rushabh P Madhu (9662140014) WHAT IS A LANGUAGE ? Language is

Programming In C Language| 2010

Page No

:25 Prepared By, Rushabh P Madhu (9662140014)

The goto requires a label in order to identify the place where the branch is to be made, A label is any valid variable name, and must follow by the colon. The label is placed where immediately before the statement where the control is to be transferred. the syntax of goto and label statement is following:

Forward jump Backward jump

goto label; label:

........... statements;

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

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

label: ..............

statements; goto label;

If the label : is before the statement goto is formed and some statements will be execute repeatedly. Such jump is known as backward jump. On the other hand if the label: is placed after the goto label: statement, some statement will be skipped and jump is known as forward jump.

Example-1 (Forward Jump) Example-2(Backward Jump)

Void main()

{ Int i=1;

For(i=1;i<=100;i++)

{

Printf(“%d”,i);

If (i==20) goto end;

}

End:

Getch();

}

Void main()

{ Int i=1;

Start :

Printf(“%d”,i);

I=i+1;

If (i<=10)

goto Start:

Getch();

}

� ARRAY

“Array is a collection or group of similar data type elements stored in contiguous memory.”

“Array is a collection of variables having same name and same datatype but with the different index value.”

The individual data items can be characters, integers, floating points numbers and so on . Here contiguous memory allocation means array occupies contiguous bytes as needed in the memory.

� DEFINING AN ARRAY :

Arrays are defined in much the same manner as ordinary variables. Except that each array name must be accompanied by a size specification number of elements for a one-dimensional array. The size specified by positive

Page 26: Programming In C Language| 2010 · PDF fileProgramming In C Language| 2010 Page No :1 Prepared By, Rushabh P Madhu (9662140014) WHAT IS A LANGUAGE ? Language is

Programming In C Language| 2010

Page No

:26 Prepared By, Rushabh P Madhu (9662140014)

integer expression enclosed in square brackets. The expression is usually written as a positive integer constants. For example if we want to declare an array of 10 integer values then we can define it as following. The general form is Storage class data type array[expression] = {vlaue1, value2,…value n}

Some notes about array:-

� Array is a collection of similar type of data.

� Array is also known as a subscripted variable.

� Same as other variable, before using any array variable it must be declared with it’s datatype.

� First element of an array is start with 0.so the last element is always less than the size of array.

Example of an array is following:

int no[10]; (will declare array on ten integer value.)

Types of Array:-

1.Single dimensional Array:-

2.Two dimensional Array:-

3.Multi dimensional Array:-

� Single Dimension Array :-

“A list of items can be given one variable name using only one subscript and

such a variable is called One dimension array.”

� Declaration:-

Like any other variable arrays must be declared before they are used. The syntax of declare one dimensional array is following:

� Syntax:-

<data type> <variable name>[ <size>];

Example:- int no[10];

� Initialization of One dimensional Array:-

1.Compiletime initialization:-

int no[5]={10,20,30,40,50};

Each array elements is referred to by specifying the array name followed by one or more subscripts. With each subscript enclosed in square brackets. Each subscript must be expressed as a non-negative integer : thus in the n- element array x, the array elements arr[0], arr[1], arr[2]…arr[n-1]. The value of each subscript can be expressed as an integer constant, an integer variable or a more complex integer expression.

The number of subscripts determines the dimensionality of the array. For example, x[I] refers to an element in the one dimensional array x. Similarly y[I][j] refers to an element in the two dimensional array..

2.Runtime initialization:-

Page 27: Programming In C Language| 2010 · PDF fileProgramming In C Language| 2010 Page No :1 Prepared By, Rushabh P Madhu (9662140014) WHAT IS A LANGUAGE ? Language is

Programming In C Language| 2010

Page No

:27 Prepared By, Rushabh P Madhu (9662140014)

One can assign the value of array variable at the time run.

Example:- for(i=0;i<10;i++)

{ if(i<5)

no[i]=1;

else

no[i]=2;

}

Here the first five element of an array no initialized to 1 and while remaining elements are initialized by 2 at runtime.

Example :

Void main()

{ Int I, n, no[10];

clrscr();

printf(“Enter How Many Values :”);

scanf(“%d”,&n);

printf(“\n \t\t Input”);

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

{

printf(“Enter %d value:”,i);

scanf(“%d”,&no[i]);

}

printf(“\n \t\t Output”);

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

{

printf(“The value Stored at [%d] Element is %d”,I,no[i]);

}

getch();

}

� Two dimensional Array:-

There could be a situation where a table of values will have to be stored therefore think this table is matrix consisting rows and column. In mathematics we represent a particular value in a matrix by using two subscripts such as Vij. Here V represent the entire matrix and Vij refers the value in the matrix Ith row and Jth column.

� Initialization of Two dimensional Array:-

Two dimensional array can be initialized as following:

Syntax:- <data type> <variable name> [<row>][ <cols>];

Example:- float a[3][3];

Here we declare a with 3 rows and 3 column, and with 3 rows and 3 column. Generally For loop is used to initialize a value in a two dimensional array.

Example:- float a[3][3]={1,1,1,2,2,2,3,3,3};

Page 28: Programming In C Language| 2010 · PDF fileProgramming In C Language| 2010 Page No :1 Prepared By, Rushabh P Madhu (9662140014) WHAT IS A LANGUAGE ? Language is

Programming In C Language| 2010

Page No

:28 Prepared By, Rushabh P Madhu (9662140014)

Here we initialize the elements of the first row to 1 and second row to 2 and third rows to 3 is done row by row. we can also declare as;

Example:- float a[3][3]={{1,1,1},{2,2,2},{3,3,3}};

(we can also initialized by above method.)

Example :

Void main()

{ Int I, n,j,no[3][3];

clrscr();

printf(“\n \t\t Input”);

printf(“\n Enter values of [3] * [3] Metrix :”);

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

{

for(j=0;j<3;j++)

{

printf(“Enter value of [%d][%d] column :”,i,j );

scanf(“%d”,&no[i][j]);

}

}

printf(“\n \t\t Output”);

for(i=0;i<3;j++)

{

for(j=0;j<3;j++)

{

printf(“The value Stored at [%d] [%d] Element is %d”,I,j, no[i][j]);

}

getch();

}

� Multi dimensional Array:-

C allows of three or more dimensions. The exact limit is determine the complier. The syntax of multidimensional array is following:

Syntax:- <data type> <variable name> <[s1]><[s2]>...<[sm]>;

Example:- int no[3][4][5];

Example:- float a[2][3][4][5];

Here no is three dimensional array and it contain 60 elements of integer type. And variable a is four dimensional array and it contain 120 elements of float type data. Generally nested for loop constructed is used to assign a value in multidimensional array at runtime.

Multidimensional arrays are processed in the same manners as one-dimensional arrays, an element-by-element basis. However, some care is required when passing multidimensional arrays to a function. In particular, the formal argument declarations within a function definition must include explicit size specifications in all of the subscript positions except the first. These size specification must be consistent with the corresponding size specifications in the calling program. The first subscript position may be written as an empty pair of square brackets as with a one-dimensional array.

Page 29: Programming In C Language| 2010 · PDF fileProgramming In C Language| 2010 Page No :1 Prepared By, Rushabh P Madhu (9662140014) WHAT IS A LANGUAGE ? Language is

Programming In C Language| 2010

Page No

:29 Prepared By, Rushabh P Madhu (9662140014)

At individual array element that are not assigned explicit values will automatically to set to zero. This includes the remaining elements of an array in which certain elements have been assigned non zero values.

The array size need not be specified explicitly when initial values are included as a part of an array definition, with a numerical array, the size will automatically be set equal to the number of initial values included within the definition.

� ARRAY AND STRINGS (Gets and Puts)

The gets() and puts() functions:

The gets() and puts() functions facilitate the transfer of strings between the computer and the standard input/output devices. Each of these functions accepts a single argument. The argument must be a data item that represents a string(e.g. character array). The string may include white space characters. In the case of gets, the string will enter from the keyboard and will terminate with a new line character(i.e. the string will end when the user presses the RETURN key). The gets and puts functions offer simple alternatives to the use of scan f and printf for reading and displaying strings, as illustrated in the following example. Here is a program that reads a line of text into the computer and then writes it back out in its original form :

#include<stdio.h>

main()

{

char nm[20];

gets(nm);

puts(nm);

} This program utilizes gets and puts to transfer the line of text into and out of the computer. Most C compilers include library functions that allow strings to be compared. Copied or concatenated. Other functions permit operations on individual character within strings. For example, they allow individual characters to be found within strings and so on. The following example illustrate the use of some of these library functions :

� THE SCPOE AND LIFETIME OF VARIABLES IN FUNCTION :

A variable in C can have any one of the four storage classes :

� Automatic variable :-

This is type of variables are declared inside the function in which they utilize. They are created when function are called and destroyed automatically when the function exited. Automatic variables are also known as a private variable or local variable or internal variables.

A variable declared inside a function without specify any storage class is by default an automatic variable

Page 30: Programming In C Language| 2010 · PDF fileProgramming In C Language| 2010 Page No :1 Prepared By, Rushabh P Madhu (9662140014) WHAT IS A LANGUAGE ? Language is

Programming In C Language| 2010

Page No

:30 Prepared By, Rushabh P Madhu (9662140014)

main()

{ int i,j;

........

........

} // Here I and J is automatic variable.

� External variable :-

This type of variables are declared outside the main() and UDF fuction. External variables are also known as Global variable. Once a Global variable is declared all the function can use it and any function can change its value. This function remain alive and active in the program. At the time of declare we must have to specify the data type of variable as automatic variable.

int f=1;

main()

{ int i,j;

........

........

} //Here F is External variable. Any function can use it and change its value.

� Static variable :-

As the name suggest , the value of static variable remain static till the end of program.A static variable can be created using ‘static’ keyword. A static variable can be internal or external both depending upon the place of declaration. Static variable is use in recersion function frequently.

Ex :- static int no;

� Register variable :-

Register variable can be define by using ‘register’ keyword. we can tell the compiler that to keep this variable in one of the machines register, insted of keeping in memory where all the variables are stored. Since register access is much faster than a memory access. Many compiler allow only integer and character variable to keep in register but ANSI should not restrict any.

Ex :- register int no;

� Type Definition (typedef)

C language supports a feature known as a “type definition” that allow user to define a new identifier that would represent an existing data type. the user-defined type data type identifier can later be used to declare variable. the syntax of creating a new identifier:

Syntax:- typedef <data type> <identifier name>;

Ex :- typedef int numeric;

Page 31: Programming In C Language| 2010 · PDF fileProgramming In C Language| 2010 Page No :1 Prepared By, Rushabh P Madhu (9662140014) WHAT IS A LANGUAGE ? Language is

Programming In C Language| 2010

Page No

:31 Prepared By, Rushabh P Madhu (9662140014)

Here we define new identifier named numeric which containe int datatype. Now we can declare any integer variable as numeric.

Ex :- numeric no, rno;

In above example no and rno is integer variable.

Structures

� Structure is a Collection of different types of data into a single unit. � Structure is a user define data type means user can decides type of data for structure collection.

� A Structure is use to handle a logically related data items. For example, it can be use to represent a set of attributes like student’s name, roll no, total, percentage.

� The concept of structure is same as record in many other language.

� Group of similar data type such as int or float can be store in ARRAY (Derived Data Type) type of variables.

Ex. int a[10];

Ex. float sal[10];

� If we want to represent a collection of data items of different types using a single name, then we cannot use an array.

� C supports a constructed data type (User Define Data Type) known as 'STRUCTURE' -- packing data of different types Logically related data.

i.e. a STUDENT(roll_no, stud_Name, Age, Perc) or

a BOOK (bkId, Title, Price, pages, Auther) or

an EMPLOYEE(empno, ename, desig, sal, deptno) etc.....

� Above all example each data item (roll_no, price, sal, Title, stud_name... etc) are called members of structure.

Syntax:-

struct <tag_name>

{

data_type member1;

data_type member2;

:

:

};

���� How to Create a structure

struct Student

{

int roll_no;

char sname[20];

float perc;

};

� How it arrange in Memory….

Name of the Structure

Remember the SEMICOLON…!!!

Page 32: Programming In C Language| 2010 · PDF fileProgramming In C Language| 2010 Page No :1 Prepared By, Rushabh P Madhu (9662140014) WHAT IS A LANGUAGE ? Language is

Programming In C Language| 2010

Page No

:32 Prepared By, Rushabh P Madhu (9662140014)

roll_no Sname perc

� 2 B� � ---------------20 Bytes---------- � � 4 Bytes �

Total Bytes occupied by a structure is 26 bytes

If you use sizeof() operator to print the size use � sizeof(struct Student)

� How to Declare structure type variables…

struct Student s1,s2;

� How to use structure in program…

Each member of the structure is accessed by ‘.’ (dot) operator

i.e. s1.roll_no = 24;

s1.sname = “E.Balagurusamy”; (INVALID)

strcpy(s1.sname, “E.Balagurusamy”); (VALID)

s1.perc = 67.85;

� How to use structure variable to input values from user in program…

Ex. struct Book_Detail

{ int bk_id;

char bname[20];

int pages;

float price;

char auther[20];

}b1,b2;

void main()

{ float pr;

clrscr();

/*********** INPUT PART ***************/

printf(“Enter Book #1 Details\n”);

printf(“Enter Book ID : “);

scanf(“%d”, &b1.bk_id);

printf(“Enter Book Title : “);

scanf(“%s”, b1.bname); // or

gets(b1.bname); // Recommended to use

printf(“Enter Total Book pages : “);

scanf(“%d”, &b1.pages);

printf(“Enter Book price : “);

scanf(“%f”, &b1.price); // Not recommended when structure

member is float

/*********** PRINTING PART ***************/

printf(“Book #1 Details\n”);

printf(“Enter Book ID : %d \n“, b1.bk_id);

scanf(“%f”, &pr);

b1.price =

// Recommended to

Page 33: Programming In C Language| 2010 · PDF fileProgramming In C Language| 2010 Page No :1 Prepared By, Rushabh P Madhu (9662140014) WHAT IS A LANGUAGE ? Language is

Programming In C Language| 2010

Page No

:33 Prepared By, Rushabh P Madhu (9662140014)

printf(“Enter Book Title : %s \n “, b1.bname);

printf(“Enter Total Book pages : %d \n “, b1.pages);

printf(“Enter Book price : %8.2f \n “, b1.price);

getch();

}

Arrays within Structures

C Permit the use of arrays as structure members. We have already array of character inside a structure, Similarly , we can use single-dimensional or multidimensional arrays of type int or float. For example , the following structure declares an array of int in structure.

When we have an array of member of structure it is called array within structure.

#include <stdio.h>

#include <conio.h>

struct stud

{ int rno;

char sname[20];

// int sub1, sub2, sub3; <---------------

int sub[3];// <======================

int total;

float perc;

};

void main()

{ int j;

struct stud s1;

clrscr();

printf("Enter student No. :");

scanf("%d", &s1.rno);

printf("Enter student Name :");

fflush(stdin);

gets(s1.sname);

s1.total = 0;

for(j=0; j<3; j++) // Use of array that is in side the structure

{ printf("Subject : %d = ", j+1);

scanf("%d",&s1.sub[j]);

s1.total += s1.sub[j];

}

s1.perc = s1.total/3.0;

printf("\n============Student's Result===========\n");

printf("Roll No : %d\n",s1.rno);

printf("Name : %s\n",s1.sname);

printf("Total Marks : %d\n",s1.total);

Page 34: Programming In C Language| 2010 · PDF fileProgramming In C Language| 2010 Page No :1 Prepared By, Rushabh P Madhu (9662140014) WHAT IS A LANGUAGE ? Language is

Programming In C Language| 2010

Page No

:34 Prepared By, Rushabh P Madhu (9662140014)

printf("Percentage : %5.2f\n",s1.perc);

getch();

}

Array of Structures:

When we create an array of Structure object, is known as a Array of Structure. We can declare array of structure to store more than one record. Following program demonstrate the Array of Structure.

#include<stdio.h>

#include<conio.h>

Struct student

{

Int rno,m1,m2,m3,tot,per;

char nm[15];

}bca[50];

/* Above Structure example will store bca as a structure and it is an array. So it is an Array of Structure */

void main()

{ int i,n;

clrscr();

printf(“Enter How many Student you Have :”);

scanf(“%d”,&n);

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

{ printf(“Enter RollNo:”);

scanf(“%d”,&bca[i].rno);

printf(“Enter Name:”);

scanf(“%s”,bca[i].nm);

printf(“Enter Marks 1 :”);

scanf(“%d”,&bca[i].m1);

printf(“Enter Marks 2:”);

scanf(“%d”,&bca[i].m2);

printf(“Enter Marks 3:”);

scanf(“%d”,&bca[i].m3);

bca[i].tot=bca[i].m1+bca[i].m2+bca.[i].m3;

}

bca[i].per=bca[i].tot/3;

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

{ printf(“\n Roll No Is = %d:”,bca[i].rno);

printf(“\n Name Is = %s:”,bca[i].nm);

printf(“\n Marks 1 = %d:”,bca[i].m1);

printf(“\n Marks 2 = %d:”,bca[i].m2);

Page 35: Programming In C Language| 2010 · PDF fileProgramming In C Language| 2010 Page No :1 Prepared By, Rushabh P Madhu (9662140014) WHAT IS A LANGUAGE ? Language is

Programming In C Language| 2010

Page No

:35 Prepared By, Rushabh P Madhu (9662140014)

printf(“\n Marks 3 = %d:”,bca[i].m3);

printf(“\n Total is %d “,bca[i].tot);

printf(“\n Percentage is %d “,bca[i].per);

getch();

}

}

Array of Structures and Array Within Structure :

When we create an array of Structure object, is known as a Array of Structure. And when we declare an array of member it is known as Array within structure. When we have array or member and also an array of structure it is known as a array of structure and array within structure.

#include<stdio.h>

#include<conio.h>

Struct student

{ int rno;

int marks[5],tot,per;

char nm[15];

}bca[50] ;

void main()

{ int i,n;

clrscr();

printf(“Enter How many Student you Have :”);

scanf(“%d”,&n);

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

{ printf(“Enter RollNo:”);

scanf(“%d”,&bca[i].rno);

printf(“Enter Name:”);

scanf(“%s”,bca[i].nm);

for(j=0;j<5;j++)

{ printf(“Enter Marks of %d Subject :”,i+1);

scanf(“%d”,&bca[i].marks[j]);

}

bca[i].tot=bca[i].m1+bca[i].m2+bca.[i].m3;

}

bca[i].per=bca[i].tot/3;

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

{ printf(“\n Roll No Is = %d:”,bca[i].rno);

printf(“\n Name Is = %s:”,bca[i].nm);

for(j=0;j<5;j++)

{ printf(“\n Marks of %d subject = %d:”,i+1,bca[i].marks[i]);

}

Page 36: Programming In C Language| 2010 · PDF fileProgramming In C Language| 2010 Page No :1 Prepared By, Rushabh P Madhu (9662140014) WHAT IS A LANGUAGE ? Language is

Programming In C Language| 2010

Page No

:36 Prepared By, Rushabh P Madhu (9662140014)

printf(“\n Total is %d “,bca[i].tot);

printf(“\n Percentage is %d “,bca[i].per);

getch();

}

}

Following Example will Demonstrate the example of Structure Sorting:

struct student

{ int rno,per;

char nm[15];

} bca[10],temp;

void main()

{ int i,n;

clrscr();

printf(“enter how many students:”);

scanf(“%d”,&n);

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

{

printf(“enter roll no:”);

scanf(“%d”,&bca[i].rno);

printf(“enter name :”);

scanf(“%s”,&bca[i].nm);

printf(“enter roll no:”);

scanf(“%d”,&bca[i].per);

}

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

{ for(j=0;j<n;j++)

{ if(bca[i].per>bca[j].per)

{ temp=bca[i];

bca[i]=bca[j];

bca[j]=temp;

}

}

}

printf(“\n \t roll no \t name \t percentage:\n”);

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

{ printf(“\n \t %d:”,bca[i].rno);

printf(“\t %s:”,bca[i].nm);

printf(“\t %d:”,bca[i].per);

}

getch();

}

Page 37: Programming In C Language| 2010 · PDF fileProgramming In C Language| 2010 Page No :1 Prepared By, Rushabh P Madhu (9662140014) WHAT IS A LANGUAGE ? Language is

Programming In C Language| 2010

Page No

:37 Prepared By, Rushabh P Madhu (9662140014)

Difference Between ‘=’ and ‘==’

‘=’ ‘= =’

1.Equal to is a assignment operator. 1.Double equal is a relational operator.

2.Equal operator is mainly used to assigning a value in variable.

2.Double equal is used to check whether the expression1 is equal to the expression2.

3.Example:- no=15 3.Example: if(no==10)

Difference Between ‘*p’ and ‘**p’

‘*p’ ‘**p’

1.’*p’ is a pointer variable. 1.’**p’ is a Double pointer variable.

2.’*p’ is a variable which can hold an address of another variable.

2.’**p’ is a variable which can hold an address of another pointer variable.

3.Example:-

int i=10,*p;

*p=&i;

Here ‘*p’ is a pointer to a integer variable.

3.Example:-

int i=15,*p,**p;

*p=&i;

**p=&*p;

Here ‘**p’ is a pointer to a pointer to point an integer variable.

Difference Between Call by Value and Call By Reference

Call by value Call by reference

1. when we pass any variable or value in function is called call by value.

1. when we pass any address of a variable is called call by reference.

2. Example: s=fact(n); 2. Example: s=fact(&n);

3. call by value is used in general purpose and to pass simple variable.

3. call by reference is used to pass multiple value using array and pointer.

Difference Between Structure and Union

Structure Union

1. In structure each member has its own location.

1.In union all the member use the same memory location and the size of location is depand on the datatype which can hold more bytes.

2. If structure is following:

structure student

2. If union is following:

union student

Page 38: Programming In C Language| 2010 · PDF fileProgramming In C Language| 2010 Page No :1 Prepared By, Rushabh P Madhu (9662140014) WHAT IS A LANGUAGE ? Language is

Programming In C Language| 2010

Page No

:38 Prepared By, Rushabh P Madhu (9662140014)

{ int no,tot

char name;

float perc;

}sizeof( ) will return 9.

{ int no,tot

char name;

float perc;

}sizeof( ) iwill return 4

Difference Between Array and Structure

Array Structure

1. Array is a Derived data type. 1.Structure is a User Define Data type.

2.Array is a collection of related data of element of same data type.

2.Structure is a collection of related data element of different data type.

3.Assigning a value in an array element is very easy.

Example:- no[1]=55;

3.Assigning a value in an structures element is little difficult.

Example:- s1.no=55;

4.we can compare the elements of an array.

Example:- no[1]==no[2];

4.we can not compare the two variable of Structure.

Example:- s1==s2; (Not valid)

5.We cannot copy one array to another by simply.

Example:- no==rno;

5.We can copy structure variable to another by simply.

Example:- s1=s2;

Library Functions :-

A Function which are provided by Language, is known as a Library Function.

� Input Output Related Function :-

printf( ):-

Printf is standard output function. This function is use to write a message on the screen or to print any value of a variable. With the help of this function we can format our result. printf( ) is a member of stdio.h file.

Syntax :- printf(“<Control string>”,arg1,arg2,arg3....,agrn);

Example :- printf(“How are you”);

int no=10;

printf(“\n%d”,&no);

scanf( ):-

Scanf is standard input function. This function is use input any data from the user. Scanf is a member of stdio.h file. This function is not very useful in input string.

Syntax :- scanf(“<Control string>”,arg1,arg2,arg3....,agrn);

Example :- int no=10;

scanf(“%d”, &no);

Page 39: Programming In C Language| 2010 · PDF fileProgramming In C Language| 2010 Page No :1 Prepared By, Rushabh P Madhu (9662140014) WHAT IS A LANGUAGE ? Language is

Programming In C Language| 2010

Page No

:39 Prepared By, Rushabh P Madhu (9662140014)

getch( ):-

This function is use to get one character from the keyboard. There is no need to press enter after giving the character .The character given by user may be an any key from the keyboard like Arrow ,Enter ,Space ,etc. and all printable character also. This function is used t wait until user press any key. This function is a member of conio.h . Getch function returns ASCII value of the character you have pressed.

Syntax :- int getch(void);

Example :- int i;

i=getch( );

If a user will press ‘a’ from the keyboard, the value of i will be 97. If user will press “Enter Key” then the value of i will be 13.(Getch is use for users input)

getche( ):-

This function is very similar to getch( ). But only difference is that, it is use displays the character after getting by the user. Means, this function can be considered as “getch() with echo.

This function is use to get one character from the keyboard. There is no need to press enter after giving the character .The character given by user may be an any key from the keyboard like Arrow ,Enter ,Space ,etc. and all printable character also. This function is used t wait until user press any key. This function is a member of conio.h Getch function returns ASCII value of the character you have pressed.

Syntax :- int getche(void);

Example :- int i;

i=getche( );

If a user will press ‘a’ from the keyboard, the value of i will be 97. If user will press “Enter Key” then the value of i will be 13.(Getch is use for users input)

getchar():-

This function is use to get one character from the user.

Syntax :- character variable=getchar( );

Example :- char ch;

ch=getchar( );

If a user will press ‘a’ from the keyboard, the value of ch will be ‘a’.

gets( ): -

This function is use to get one character from the user. Scanf also works same but difference between them is that scanf does not accept a string. If scanf find space it put null character at that place and stop the inputting. But gets accept space .This function is a member of stdio.h.

Page 40: Programming In C Language| 2010 · PDF fileProgramming In C Language| 2010 Page No :1 Prepared By, Rushabh P Madhu (9662140014) WHAT IS A LANGUAGE ? Language is

Programming In C Language| 2010

Page No

:40 Prepared By, Rushabh P Madhu (9662140014)

Syntax :- gets(<variableName> );

Example :- char ch[20];

gets(ch);

puts( ):-

This function is use to print a string on the screen. It works same as printf( ) function but the difference between printf( ) and puts( ) is that printf() always start from the current position while puts( ) always start with new line.

Syntax :- puts(<variable> );

Example :- char ch[20];

gets(ch);

puts(ch);

clrscr( ):-

This function clears the screen in text-mode and places the cursor on the upper-left corner of the screen, means at(1,1)position. This function is member of <conio.h>

Syntax :- void clrscr(void);

This function has no any argument or no any return value.

(9) textbackground( );-

This function is used to set background color of the displaying text. This function does not effect any text currently on the screen. Once you have called this function, the subsequent functions using direct video output ( like cprintf( ) will use the new color. This function is member of <conio.h>

Syntax :- void textbackground ( int newcolor );

Example :- textbackground(RED+BLINK);

cprintf(“Hello World”);

The above code will set the background color RED. We can also add BLINK in textbackground and text color to blinking the text.

(10) textcolor( );-

This function is used to set text color of the displaying text. This function does not effect any text currently on the screen. Once you have called this function, the subsequent functions using direct video output ( like cprintf( ) ) will use the new color. This function is member of <conio.h>. We can also add BLINK in textbackground and text color to blinking the text.

Syntax :- void textcolor( int newcolor );

Example :- textbackground(RED);

cprintf(“Hello World”);

The above code will set the background color RED and Blinking the text.

cprintf( ):-

This function is similar with the printf( ) function. But, there is difference, that printf( ) function sends the output to Standard Input Stream, while cprintf( ) function sends the output direct to the Video RAM.

Page 41: Programming In C Language| 2010 · PDF fileProgramming In C Language| 2010 Page No :1 Prepared By, Rushabh P Madhu (9662140014) WHAT IS A LANGUAGE ? Language is

Programming In C Language| 2010

Page No

:41 Prepared By, Rushabh P Madhu (9662140014)

Another difference is that the text displayed by the printf( ) function will not have any effect of textcolor or textbackground( ). The text displayed by printf() statement will be always WHITE in BLACK background, while cprintf( ) printf the string according to the attributes set for the output text like textcolor and textbackground.

Syntax :- cprintf(Control string + Prompt);

Example :- cprintf(“Hello World”);

gotoxy( ):-

This function is used to change the position of cursor on the screen in text mode.The screen is considered as xy-plane, and the cursor will be positioned at the location provided by the user in term of ( x,y ).The screen of C language has 25 rows and 80 cols.Here X represent cols and Y represent rows

Syntax :- void gotoxy(int x, int y);

Example :- gotoxy(50,20);

printf(“Hellow World”);

� Mathematical functions :-

sqrt( ):-

This function is a member of math.h file. This function returns the square root of given value. Here, the value must be positive. If we pass negative value program produce Domain error.

Syntax :- double sqrt(double x);

Example :- m=sqrt(91) (Will set the value of m to 9.)

log( ):-

This function is a member of math.h file.This mathematical function returns the natural logarism of given value. Here, the value must be positive. If we pass negative value program produce Domain error.

Syntax :- double log(double x);

Example :- m=sqrt(5) (Will set the value of natural logarism)

ceil( ):-

This function is a member of math.h file. This function returns an integer value that is the nearest smallest integer. Means, this function rounds up, the value of x to nearest integer.

Syntax :- double ceil(double x);

Example :- int c;

c=ceil(5.67) (Will set the value of m to 6.)

floor( ):-

Page 42: Programming In C Language| 2010 · PDF fileProgramming In C Language| 2010 Page No :1 Prepared By, Rushabh P Madhu (9662140014) WHAT IS A LANGUAGE ? Language is

Programming In C Language| 2010

Page No

:42 Prepared By, Rushabh P Madhu (9662140014)

This function is a member of math.h file. This function returns an integer value that is the nearest biggest integer. Means, this function rounds down, the value of x to nearest integer.

Syntax :- double floor(double x);

Example :- int c;

ceil(5.67) (Will set the value of m to 5.)

pow( ):-

This function is a member of math.h file. This mathematics function is use to find the power of X to y. Here the value must be integer otherwise program produces a Domain error.

Syntax :- double pow(double x, double y);

Example :- int p;

p=pow(5,2) (Will set the value of p to 25.)

fmod( ):-

This function is a member of math.h file. This mathematics function returns the remainder value of X to y.

Syntax :- double fmod(double x, double y);

Example :- int f;

f=fmod(5,2) (Will set the value of f to 1)

abs( ):-

This function is a member of ‘stdlib.h’ file. This function returns the absolute value of X. Means the negative value becomes positive and positive remain unchanged.

Syntax :- int abs(int);

Example :- abs(-5) (Will return 5)

fabs( ):-

This function is a member of math.h file. This function is similar to abs( ).It returns the absolute value of X. Means the negative value becomes positive and pos-itive remain unchange. But the difference is that this function also allowed floating point value.

Syntax :- double abs(double x);

Example :- abs(-5.56) (Will return 5.56)

� String related functions :-

strrev( ):-

This function is a member of string.h file. This function returns the reverce string of given string,

Syntax :- char *strrev(char *s);

Example :- char nm=”computer”;

Page 43: Programming In C Language| 2010 · PDF fileProgramming In C Language| 2010 Page No :1 Prepared By, Rushabh P Madhu (9662140014) WHAT IS A LANGUAGE ? Language is

Programming In C Language| 2010

Page No

:43 Prepared By, Rushabh P Madhu (9662140014)

printf(“%s”,strrev(nm));

Above statement will print “retupmoc” on the screen.

strlen( ):-

This function is a member of string.h file. This function returns the numeric lengths of specified string.

Syntax :- int variable=strlen(string);

Example :- int ln;

ln=strlen(“computer”)

Above statement will store ln to 8 because there are ten character in string.

strcpy( ):-

This function is a member of string.h file. This function is use to copy one sting to another. This function also works same as assignment operator.

Syntax :- strcpy(string1,string2);

Example :- strcpy(city, “surat”);

strcat( ):-

This function is a member of string.h file. This function joints two strings together.This function add second string to first string by removing null character.

Syntax :- strcat(string1,string2);

Example :- char st1=”good”,st2=”morning”;

printf(“%s”, strcat(st1, st2));

Above statement will printf “goodmorning” to the screen.

strcmp( ):-

This function is a member of string.h file. This function is use to compare two string of different length. This function return zero if both strings are equal, return positive value if first string is bigger than second and if second string is bigger than first it return negative value.

Syntax :- strcmp(string1,string2);

Example :- char st1=”good”,st2=”good”;

int i;

i=strcmp(st1,st2);

Above statement will store 0 to i variable because both strings are equal.

� Character Type Related functions :-

isdigit( ):-

This function check whether the first leftmost character of the string is digit or not.( Means 0 to 9 ). It return Zero if the character is not digit else non zero is return. This function is a member of ‘ctype.h’ file.

Page 44: Programming In C Language| 2010 · PDF fileProgramming In C Language| 2010 Page No :1 Prepared By, Rushabh P Madhu (9662140014) WHAT IS A LANGUAGE ? Language is

Programming In C Language| 2010

Page No

:44 Prepared By, Rushabh P Madhu (9662140014)

Syntax :- int isdigit(character variable);

Example :- isdigit(‘A’); ( will return False(0) )

isalpha( ):-

This function check whether the first leftmost character of the string is alphabet or not.( Means ‘a to z’ and ‘A to Z’ ) It return Zero if the character is not alphabet else non zero is return. This function is a member of ‘ctype.h’ file.

Syntax :- int isalpha(character variable);

Example :- isalpha(‘A’); ( will return True(Non Zero) )

isalnum( ):-

This function check whether the first leftmost character of the string is alphanumeric or not. ( Means 0 to 9 and ‘a to z’ and ‘A to Z’ )It return Zero if the character is not alphanumeric else non zero is return. This function is a member of ‘ctype.h’ file.

Syntax :- int isalnum(character variable);

Example :- isalnum(‘A’); ( will return True(Non Zero) )

isspace( ):-

This function check whether the first leftmost character of the string is ‘Whitespace’ or not. ( Means Blank Space, Tab, Enter Key or a Form feed).It return Zero if the character is not White space else non zero is return. This function is a member of ‘ctype.h’ file.

Syntax :- int isspace(character variable);

Example :- isspace(‘A’); ( will return True(Non Zero) )

islower( ):-

This function check whether the first leftmost character of the string is in lowercase or not.( Means ‘a to z’). It return Zero if the character is not in lowercase else non zero is return. This function is a member of ‘ctype.h’ file.

Syntax :- int islower(character variable);

Example :- islower(‘A’); ( will return Zero )

isupper( ):-

This function check whether the first leftmost character of the string is in uppercase or not.( Means ‘A to Z’). It return Zero if the character is not in Uppercase else non zero is return. This function is a member of ‘ctype.h’ file.

Syntax :- int isupper(character variable);

Example :- isupper(‘a’); ( will return Zero )

isprint( ):-

This function check whether the first leftmost character of the string is printable character or not.( Means all printable character except the control characters like Esc,Pgup,Pgdown,Arrow,etc). this function return Zero if the

Page 45: Programming In C Language| 2010 · PDF fileProgramming In C Language| 2010 Page No :1 Prepared By, Rushabh P Madhu (9662140014) WHAT IS A LANGUAGE ? Language is

Programming In C Language| 2010

Page No

:45 Prepared By, Rushabh P Madhu (9662140014)

character is not printable else non zero is return. This function is a member of ‘ctype.h’ file.

Syntax :- int isprintf(character variable);

Example :- isprint(‘A’); ( will return Zero )

tolower( ):-

This function is use to convert case of specified character expression in lowercase. This function returns, a character after converting the case. This function is a member of ‘ctype.h’ file.

Syntax :- int tolower(character variable);

Example :- char nm=”NAME”;

printf(“%s”,tolower(nm));

The Above statement will print ‘name’ on the screen.

tolower( ):-

This function is use to convert case of specified character expression in uppercase. This function returns, a character after converting the case. This function is a member of ‘ctype.h’ file.

Syntax :- int tolower(character variable);

Example :- char nm=”jaydev”;

printf(“%s”,tolower(nm));

The Above statement will print ‘JAYDEV’ on the screen.

File Handling related functions :-

fclose( ):- This function is use to close open file as is open with the help of file pointer.

Syntax :- fclose(file pointer);

Example :- fclose(fp);

fopen( ):-

This function is use to open a new file for read, write or appending purpose. we must have to specify file name and mode of the file for which we open the file. File name is string of character.

Syntax :- <file pointer>=fopen(“filename”, ”mode” );

Example :- fp=fopen(“abc.txt”,”w”);

� modes are following : -

w This mode is helpful to open a file for writing purpose.

r This mode is helpful to read a previously saved file for reading purpose. If this file is not exist the file pointer will be null and program not execute properly.

a This mode is use to append in previously created file.

w+ This mode is use to write and reading purpose.

Page 46: Programming In C Language| 2010 · PDF fileProgramming In C Language| 2010 Page No :1 Prepared By, Rushabh P Madhu (9662140014) WHAT IS A LANGUAGE ? Language is

Programming In C Language| 2010

Page No

:46 Prepared By, Rushabh P Madhu (9662140014)

r+ This mode is use to read and writing purpose.

a+ This mode is use to append and reading purpose.

fgetc( ):- This function is use to store one character from open file.

Syntax :- character variable=fgetc(file pointer);

Example :- ch=fgetc(fp);

putc( ):- This function is use to put one character into open file.

Syntax :- putc(<variable>,file pointer);

Example :- putc(ch, fp);

fprintf( ):-

fprintf( ) function also work same as simple printf( ) but the diffrence is that fprintf works in handling the file means to write in a file.

Syntax :- fprintf(<file pointer>,<control string>,list of variables );

Example :- fprintf( fp,”%d %s %f”,rno,name,perc);

fscanf( ):- fscanf( ) function also work same as simple scanf( ) but the diffrence is that fscanf works in handling the file means to read from the file.

Syntax :- fscanf(<file pointer>,<control string>,list of variables );

Example :- fscanf( fp,”%d %s %f”,&.rno,name,&perc);

ftell( ):- ftell( ) function is use to store current position of file into a variable with the help of file pointer. which can be useful later.

Syntax :- int variable=ftell(<file pointer>);

Example :- n=fell(fp);

rewind( ):-

rewind( ) function is use to reset the file pointer to the start of the file.

Syntax :- rewind(<file pointer>);

Example :- rewind(fp);

fseek( ):-

This function is use to move a file pointer to a desired location with in a file.

Syntax :- ftell(<file pointer>, <offset>, position);

Page 47: Programming In C Language| 2010 · PDF fileProgramming In C Language| 2010 Page No :1 Prepared By, Rushabh P Madhu (9662140014) WHAT IS A LANGUAGE ? Language is

Programming In C Language| 2010

Page No

:47 Prepared By, Rushabh P Madhu (9662140014)

File pointer is a pointer to a file, offset is a number or variable of type long and position is an integer numbers. the position can be one of the following.

values --- meaning

0 -- Beginning of file.

1 -- current position of file.

2 -- Ending of file.

Example :- fseek(fp,0,0); (will go to the beginning position)

Example :- fseek(fp,0,2); (will go to the ending of file )

fseek(fp,m.0) (will go forward by m bytes from the current position.)

� Character Type Related functions :-

isdigit( ):-

This function check whether the first leftmost character of the string is digit or not.( Means 0 to 9 ). It return Zero if the character is not digit else non zero is return. This function is a member of ‘ctype.h’ file.

Syntax :- int isdigit(character variable);

Example :- isdigit(‘A’); ( will return False(0) )

isalpha( ):-

This function check whether the first leftmost character of the string is alphabet or not.( Means ‘a to z’ and ‘A to Z’ ) It return Zero if the character is not alphabet else non zero is return. This function is a member of ‘ctype.h’ file.

Syntax :- int isalpha(character variable);

Example :- isalpha(‘A’); ( will return True(Non Zero) )

isalnum( ):-

This function check whether the first leftmost character of the string is alphanumeric or not. ( Means 0 to 9 and ‘a to z’ and ‘A to Z’ )It return Zero if the character is not alphanumeric else non zero is return. This function is a member of ‘ctype.h’ file.

Syntax :- int isalnum(character variable);

Example :- isalnum(‘A’); ( will return True(Non Zero) )

isspace( ):-

This function check whether the first leftmost character of the string is ‘Whitespace’ or not. ( Means Blank Space, Tab, Enter Key or a Form feed).It return Zero if the character is not White space else non zero is return. This function is a member of ‘ctype.h’ file.

Page 48: Programming In C Language| 2010 · PDF fileProgramming In C Language| 2010 Page No :1 Prepared By, Rushabh P Madhu (9662140014) WHAT IS A LANGUAGE ? Language is

Programming In C Language| 2010

Page No

:48 Prepared By, Rushabh P Madhu (9662140014)

Syntax :- int isspace(character variable);

Example :- isspace(‘A’); ( will return True(Non Zero) )

islower( ):-

This function check whether the first leftmost character of the string is in lowercase or not.( Means ‘a to z’). It return Zero if the character is not in lowercase else non zero is return. This function is a member of ‘ctype.h’ file.

Syntax :- int islower(character variable);

Example :- islower(‘A’); ( will return Zero )

isupper( ):-

This function check whether the first leftmost character of the string is in uppercase or not.( Means ‘A to Z’). It return Zero if the character is not in Uppercase else non zero is return. This function is a member of ‘ctype.h’ file.

Syntax :- int isupper(character variable);

Example :- isupper(‘a’); ( will return Zero )

isprint( ):-

This function check whether the first leftmost character of the string is printable character or not.( Means all printable character except the control characters like Esc,Pgup,Pgdown,Arrow,etc). this function return Zero if the character is not printable else non zero is return. This function is a member of ‘ctype.h’ file.

Syntax :- int isprintf(character variable);

Example :- isprint(‘A’); ( will return Zero )

tolower( ):-

This function is use to convert case of specified character expression in lowercase. This function returns, a character after converting the case. This function is a member of ‘ctype.h’ file.

Syntax :- int tolower(character variable);

Example :- char nm=”NAME”;

printf(“%s”,tolower(nm));

The Above statement will print ‘name’ on the screen.

tolower( ):-

This function is use to convert case of specified character expression in uppercase. This function returns, a character after converting the case. This function is a member of ‘ctype.h’ file.

Syntax :- int tolower(character variable);

Example :- char nm=”jaydev”;

Page 49: Programming In C Language| 2010 · PDF fileProgramming In C Language| 2010 Page No :1 Prepared By, Rushabh P Madhu (9662140014) WHAT IS A LANGUAGE ? Language is

Programming In C Language| 2010

Page No

:49 Prepared By, Rushabh P Madhu (9662140014)

printf(“%s”,tolower(nm));

The Above statement will print ‘JAYDEV’ on the screen.

UDF(User Define Function)

• What is Function ? Types of Function? Explain in Brief? • Explain User Define Function ? • List out the types of User Define Function ? • Which are the element of UDF?

What is Function ?

� Function is a Self Contained Block of Statement which is use to perform a specific task.

Types of Function ?

There are two types of Function available in C language.

1. Library Function 2. User Define Function

� Library Functions are also known as a Inbuilt Function. Inbuilt function means the function which are provided by language to the user.

� User Define Function is a block of Statement define by the user by its own logic to perform a specific task of programming.

Library Functions:

Library Functions of C language are stored in Library files. Library Functions are also categories in different parts :

1. Input / Output Functions (Standard Input Output Header File, Stdio.h) 2. Console related Functions (Console Input Output Header File,

Conio.h) 3. Mathematical Functions (Mathematical Functions, Math.h) 4. String Related Function (String Manipulation Function, String.h) 5. Character Type Function (Character Type Functions, Ctype.h) 6. Graphics Related Function (Graphics Related Function, Grphics.h)

Need of UDF:-

� Every C program must have a main( ) function to indicate where the program has to begin its execution.

� Sometimes the program may be become too large and complex and has a result the task of a debugging, testing and maintaining becomes difficult.

� If a program is divided into a functional parts then each part may be independently coded and later combined into a single unit.

� These sub programs called functions.

� These function are easier to understand and debug and test.

Page 50: Programming In C Language| 2010 · PDF fileProgramming In C Language| 2010 Page No :1 Prepared By, Rushabh P Madhu (9662140014) WHAT IS A LANGUAGE ? Language is

Programming In C Language| 2010

Page No

:50 Prepared By, Rushabh P Madhu (9662140014)

� Another benefit of design of function is that it can be called anytime and used any time whenever required. Function can save both time and space.

We know that functions are the real strength of C language. They are easier to define and use. Main is an example of User Define Function while printf and scanf are the library function. In order to make the user of User Define, we need to establish three elements that are related to function.

Elements of UDF:-

1.Function declaration:

2.Function call:

3.Function definition:

Types of UDF:-

1. No Argument and No return value:-

2. Argument but No Return value:-

3. Argument with Return value:-

4. No Argument but Return value:-

Function Declaration :-

Function declaration is an important part of program. Before using any function it must be declared in our C program. Function Declaration is perform in Global Variable Declaration part of C language. Syntax use to declare any User define function is as follow :

Syntax : <Function Return Data type> <Function Name>(<Argument’s Data type) ;

Ex :- void printmessage(void)

------ (No Argument and No Return Value)

Ex :- void findsum(int, int) ------ (Argument and No Return Value)

Ex :- int findmax(void) ------ (No Argument and Return Value)

Ex :- int fact(int) ------ (Argument and Return Value)

Function Call :-

Function call is an important part of user define function because if we define a function and does not call that function, there in no meaning to define that function. Function calling is perform from the main function of C language. Before calling any function it should be declared in memory and there is also definition of that function is present in that program. At the time calling a function we also have to take care that function will return a value of not and if

Page 51: Programming In C Language| 2010 · PDF fileProgramming In C Language| 2010 Page No :1 Prepared By, Rushabh P Madhu (9662140014) WHAT IS A LANGUAGE ? Language is

Programming In C Language| 2010

Page No

:51 Prepared By, Rushabh P Madhu (9662140014)

that function is returning any value it is stored in variable or not. A function can be accessed (i.e. called) by specifying its name, followed by a list of arguments enclosed in parentheses and separated by commas. If the function call does not require any arguments, an empty pair of parenthesis must follow the function’s name. Syntax of Calling a function is as follow :

Syntax : [<Variable_name> = ] <Function_Name> (<Arguments>) ;

Ex :- printmessage() ------ (No Agrument and No Return Value)

Ex :- findsum(int,int) ------ (Agrument and No Return Value)

Ex :- m=findmax(void) ------ (No Agrument and Return Value)

Ex :- f=fact(int) ------ (Agrument and Return Value)

Function Definition :-

Function definition is an independent program module that is specially written to implement the requirements of the function. In order to use this function we need to invoke it at a required place in the program. This is known as function call. Function definition is also known as function implementation.

Syntax :

<Return Data type> <Function Name> (<Argument List>) ;

{

Block of Statement;

[return <exp> ];

}

Ex :-

Ex :-

Ex :-

int findmax() /*------ (No Argument and Return Value) */ { Block of Statements ; return (<variable>) ;

void findsum(int a , int b) /* ------ (Argument and No Return Value)*/ { Block of Statements ; }

void printmessage() /*------ (No Argument and No Return Value)*/ { Block of Statements; }

Page 52: Programming In C Language| 2010 · PDF fileProgramming In C Language| 2010 Page No :1 Prepared By, Rushabh P Madhu (9662140014) WHAT IS A LANGUAGE ? Language is

Programming In C Language| 2010

Page No

:52 Prepared By, Rushabh P Madhu (9662140014)

Ex :-

::Types of Function ::

[1] No Argument and No Return Value :-

When we call any user define function that does not return any value and it also not take any argument from the calling function, that function is known as No Argument and No return value type function. Following Example is of no argument and no return value .

[2] Argument but No Return Value :-

When we call any user define function that does not return any value but it take one or more argument from the calling function, that function is known as Argument but No return value type function. Following Example is of Argument and no return value .

int fact (int x ) /*------ (Argument and Return Value) */ {

Block of Statements ; return (<variable>) ;

void printline(); void main() { clrscr(); printline(); getch(); } void printline() { printf("\n \t\t Hello From My First User Define Function"); }

void findsum(int); void main() { int a,b; clrscr(); printf("Enter A and B Number to find Sum: "); scanf("%d %d ",&a, &b); printline(a,b); getch(); } void findsum(int a, int b) { int tot; printf("\n \t\t Sum is %d ",sum ); } }

Page 53: Programming In C Language| 2010 · PDF fileProgramming In C Language| 2010 Page No :1 Prepared By, Rushabh P Madhu (9662140014) WHAT IS A LANGUAGE ? Language is

Programming In C Language| 2010

Page No

:53 Prepared By, Rushabh P Madhu (9662140014)

[3] No Argument and Return Value :-

When we call any user define function that returns value to the main function although we have not passed any argument from the calling function, that function is known as No Argument and No return value type function. Following Example is of No argument and return value .

[4] Argument and Return Value :-

When we call any user define function that return return value to the main function and it also take one or more argument from the calling function, that function is known as Argument and return value type function. Following Example is of Argument and return value .

Nested Function :

When we call any function from the main function and called function call any other function from its body, thus the chain of function is generate and is known as Nested Functions. Following Example will display the concept of Nested Function :

int findmax(); void main() { int m; clrscr(); m=findmax();

printf(“\n\t\t Maximum is %d”,m); getch(); } int findmax() { int a,b;

printf("Enter A and B Number to find Sum: "); scanf("%d %d ",&a, &b); return (a+b); }

int fact(int); void main() { int n,f; clrscr();

printf("Enter N to find Factorial : "); scanf("%d ",&n); f=fact(n);

printf(“\n\t\t Factorial is %d”,f); getch(); } int fact(int n) { int I,f=1; For(i=1;i<=n;i++) { f=f*I; } return (f); }

/* WAP for tot=1!+2!+3!+4!+......n! */ int sum(int); int fact(int); main( ) { int n=5,ans; ans=sum(n);

Page 54: Programming In C Language| 2010 · PDF fileProgramming In C Language| 2010 Page No :1 Prepared By, Rushabh P Madhu (9662140014) WHAT IS A LANGUAGE ? Language is

Programming In C Language| 2010

Page No

:54 Prepared By, Rushabh P Madhu (9662140014)

Page 55: Programming In C Language| 2010 · PDF fileProgramming In C Language| 2010 Page No :1 Prepared By, Rushabh P Madhu (9662140014) WHAT IS A LANGUAGE ? Language is

Programming In C Language| 2010

Page No

:55 Prepared By, Rushabh P Madhu (9662140014)

RECURSION :

Recursion is a process by which a function calls itself repeatedly, until some specified condition has been satisfied. The process is used for repetitive computation in which each action is stated on forms of previous result. The process is used for repetitive computation in which each action in terms of a previous result. Many iterative problems can be written in this form.

In order to solve a problem recursively, two condition must be satisfied. First, the problem must be written in recursive form and second the problem example, we wish to calculate the factorial of a positive integer quantity. We would normally express this problem as n1=1 x 2 x 3 x 4 … x n where n is the specified positive integer. However, we can also express in another way, by writing n=1 = n*(n-1). This is a recursive statement of the problem, in which last expression provides a stopping condition for the recursion.

When a recursive program is executed the recursive function calls are not executed immediately. Rather, they are placed on a stack until the condition that terminates the recursion is encountered. The function calls are then executed in reverse order, as they are popped off the stack.

If a recursive function contains local variables, a different set of local variables will be created during each call. The name of the local variables, will be cause always be the same, as declared within the function. However, the variables will represent a different set of values each time the function is executed. Each set of values will be stored on the stack, so that they will be available as the recursive process “unwinds” i.e. as the various function calls are “popped” off the stack and executed.

PASSING ARRAYS TO A FUNCTION:

int fact(int); main( ) { int n=5,ans; ans=fact(n);

printf(“%d”,ans); } int fact(int n) { int f; if(n==1) return 1;

else f=n*fact(n-1); return(f);

}

Page 56: Programming In C Language| 2010 · PDF fileProgramming In C Language| 2010 Page No :1 Prepared By, Rushabh P Madhu (9662140014) WHAT IS A LANGUAGE ? Language is

Programming In C Language| 2010

Page No

:56 Prepared By, Rushabh P Madhu (9662140014)

An array name can be used as an argument to a function, thus permitting the entire array to be passed to the function. The manner in which the array is passed differs mainly. However, from that of an ordinary variable.

To pass an array to a function, the array mane must appear by itself without brackets or subscripts as an actual argument within the function call. The corresponding format argument is written in the same manner, though it must be declared as an array within the formal argument declaration. When declaring array as a format argument, the array name is written with a pair of empty square brackets. The size of the array is not specified within the format argument declaration.

The following program outline illustrates the passing of an array from the main portion of the program to the function

Value passing Approaches:

� Pass by value approach � Pass by reference approach

PASSING BY BALUE APPROACH

When we call any function we pass the variable as an argument (In Actual Arguments ) and this passing approach is known as call by value approach. Function is called by value does not give its real value to another (Formal Argument ) function’s variable.

PASS BY REFERENCE APPROACH

When we call any function and we pass the address of variable as an argument (In Actual Arguments ), is known as pass by reference approach. Function called by reference does not pass any variables value but is pass its address as a argument so that in format argument’s variable the address of passing arguments is stored. And by using that address operation is performed. The disadvantage of pass by reference approach is that formal argument’s variable can change the value of real variable which is passed as argument. void disp(int); void main() { int i; clrscr(); i=10; disp(i); getch(); }

void disp(int *); void main() { int i; clrscr(); i=10; disp ( &I ); getch(); }

Difference between call by value and call by

ref. is display at the time when we call the

function.

void disp(int [],int);

void main()

{ int i,no[10];

clrscr();

printf("Enter any Ten Values :");

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

{

printf("Enter %d value",i+1);

scanf("%d",&no[i]);

}

disp(no,10);

getch();

}

void disp(int no[],int n)

{ int i;

for(i=0;i<n;i++) printf("\n your %d value is

%d",i+1,no[i]);

}

Here emply pair represent

that argumement passed by

the calling function is in the

form of Array variable. At the

time of variable declaration

we also have to specify that

sign to indicate that UDF will

pass array as arguments.

Formal

Actual

Page 57: Programming In C Language| 2010 · PDF fileProgramming In C Language| 2010 Page No :1 Prepared By, Rushabh P Madhu (9662140014) WHAT IS A LANGUAGE ? Language is

Programming In C Language| 2010

Page No

:57 Prepared By, Rushabh P Madhu (9662140014)

struct student { int rno; char nm[15]; int per; }bca; void disp(struct student); void main() { int i; clrscr(); printf("Enter rollno:"); scanf("%d",&bca.rno); printf("Enter Name:"); scanf("%s",&bca.nm); printf("Enter Percentage:"); scanf("%d",&bca.per); disp(bca); getch(); } void disp(struct student bscit) { printf("\n \n Roll No is %d",bscit.rno); printf("\n Name is %s",bscit.nm); printf("\n Percentage is %d",bscit.per); }

When Function is call Reference the formal argument must be pointer.

PASSING STRUCTURE TO A FUNCTION:

A Structure can be used as an argument to a function, thus permitting the entire structure to be passed to the function. Following Example will display how to pass structure in User Define Function.

When we want to pass whole structure in User Define Function we must have to specify the passing argument type (AS sturuct student) at the time of User define function calling.

Calling of a function is same as we call simple function.

At the time of Function definition we also specify the argument type and the name of formal argument in which the content of Actual argument is to be stored(Receive).

Page 58: Programming In C Language| 2010 · PDF fileProgramming In C Language| 2010 Page No :1 Prepared By, Rushabh P Madhu (9662140014) WHAT IS A LANGUAGE ? Language is

Programming In C Language| 2010

Page No

:58 Prepared By, Rushabh P Madhu (9662140014)

Pointers :

A pointer is a variable that represents the location of a data item, such as a variable or an array element. Pointers have a number of useful applications. For example, pointer can be used to pass information back and forth between a function and a reference point. In particular, other provides a way to return multiple data items from a function via arguments. Pointer also permits references to other functions to be specified as arguments to a given function. This has the effect of passing function as arguments to the given functions. Pointers are also closely associated with arrays and therefore provide an alternative way to access individual array elements.

& [AND] OPERATORS

Suppose v is a variable that represents some particular data item. The address location can be determined by the expression &v. where & is a 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.

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. (i.e. contents of same memory cell). Furthermore, if we write pv = &v and u=*pv then u and v will both represent the same value. i.e. the value of v will indirectly be assigned to u. (it is assumed that u and v are declared to have the same data type).

The unary operators & and * are members of the same precedence group as the other unary operators. This group of operators has a higher precedence than the groups containing the arithmetic operators. The associativity of the unary operators is right to left.

The address operator(&) must act upon operand associated with unique addresses. Such as ordinary variables or single array elements. Thus the address operator cannot act upon arithmetic expressions such as 2*(u+v).

The indirection operator(*) can only act upon operands that are pointers. However, if pv points to v (i.e. pv=&v) then an expression such as *pv can be used interchangeably with its corresponding variable v. thus an indirect reference can also appear on the left side and assignment statement. This provides another method for assigning a value to an array element of an ordinary variable (e.g. v) within a more complicated expression.

address of v value of v

Page 59: Programming In C Language| 2010 · PDF fileProgramming In C Language| 2010 Page No :1 Prepared By, Rushabh P Madhu (9662140014) WHAT IS A LANGUAGE ? Language is

Programming In C Language| 2010

Page No

:59 Prepared By, Rushabh P Madhu (9662140014)

Pointer variables can point to numeric or character variables, arrays, functions or other pointer variables. Thus a pointer variable can be assigned the address of an ordinary variable (i.e. pv=&v). also a pointer can be assigned the value of another pointer variable (i.e. pv=px) provided both pointer variables point to data items of the same type. More over, a pointer variable can be assigned a null (zero ) value.

POINTER DECLARATIONS :

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 *ptvar;

Where ptvar is the name of the pointer variable and data type refers to the data type of the pointer object. Remember that an asterisk must precede ptvar.

For example,

Float u,v;

Float *pv;

---

pv = &v;

The first line declares u and v to be floating point variables. The second line declares pv to be a pointer whose object is a floating-point quantity. i.e. pv points to a floating point quantity. note that pv represents an address not a floating-point quantity. An asterisk should not be included in the assignment statement.

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,

Float u,v;

Float *pv=&v;

PASSING POINTER TO A FUNCTION :

Pointers are often passed to a function as arguments. This allows data items within the calling portion of the program to be accessed by the function altered within the function and then returned to the calling portion of the program in altered form. We refer to this use of pointer as passing of arguments by reference (or by address or by location).

Page 60: Programming In C Language| 2010 · PDF fileProgramming In C Language| 2010 Page No :1 Prepared By, Rushabh P Madhu (9662140014) WHAT IS A LANGUAGE ? Language is

Programming In C Language| 2010

Page No

:60 Prepared By, Rushabh P Madhu (9662140014)

When an argument is passed by value, the data item is copied to the function. Thus any alteration made to the data item within the function is not carried over into the calling routine. When an argument is passed by reference, however (i.e. when a pointer is passed to a function) the address of a data item is passed to the function. The contents of that address can be accessed freely, either within the function or within the calling routine. More over change that is made to the data item(i.e. to the contents of the address) will be recognized in both the function and the calling routine, thus the use of pointer as a function argument permits the corresponding data item to be altered globally from within the function. When pointers are used as argument to a function the formal arguments that are pointers must each be preceded by an asterisk. Also, if a function declaration is included in the coding portion of the program. The data type of each argument that corresponds to a pointer must be followed by an asterisk. Both these points are illustrated in the following example :

here, fun2 receives two pointer to integer variables as its arguments. The arguments are identified as pointers by the indirection operators (i.e. the asterisk) that appear in the argument declaration, in addition declaration indicates that the pointers represents the integer quantities.

Within fun2, the contents of the pointer address are reassigned the values 0.0; since, the address are recognized in both fun2 and main, the reassigned values will be recognized within main after the call to fun2, therefore, the integer variables u and v will have accessed indirectly, by referencing the pu and pv. This is necessary because the variable u and v are not recognized such as within fun2.

The items in parentheses identify the arguments as pointers to integer quantities. The pointer variable, pu and pv have not been declared elsewhere in main.In the declaration of the formal argument within the first line of fun2, that is void func2(int *pv, int *pv) .The formal arguments pu and pv are consistent with the dummy arguments in the function prototype. In this example the corresponding variable names are the same though this is generally not required.

An array name is actually a pointer to the array. i.e. the array name represents the address of the first element in the array. therefore, an array name is treated

#include <stdio.h>

main()

{ int n=1, v=3;

void fun2(int pu, int *pv) ;

printf(“ \n after calling func2 : u=%d

v=%d “ , u,v) ;

}

void fun2(int *pu, int *pv)

{ *pu=0 ;

*pv=0 ;

printf(\n within fun2 pu=%d pv=%d”,

pu,*pv);

Page 61: Programming In C Language| 2010 · PDF fileProgramming In C Language| 2010 Page No :1 Prepared By, Rushabh P Madhu (9662140014) WHAT IS A LANGUAGE ? Language is

Programming In C Language| 2010

Page No

:61 Prepared By, Rushabh P Madhu (9662140014)

as pointer when it is passed to a function. However, it is not necessary to precede the array names with an ampersand within the function call. An array name that appears as a formal argument within a function definition can be declared either as a pointer or as an array of unspecified size.

It is possible to pass a portion of an array, rather than an entire array, to a function. To do so, the address of the first array element to be passed must be specified with the argument. The remainder of the array, starting with specified array element, will then be passed to the function.

A function can also return a pointer to the calling portion of the program. The do so, the function definition and any corresponding function declaration must indicate that the function will return a pointer. this is accomplished by preceding the function name with an asterisk. The asterisk must appear in both the function definition and the function declaration.

POINTER AND ONE DIMENTSIONAL ARRAY

If x is a one-dimensional array, then the address of the first array element can be expressed as either &x[0] or simply x. moreover, the address of the second array element can be written as either &x[1] or as (x+1). And so on. In general the address of I+1 th array element is expressed as (x+I). Since x[1] and (x+1) both represent the address of 1 element of x. it would seem reasonable that x[1] and *(x+1) both represent the contents of that address. i.e. the value of the 1st element of x for example.

Executing this program results the following output :

I=0 x[I]=10 *(x+I)=10 &x[I]=72 x+I=72

I=1 x[I]=11 *(x+I)=11 &x[I]=74 x+I=74

I=2 x[I]=12 *(x+I)=12 &x[I]=76 x+I=76

I=3 x[I]=13 *(x+I)=13 &x[I]=78 x+I=78

I=4 x[I]=14 *(x+I)=14 &x[I]=7A x+I=7A

We can see that the value of the ith array element can be represented either x[I] or x[I+1] and the address of the ith element can be represented by either &x[I] or x+i. When assigning a value an array element such as x[I], the left side of the assignment statement may be written as either x[I] or as *(x+I). Thus a value may be assigned directly to an array element or it may be assigned to the memory area whose address is arbitrary address to an array name or to an array element. Thus expression such as (x+1) and &x[I] cannot appear on the left side

#include <stdio.h>

main()

{

static int x[5] = {10, 11, 12, 14};

int I;

for(I=0; I<5; I++)

printf(“\n I=%d x[I]=%function *(x+I)=%d &x[I] = %d(x+I)

%d”, x[I], *(x+I),&x[I],x+I);

}

Page 62: Programming In C Language| 2010 · PDF fileProgramming In C Language| 2010 Page No :1 Prepared By, Rushabh P Madhu (9662140014) WHAT IS A LANGUAGE ? Language is

Programming In C Language| 2010

Page No

:62 Prepared By, Rushabh P Madhu (9662140014)

of an assignment a\statement. For example. these four statement are all equivalent.

Line[2] = line[1];

Line[2] = *(line+1);

*(Line+2) = line[1];

*(Line+2) = *(line+1);

The address pf an array element cannot be assigned to some other array element. We cannot write a statement such as.

&line[2] = &line[1];

we can assign the value of one array element to another through a pointer. if we wish, for example,

pl = &line[I]

line[2]=*pi

pl = line+l;

*(line+2) = *pl;

numeric array element cannot be assigned initial values if the array is defined as a pointer variable. Therefore a conventional array definition is required if initial values will be assigned to the element of a numerical array. however, a character type pointer variable can be assigned an entire string as a part of the variable declaration. Thus a string can conveniently be represented by either a non-dimensional array or a character pointer.

OPERATIONS ON POINTERS

In particular an integer value can be added to or subtracted from a pointer variable though the resulting expression must be interpreted very carefully. Suppose for example that, px is the pointer variable representing the address of the same variable x, we can write expressions such as ++px, --px, (px+3), (px-1), where I is an integer variable. Such expression will represent an address located some distance of the integer quantity and the number of bytes or words associated with the data item to which px points. Suppose for example, that px points to an integer quantity, and each integer quantity requires 2 bytes of memory. Then the expression (px+3) will result in an address 6 bytes beyond the integer to which px points as illustrated following ;

Px-> 2 bytes v (px+3)

One pointer variable can be subtracted from another provided both pointer point to element of the same array. the resulting value indicates the number of words or bytes separating the corresponding array elements.

Pointer variable can be compared provided both variable point to object of the same data type. Such comparisons can test for either quality or inequality.

Moreover, a pointer variable can be computed with 0.

Page 63: Programming In C Language| 2010 · PDF fileProgramming In C Language| 2010 Page No :1 Prepared By, Rushabh P Madhu (9662140014) WHAT IS A LANGUAGE ? Language is

Programming In C Language| 2010

Page No

:63 Prepared By, Rushabh P Madhu (9662140014)

The permissible operations on pointers are summarized below :

1. A pointer variable can be assigned the address of an ordinary variable (e.g. pv=&v)

2. A pointer variable can be assigned the value of another pointer variable (e.g. pv=px) provided both pointers points to the object of the same data type.

3. A pointer variable can be assigned a null(zero) value (e.g. pv=null) 4. An integer quantity can be added to or subtracted from a pointer variable

(e.g. pv+3, ++pv, pv-1)

5. One pointer variable can be subtracted from another provided both pointer points to the element of the same array.

6. The pointer variables can be compared provided both pointers point to the object of the same type.

Other arithmetic operations on pointers are not allowed. Thus a pointer variable cannot be multiplied by a constant. Two pointer variables cannot be added and so on.

POINTERS AND MULTIDIMENSIONAL ARRAYS :

A two dimensional array, for example is actually a collection of one-dimensional arrays . therefore, we can define a two dimensional array as a pointer to a group of contiguous one-dimensional arrays. A two-dimensional array declaration can be written

Data-type (*ptvar) expression 2;

This concept can be generalized to higher dimensional arrays that is

Data-type (*ptvar) [expression 2][expression 3] … [expression n];

In these declarations data type refers to the data type of the array. ptvar is the name of the pointer variable. Array is the corresponding array name an expression 1, expression 2, … expression n are positive –valued integer expression that indicate the maximum number of array element associated with each subscript.

The parentheses that surround the array name should normally be evaluated right to left. Suppose that x is a two-dimensional integer array having 10 rows and 20 columns. We can declare x as a

Int(*x)[20];

In this declaration, x is defined to be a pointer to a group of contiguous, one-dimensional 20 element integer arrays. Thus x points to the first 20-element array, which is actually the first row (row 0) of the original two-dimensional array.

Page 64: Programming In C Language| 2010 · PDF fileProgramming In C Language| 2010 Page No :1 Prepared By, Rushabh P Madhu (9662140014) WHAT IS A LANGUAGE ? Language is

Programming In C Language| 2010

Page No

:64 Prepared By, Rushabh P Madhu (9662140014)

Similarly, (x+1) points to the second 20 elements array. which is the second row(row 1) of the original two-dimensional array and so on.

An individual array element within a multidimensional array can also be accessed by repeatedly using the indirection operator. Usually, however this procedure is more awkward then the conventional method for accessing an array element. The following example illustrates the use of the indirection operator.

Suppose that x is a two dimensional integer array having 10 rows and 20 columns, as declared as Int(*x) [20];

The item in row2, column 5 can be accessed by working either.

X[2][5] or *(*(x+2)+5)

Here, (x+2) is a pointer to row 2, therefore, the object of this pointer *(x+2), refers to the entire row since row2 is a one-dimensional array. *(x+2) is actually a pointer to the first element in row 2. we now add 5 to the pointer. hence, (*(x+2)+5) is a pointer to element 5 in row 2. the object of this pointer, refers to the item in column 5 or row 2 which is x[2][5].

ARRAY OF POINTERS:

A multidimensional array can be expressed in terms of an array of pointers rather than as a pointer to a group of contiguous arrays. In such situations the newly defined array will have one less dimension that the original multidimensional array. such pointer will indicated the beginning of separate (n-1) dimensional array.

In general terms a two-dimensional array can be defined as one-dimensional array of pointes by writing

Data-type *array(expression 1);

Similarly an n-dimensional array can be defined as (n-1) dimensional array of pointer by writing,

Data-type *array[expression 1][expression 2]…[expression n];

In these declaration data type refers to the data type of the original n-dimensional array. array is the array name and expression 1, expression 2, expression n are positive valued integer expressions that indicate the maximum number of element associated with each subscript.

A right-to-left rule first associates the pairs of square brackets with array, defining the named object as an array. the preceding asterisk then establishes that the array will contain pointers.

Page 65: Programming In C Language| 2010 · PDF fileProgramming In C Language| 2010 Page No :1 Prepared By, Rushabh P Madhu (9662140014) WHAT IS A LANGUAGE ? Language is

Programming In C Language| 2010

Page No

:65 Prepared By, Rushabh P Madhu (9662140014)

The last (the right most) expression is when defining an array of pointers. Where as the first (the left most) expression is omitted when defining a pointer to a group of arrays. When an n-dimensional array expressed in this manner an individual array element within the n-dimensional array can be accessed by a single use of the indirection operator for example,

We can define x as a one dimensional array of pointers by writing

Int *x[10];

Hence, x[0] points to the beginning of the first row, x[1] points to the beginning of the second row and so on. Note that the number of element within each row is not explicitly specified.

An individual array element, such as x[2][5] can be accessed by writing,

*(x[2]+5)

In this expression, x[2] is a pointer to the first element in row 2 so that x[2] +5 points to element 5 within row 2. the object of this pointer, *(x[2] +5) therefore refers to x[2][5]. Now consider a three-dimensional floating-point array t. suppose the dimension of t is 10 x 20 x 30. this array can be expressed as a two-dimensional array of pointers by writing

Float *t[10][20];

Therefore we have 200 pointers, each pointing to a one-dimensional array. an individual array element, such as t[2][3][5] can be accessed by writing

*(t[2][3]+5)

In this expression, t[2][3] is a pointer to the first element in the one-dimensional array represented by t[2][3]. Hence (t[2][3]+5) points to element 5 within this array. the object of this pointer *(t[2][3]+5) therefore represents t[2][3][5].

Pointer arrays offer a particularly convenient method for storing strings. In this situation, each array element is a character type pointer that indicated the beginning of separate string. Thus an n-element array can be point to n different strings. Each individual string can be accessed by referring to its corresponding pointer.

For example, char name[10][12]; here name contains 10 rows to accommodate the 10 strings. Each row must be large enough to store at least 12 characters. A better way to do this is to define a 10 element of pointer, that is,

Char *name[10];

Thus, name[0] will indicate the first name. Name[1] will indicate the second name and so on.

Page 66: Programming In C Language| 2010 · PDF fileProgramming In C Language| 2010 Page No :1 Prepared By, Rushabh P Madhu (9662140014) WHAT IS A LANGUAGE ? Language is

Programming In C Language| 2010

Page No

:66 Prepared By, Rushabh P Madhu (9662140014)

Just as individual strings can be accessed by referring to the corresponding pointers. (i.e. corresponding array element). So can individual string element be accessed through the use of the indirection operator. For example, *(*(name+2)+3) refers to the forth character in the third string of the array name.

If the element of the array is sting pointers, a set of initial values can be specified as a part of the array declaration. In such cases the initial values will be strings, where each string corresponds to a separate array element. Remember however that an array must be declared static if it is initialize within a function. For example

in this example, name is a 5-element array of pointers. The first array element (i.e. the first pointer ) will point to Pacific, the second element will points to Atlantic, and so on.

:: Practicals ::

In this example we have inputted the value of I and then we store the address of I to pointer variable p. While displaying data on screen in first printf statement we display the value of I and the value of p means the value of I is(10) while the value of p is (the address of I means 64434 or any address). In second

example we have display the value of pointer variable P and the address of I using (&)sign which is use to display memory location of any variable. The value of Pointer p is the value of that address which is stored in p variable ( In P address of I is stored ) so the value is I which is 10 and at last the address of I is display to specify at where the value is stored in memory.

Static char *name[5] = {

“pacific”,

“Atlantic”,

“Indian”,

“Caribbean”,

“Bering”

};

void main() { int i; int *p; clrscr(); printf("Enter The value of I= "); scanf("%d",&i); p=&i; printf("The vlaue of i= %d and its address is= %u",i,p); printf("\n Second Method"); printf("The value of i=%d and its address is= %u",*p,&i); getch();

Page 67: Programming In C Language| 2010 · PDF fileProgramming In C Language| 2010 Page No :1 Prepared By, Rushabh P Madhu (9662140014) WHAT IS A LANGUAGE ? Language is

Programming In C Language| 2010

Page No

:67 Prepared By, Rushabh P Madhu (9662140014)

void main() { int v1,v2; int *p,*q;

clrscr(); printf("Enter First value :"); scanf("%d",&v1);

printf("Enter Second value :"); scanf("%d",&v2); p=&v1; q=&v2; if(*p>*q) { printf("The First vlaue is Maximum"); }Else

{ printf("Second value is maximum"); }

getch(); }

Pointer with Conditional Statements

:-

As we use general variable for condition we can also use pointer variable for that purpose. Next example illustrate the perfect example for Pointer with conditional Statement.

In th First example we have inputted two value and store those variable to pointer variable p and q. Then in IF statement we have check whether the value of pointer p is greater than the value of pointer q. Using proper conditional statement we have display appropriate message to the user.

In Second example we have inputted two value and swap by using pointer and only arithmetic operator. Then we display on screen.

Pointer with Looping Statements :-

As we use general variable for Looping we can also use pointer variable for that purpose. Next example illustrate the perfect example for Pointer with Looping Statement.

/* WACP to swap two value using pointer. */ #include<stdio.h> #include<conio.h> void main() { int n1,n2,*p1,*p2; clrscr(); printf("Enter value of n1: "); scanf("%d",&n1); printf("enter value of n2: "); scanf("%d",&n2); p1=&n1; p2=&n2;

*p1=*p1+*p2; *p2=*p1-*p2; *p1=*p1-*p2; printf("n1=%d\n",*p1); printf("n2=%d\n",*p2); printf("address of n1 is %u\n",&n1); printf("address of n2 is %u",&n2); getch(); }

Page 68: Programming In C Language| 2010 · PDF fileProgramming In C Language| 2010 Page No :1 Prepared By, Rushabh P Madhu (9662140014) WHAT IS A LANGUAGE ? Language is

Programming In C Language| 2010

Page No

:68 Prepared By, Rushabh P Madhu (9662140014)

Pointer with Array Statements :-

As we use Array variable to store more than one value having same name and of data type, to handle that array we can also use pointer. Next example display how to handle array by using pointer

Pointer with Structure :-

Structure is a collection of different types of data into a single unit. Structure is use when we have different types of variable in a single unit. For that structure we can also user pointer. Following Example will display its concept.

void main() { int i,n,no[10]; int *p; clrscr(); printf("Enter how many elements You want to Enter:"); scanf("%d",&n); for(i=0;i<n;i++) { printf("Enter %d value: ",i+1); scanf("%d",&no[i]); } p=no; printf("\n\n\n output "); for(i=0;i<n;i++,p++) { printf("\n Value at [%d] position is = %d",i+1,*p); }getch(); }

Here no is a Array of Integer type and of Ten element. And P is a integer pointer variable. In this example we have input n value from the user and store the array variable to Pointer. Then we display the data of array

void main() { int n,i=1; int *p; clrscr(); printf("Enter the value of N:"); scanf("%d",&n); p=&n; while(i<=*p) { printf("%4d",i); i=i+1; }getch(); }

Here N is integer variable

which input any single

value from the user. While

P is a integer Pointer

variable. In p we have

store the Address of n

variable and in while

condition we specify that

loop is continue until the

value of I is not greater

than Pointer p variable. So

Page 69: Programming In C Language| 2010 · PDF fileProgramming In C Language| 2010 Page No :1 Prepared By, Rushabh P Madhu (9662140014) WHAT IS A LANGUAGE ? Language is

Programming In C Language| 2010

Page No

:69 Prepared By, Rushabh P Madhu (9662140014)

struct stu { int rno; char name[10]; } *s1,s2; void main() { printf("enter roll.no: "); scanf("%d",&s1->rno); printf("enter name: "); scanf("%s",&s1->name); printf("\nno is%d ",s1->rno); printf("\nname is%s",s1->name); printf("\nenter roll.no: "); scanf("%d",&s2.rno); printf("enter name: "); scanf("%s",&s2.name); s1=&s2; printf("no is%d ",s1->rno); printf("name is%s",s1->name); getch(); }

Structure Array with

Pointer :

Array of Structure can be handled by using pointer easily. Following Example will display the Perfect Example for Handling the array of Structure.

struct student { int rno; char name[15]; int per; }bca[10],*p; void main() { int n,i; clrscr(); printf("Enter how many Records :"); scanf("%d",&n); for(i=0;i<n;i++) { printf("Enter Rollno:"); scanf("%d",&bca[i].rno); printf("Enter Name :"); scanf("%s",&bca[i].name); printf("Enter Perc:"); scanf("%d",&bca[i].per); }p=&bca; clrscr(); printf("\n \n \t \t output "); for(i=0;i<n;i++,p++) { printf("\n Rollno is %d",p->rno); printf("\n Name is %s",p->name); printf("\n percentage is %d\n \n ",p->per); } getch(); }

In this example first we have input value in s1 pointer object and display on screen by the simple method of structure handling. While we input in s2 structure variable and stores in the pointer variable we have to use

(‘->’) to access the structure which is stored in pointer variable.

Page 70: Programming In C Language| 2010 · PDF fileProgramming In C Language| 2010 Page No :1 Prepared By, Rushabh P Madhu (9662140014) WHAT IS A LANGUAGE ? Language is

Programming In C Language| 2010

Page No

:70 Prepared By, Rushabh P Madhu (9662140014)

String with Pointer :

String can also handle by pointer variable. Following example will display a demo for that.

/*Pointer in String Handling char *st; */

#include <stdio.h>

#include <string.h>

void main()

{ char *st; char s1[10]; int i,s;

clrscr();

s=sizeof(st);

printf("\n size of st is %d",s);

s=sizeof(s1);

printf("\n size of st is %d",s);

printf("\n Enter a String : ");

gets(st);

printf("\n Length of the string is

%d\n\n",strlen(st));

for(i=0; st[i] != NULL; i++)

{ printf("st[%d] = %c\n",i,st[i]); }

getch();

Page 71: Programming In C Language| 2010 · PDF fileProgramming In C Language| 2010 Page No :1 Prepared By, Rushabh P Madhu (9662140014) WHAT IS A LANGUAGE ? Language is

Programming In C Language| 2010

Page No

:71 Prepared By, Rushabh P Madhu (9662140014)

FILE MANAGEMENT

A file is a place on the disk where a group of related date is stored. Some basic file operation can be given as :

� naming a file

� opening a file � reading data from a file

� writing data to a file

� closing a file

Opening and closing a data file :

When working with a file steps it to establish a buffer area, where information is temporarily stored while being transferred between the computer’s memory and the data file. This buffer area allows information to be read from or written to the data file more rapidly then would otherwise be possible. The buffer area is established by writing

FILE *ptvar;

Where FILE (uppercase required) is a special structure type that establishes the buffer area and ptvar is a pointer variable that indicates the beginning of the buffer area. The structure type file is defined with a system include file : typically stdio.h

A data file must be opened or created before it can be created or processed. Thus associates the file name with the buffer area. It also specifies how the data file will be utilized. That is a read only file, a write-only file or a read/write file, in which both operations are permitted. The library function fopen is used to open a file. This function is typically written as :

Ptvar = fopen(file_name, file_type)

Where file_name and file_type are strings that represents the name of the data file and the manner in which the data file will be utilized, respectively. The name chosen for the file_name must be consistent within the rules for naming files, as determined by the computer’s operating system. The file_type must be one of the strings shown in the following table :

File_type meaning

“w” open a new file for writing only. If the file with specified file_name currently exists it will be destroyed and new file is created in its place.

“r” open an existing file for reading only.

“a” open an existing file for appending. A new file will be created if the file with the specific file_name does not exist.

Page 72: Programming In C Language| 2010 · PDF fileProgramming In C Language| 2010 Page No :1 Prepared By, Rushabh P Madhu (9662140014) WHAT IS A LANGUAGE ? Language is

Programming In C Language| 2010

Page No

:72 Prepared By, Rushabh P Madhu (9662140014)

The fopen function returns a pointer to the beginning of the buffer area associated with the file. A NULL value is returned if the file cannot be opened as for example, when and existing file cannot be found. Finally a data file must be closed at eh end of the program. This ensures that all outstanding information associated with the file is flushed out from the buffers and all links to the file are broken. It also prevents any accidental misuse of the file. In case there is a limit to the number of files that can be kept open simultaneously, closing of unwanted file might help open the required files. Another instance, where we have to close a file is when we want to reopen the same file in a different mode. This can be accomplished with the library function fclose. The syntax is simply :

fclose(fptvar);

Input-output operation on file :

THE GETC AND PUTC FUNCTIONS :

The simplest file i/o functions are fgetc and fputc. These are used to handle one character at a time. Assume that a file is opened with mode w and file point fpt. Then, the statement

fputc(c,fpt);

Writes the character contained in the character variable c to the file associated with FILE pointer fpt. Similarly getc is used to read character from a file that has been opened in read mode. For example, the statement

“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 is created in its place.

“r+” open an existing file for both reading and writing.

“a+” open an existing file for reading and writing. A new file will be created if the file with the specified file_name does not exist.

#include <stdio.h>

Void main()

{

FILE *fpt;

Fpt=fopen(“simple.dat”,”w”);

close(fpt);

}

Page 73: Programming In C Language| 2010 · PDF fileProgramming In C Language| 2010 Page No :1 Prepared By, Rushabh P Madhu (9662140014) WHAT IS A LANGUAGE ? Language is

Programming In C Language| 2010

Page No

:73 Prepared By, Rushabh P Madhu (9662140014)

C = fgetc(fp2);

Would read character from file whose file pointer is fp2. the file pointer moves by one character position for every operation of getc and putc. The getc will have been reached. Therefore, the reading should be terminated when EOF is encountered.

For example,

THE FGETS AND FPUTS FUNCTIONS :

These functions are used to handle a string at ja time. Assume that a file is open in the write mode and file pointer is fp1, then the statement

Fputs(s,fp1);

Writes the string contained in the character arrays to the file associated with FILE pointer fp1. similarly, fgets is used to read a string of particular length from a file that has been opened in read mode. For example,

Fgets(s,79,fp1);

Would read string of 79 character from the file whose file pointer is fp1. The fgets

Main()

{ FILE *fp;

Char c;

Fp = fopen(“input”, “w”);

While(c=getchar()) != EOF)

{

fputc(c,fp);

}

fclose(fp);

f1 = fopen(“input”,”r”);

while(c=fgetc(f1)) != EOF)

{

printf(“%c”,c);

}

fclose(f1);

}

#include<stdio.h>

main()

{ FILE *fp;

Char c[80];

Fp = fopen(“INPUT”, “w”);

While(strlen(getc(c)>0)

{ fputs(c,fp);

fputc(“\n”, c);

}

fclose(fp) ;

fp = fopen(« INPUT », « r ») ;

while(gets(c,79, fp) = NULL)

printf(“%s \n”,c);

fclose(fp);

}

Page 74: Programming In C Language| 2010 · PDF fileProgramming In C Language| 2010 Page No :1 Prepared By, Rushabh P Madhu (9662140014) WHAT IS A LANGUAGE ? Language is

Programming In C Language| 2010

Page No

:74 Prepared By, Rushabh P Madhu (9662140014)

will return NULL character when reached at the end of file. Therefore the reading should be terminated when NULL is encountered. For example,

THE FSCANF AND FPRINTF FUNCTIONS :

These functions are used to read or write in formatted from from/to the files. The general form of fprintf is

fprintf(f1, “%s%d%function”, name, age, 7.5);

Here f1 is the file pointer name is an array variable of type character, age is integer variable.

The general form of fcanf is :

Fscanf(fp, “control string”, list);

This statement would cause the reading of the items in the list from the file specified by fp, according to the specifications contained in the control string. For example,

Fcanf(f2, “%s” “%d” ”%f”, item, qty,price);

Fcanf returns the number of items that are successfully read. When the end of the file is reached, it returns the value of EOF.

THE FREAD AND FWRITE FUNCTIONS :

Some applications involve the use of data files to store blocks of data, where each block consists of a fixed number of contiguous bytes. Each block will generally represent a complete data structure, such as a structure or an array. for such applications it may be desirable to read the entire block from the data file or write the entire block to the file.

The library function fread and fwrite are intended to be used in situations of this size of the data block, the number of data block being transferred and file pointer. thus typical fwrite and fread functions :

fwrite(&customer, sizeof(record),1,fpt);

fread(&customer, sizeof(record),1,fpt);

Where customer is a structure variable of type record and fpt is the file pointer associated with the data file that has been opened for input/output. Once an unformatted data file has been created with fwrite, it can be read with fread function. The function returns a zero value if an end-of-file condition has been detected and non-zero value if an end-of-file is not detected. Hence, a program that reads an unformatted data file can be reading file, as long as the value returned by fread is non-zero value.

Page 75: Programming In C Language| 2010 · PDF fileProgramming In C Language| 2010 Page No :1 Prepared By, Rushabh P Madhu (9662140014) WHAT IS A LANGUAGE ? Language is

Programming In C Language| 2010

Page No

:75 Prepared By, Rushabh P Madhu (9662140014)

RANDOM ACCESS TO FILES :

There are occasions however, when we are interested in accessing only a particular part of a file and not in reading the other parts. This can be achieved with the help of the function fseek, ftell and rewind available in the library.

ftell :

ftell take a file pointer and returns a number of type long that corresponds to the current portion. This function is useful in saving the current position of a file, which can be used in the program. It takes the following form.

N =ftell(fp);

N would give the relative offset (n bytes) of the current position. This means that n bytes have already bean read.

rewind :

rewind takes a file pointer and resets the position to the start of the file. For example the statement :

Rewind(fp);

N=ftell(fp);

Would assign to fp because the file position has been set to the start of the file by rewind. This function helps us in reading a file more than once. Without having to close and open the file.

fseek :

fseek function is used to move the position to a desired location within the file. It takes the following form.

Fseek(fpt, offset, position)

Fpt is a pointer to file concerned. Offset is a number of variable of type long and position is an integer number. The offset specifies the number of bytes(position) to be moved from the location specified by position. The position can take one of the following three values :

0 beginning of file

1 current position

2 end of file

The offset may be positive, meaning move forward and negative, meaning move backwards.

When the operation is successful, fseek returns a zero. If we attempt to move beyond the file boundaries and error occurs and fseek returns.

Page 76: Programming In C Language| 2010 · PDF fileProgramming In C Language| 2010 Page No :1 Prepared By, Rushabh P Madhu (9662140014) WHAT IS A LANGUAGE ? Language is

Programming In C Language| 2010

Page No

:76 Prepared By, Rushabh P Madhu (9662140014)

/*Program # 1 : File Handling Program : Writing into a file One-By-One Character. Reading from keyboard.

To read one character from keyboard --> getch, getche, getchar functions

To write a character in to a file --> putc(ch, File_Ptr) ==> "Reading one-by-one character from keyboard and writing to a file "******************************************/ #include <stdio.h> #include <conio.h> void main() { char ch; FILE *fp; fp = fopen("d:\\Myfile.txt", "w"); while(1) { ch = getche(); if(ch == 13) break; putc(ch,fp); } getch();

/*Program # 2 : File Handling Program : Reading One-By-One Character from the file. Displaying on the screen. To read one character from a file --> getc() To display a character on the screen --> putchar(ch) ******************************************/ #include <stdio.h> #include <conio.h> void main() { char ch; FILE *fp; fp = fopen("d:\\Myfile.C", "r"); clrscr(); while(1) { ch = getc(fp); if(ch == EOF) break; putchar(ch); } getch(); }

Page 77: Programming In C Language| 2010 · PDF fileProgramming In C Language| 2010 Page No :1 Prepared By, Rushabh P Madhu (9662140014) WHAT IS A LANGUAGE ? Language is

Programming In C Language| 2010

Page No

:77 Prepared By, Rushabh P Madhu (9662140014)

/* Program # 3 : File Handling Program : Reading One-By-One Character from the file. Display only VOWELs on the screen. ------------------> Display the file without VOWELs To read one character from a file --> getc() To display a character on the screen --> putchar(ch) *********************************************/ #include <stdio.h> #include <conio.h> #include <ctype.h> void main() { char ch; FILE *fp; fp = fopen("d:\\Myfile.txt", "r "); clrscr(); while(1) { ch = getc(fp); if(ch == EOF) break; switch(toupper(ch)) { case 'A': case 'I': case 'O': case 'U': case 'E': putchar(ch); break; default: putchar(ch); } } getch();

/* 4.write a program to insert to data in file and display on screen */ #include<stdio.h> #include<conio.h> void main() { FILE *ft; char c; clrscr(); ft=fopen("d:\\Bca.txt","w"); printf("\n\t\t Enter char [ctr+z==Exit]\n\n\n"); while((c=getchar())!=EOF) { fputc(c,ft); } fclose(ft); ft=fopen("d:\\Bca.txt","r"); while((c=fgetc(ft))!=EOF) { printf("%c",c); } fclose(ft); getch(); }

Page 78: Programming In C Language| 2010 · PDF fileProgramming In C Language| 2010 Page No :1 Prepared By, Rushabh P Madhu (9662140014) WHAT IS A LANGUAGE ? Language is

Programming In C Language| 2010

Page No

:78 Prepared By, Rushabh P Madhu (9662140014)

/* 5. =====>> FILE HELNDLING <<=====

write a program to insert to data in file */ #include<stdio.h> #include<conio.h> void main() { FILE *ft; char ch; clrscr(); ft=fopen("d:\\Dinesh.txt","w"); printf("\n\t\t Enter no. [ctr+z==Exit]\n\n\n"); while(1) { ch=getche(); if(ch==13) break; putc(ch,ft); } fclose(ft); /* ft=fopen("d:\\Dinesh.txt","r"); while(1) { printf("%d",ch); } fclose(ft);*/ getch(); }

Page 79: Programming In C Language| 2010 · PDF fileProgramming In C Language| 2010 Page No :1 Prepared By, Rushabh P Madhu (9662140014) WHAT IS A LANGUAGE ? Language is

Programming In C Language| 2010

Page No

:79 Prepared By, Rushabh P Madhu (9662140014)

/* 6. write a program to print merge two file in third file */ #include<stdio.h> #include<conio.h> void main() { FILE *f1,*f2,*f3; char ch; clrscr(); f1=fopen("d:\\File1.txt","w"); f2=fopen("d:\\File2.txt","w"); printf("\n Enter your Data Entry in First File ['ctr+z' to exit]===>>\n\n"); while((ch=getchar())!=EOF) { putc(ch,f1); } printf("\n Enter your Data Entry in Second File ['ctr+z' to Exit]===>>\n\n"); while((ch=getchar())!=EOF) { putc(ch,f2); } fclose(f1); fclose(f2); f1=fopen("d:\\File1.txt","r"); f2=fopen("d:\\File2.txt","r"); f3=fopen("d:\\Merge.txt","a"); while((ch=getc(f1))!=EOF) { putc(ch,f3); } // fclose(f3); //f3=fopen("d:\\Merge.txt","a"); while((ch=getc(f2))!=EOF) { putc(ch,f3); } fclose(f1); fclose(f2); fclose(f3); /*--------------------------------------------------------------------------------------------------*/ f3=fopen("d:\\Merge.txt","r"); printf("\n\n <<:: Your Data ::>>\n\n"); while((ch=getc(f3))!=EOF) { printf("%c",ch); } fclose(f3); getch(); }

Page 80: Programming In C Language| 2010 · PDF fileProgramming In C Language| 2010 Page No :1 Prepared By, Rushabh P Madhu (9662140014) WHAT IS A LANGUAGE ? Language is

Programming In C Language| 2010

Page No

:80 Prepared By, Rushabh P Madhu (9662140014)

/* write a program to enter number to print odd and even in file using putw and getw */ #include<stdio.h> #include<conio.h> void main() { FILE *ft,*fo,*fe; int no; clrscr(); ft=fopen("d:\\Data.txt","w"); printf("\n\n\t\t ===>> enter number <<====\n\n"); while(1) { scanf("%d",&no); if(no==0) break; else putw(no,ft); } fclose(ft); ft=fopen("d:\\Data.txt","r"); fo=fopen("d:\\Odd.txt","w"); fe=fopen("d:\\Even.txt","w"); while((no=getw(ft))!=EOF) { if(no%2==0) putw(no,fe); else putw(no,fo); } fclose(ft); fclose(fo); fclose(fe); fo=fopen("d:\\Odd.txt","r"); fe=fopen("d:\\Even.txt","r"); printf("\n\n\t<<:: EVEN Number ::>>\n\n"); while((no=getw(fe))!=EOF) { printf("\n %d",no); } printf("\n\n\t<<:: ODD Number ::>>\n\n"); while((no=getw(fo))!=EOF) { printf("\n %d",no); } fclose(fo); fclose(fe); getch(); }

Page 81: Programming In C Language| 2010 · PDF fileProgramming In C Language| 2010 Page No :1 Prepared By, Rushabh P Madhu (9662140014) WHAT IS A LANGUAGE ? Language is

Programming In C Language| 2010

Page No

:81 Prepared By, Rushabh P Madhu (9662140014)

/* write a program n recod in file using 'fprintf and 'fscanf' */

#include<stdio.h> #include<conio.h> void main() { FILE *fp; int number,quantity,i; float price,value; char item[10],filename[10]; clrscr(); printf("\n Enter file Name\n\n"); scanf("%s",&filename); fp=fopen("d:\\filename","w"); printf("\n Number \t Item \t Qnt \t Rate\n "); for(i=1;i<=3;i++) { fscanf(stdin,"%d%s%d%f",&number,&item,&quantity,&price); fprintf(fp,"%d%s%d%f",number,item,quantity,price); } fclose(fp); fprintf(stdout,"\n\n"); fp=fopen("d:\\filename","r"); printf("\n Number \t Item \t Qnt \t Rate \t value\n "); for(i=1;i<=3;i++) { fscanf(fp,"%d%s%d%f",number,item,quantity,price); value=price*quantity ; fprintf(stdout,"\n%d \t %s \t %d \t %f \t%.2f",number,item,quantity,price,value); } fclose(fp); getch(); }

Page 82: Programming In C Language| 2010 · PDF fileProgramming In C Language| 2010 Page No :1 Prepared By, Rushabh P Madhu (9662140014) WHAT IS A LANGUAGE ? Language is

Programming In C Language| 2010

Page No

:82 Prepared By, Rushabh P Madhu (9662140014)

/* write a program to print bill amount in file (" Amount = qnt*rate") */ #include<stdio.h> #include<conio.h> struct invest { char item[10]; int pro_code,qnt; float amount,rate; }; struct invest e; void main() { FILE *fp; int i;// sum=0; float sum; clrscr(); fp=fopen("d:\\Amount.txt","w"); printf("\ncode\t Item \t qnt \t rate\n\n"); for(i=0;i<5;i++) { scanf("%d%s%d%f",&e.pro_code,&e.item,&e.qnt,&e.rate); fwrite(&e,sizeof(e),1,fp); } fclose(fp); clrscr(); fp=fopen("d:\\Amount.txt","r"); printf("\n\n\t\t==>>Bill Amount <<==\n"); printf("\n-----------------------------------------------------------------------------\n"); printf("\ncode \t Item \t Qnt \t Rate \t\t Amount"); printf("\n-----------------------------------------------------------------------------\n"); sum=0; for(i=0;i<5;i++) { fread(&e,sizeof(e),1,fp); e.amount=(e.qnt * e.rate); sum=sum+e.amount; printf("\n %d \t %s\t %d \t %.2f\t\t %.2f",e.pro_code,e.item,e.qnt,e.rate,e.amount); } printf("\n\n************************************************\n"); printf("\n\t \t Total Amount---------->>\t \t\ %.2f",sum); printf("\n\n************************************************\n"); fclose(fp); getch(); }

Page 83: Programming In C Language| 2010 · PDF fileProgramming In C Language| 2010 Page No :1 Prepared By, Rushabh P Madhu (9662140014) WHAT IS A LANGUAGE ? Language is

Programming In C Language| 2010

Page No

:83 Prepared By, Rushabh P Madhu (9662140014)

/* write a program to print bill amount in file (" Amount = qnt*rate") */ #include<stdio.h> #include<conio.h> struct student { char name[10]; int mark[10]; }s[50]; void main() { FILE *fp; int sum[10],no1,no2,i,j,t; float avg[10]; clrscr(); fp=fopen("d:\\Student.txt","w"); printf("\n Enter gow many student===>>"); scanf("%d",&no1); printf("\n Enter how many subject==>>"); scanf("%d",&no2); for(i=0;i<no1;i++) { t=0; printf("\n\n\n Enter student(%d)Nane===>>",i+1); scanf("%s",&s[i].name); for(j=0;j<no2;j++) { printf("\n\t enter subject[%d]Mark==>",j+1); scanf("%d",&s[i].mark[j]); t=t+s[i].mark[j]; } sum[i]=t; avg[i]=sum[i]/no2; fwrite(&s[i],sizeof(s[i]),1,fp); }fclose(fp); clrscr(); fp=fopen("d:\\Student.txt","r"); printf("\n\n\t\t==>> Result <<==\n"); printf("\n-----------------------------------------------------------------------------\n"); printf("\n Name"); for(i=1;i<=no2;i++) { printf("\t sub[%d]",i); } printf("\t Total \t Per"); printf("\n-----------------------------------------------------------------------------\n"); fread(&s[i],sizeof(s),1,fp); for(i=0;i<no1;i++) { printf("\n %s",s[i].name); for(j=0;j<no2;j++) printf("\t %d",s[i].mark[j]); printf("\t %d \t %f",sum[i],avg[i]); }fclose(fp); getch(); }

Page 84: Programming In C Language| 2010 · PDF fileProgramming In C Language| 2010 Page No :1 Prepared By, Rushabh P Madhu (9662140014) WHAT IS A LANGUAGE ? Language is

Programming In C Language| 2010

Page No

:84 Prepared By, Rushabh P Madhu (9662140014)

Command line argument :

Command line argument is the parameter supplied to a program when program is invoked. The parameter may represent a filename, the program should process. For example if we want to execute a program to copy the content of FILE1 to another file named FILE2 then we may type following command line like

Example:- PROGRAM FILE1 FILE2

In above command like PROGRAM is a filename where executable code of the program is stored. Now we think how this parameter get into the program.

We know that every C program must have one main function but what we have mentioned so far is that main() function can also take an argument. In fact main() function can take two argument like Argc and Argv. Through this function information contained in command line is passed into the program when the main() is called by the system.

The variable Argc is an Argument Counter that contained the numbers of argument on the command line. The Agrv is an argument vector that represent an array of character pointer that point to the command line arguments. the size of this array will be equal to the value of Argc. For Example. Command line given below argc is three and argv is an array of three pointer to string as shown below.

argv[0]=PROGRAM

argv[1]=FILE1

argv[2]=FILE2

In order to access the command line arguments, we must declare the main Function and its parameters as follow :

main( int argc,char *argv[ ])

{

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

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

}

Page 85: Programming In C Language| 2010 · PDF fileProgramming In C Language| 2010 Page No :1 Prepared By, Rushabh P Madhu (9662140014) WHAT IS A LANGUAGE ? Language is

Programming In C Language| 2010

Page No

:85 Prepared By, Rushabh P Madhu (9662140014)

� DYNAMIC MEMORY ALLOCATION

The process of allocating memory at run time is known as dynamic memory allocation. malloc() and calloc() are library routines known as “Memory Management Functions” that can be used for allocating and freeing memory during program execution.

Malloc()

/*******************************

COMMAND LINE ARGUMENTS

CMD01.C

*******************************/

#include<stdio.h> #include<conio.h> void main(int argc,char *argv[] ) { clrscr(); printf(“welcome to command line Argument.”); printf(“\n you have passed [%d] Agruments.“); printf("\n\t Argument 0 = %s\n",argv[0]); printf("\n\t Argument 1 = %s\n",argv[1]); printf("\n\t Argument 2 = %s\n”, argv[2]); getch();

}

/*******************************

CMD02.C

********************************/

#include <stdio.h> #include <conio.h> void main(int argc, char *argv[]) { int i; clrscr();

printf("\n\t Wel come to Command line arguments...\n"); printf("\n\t You have passed [%d] arguments\n",argc);

for(i=0; i<argc; i++) { printf("\n\t Arguments %d = %s\n", argv[i]); } getch(); }

/*******************************

CMD03.C :: Two Numbers Addition ********************************/

#include <stdio.h> #include <conio.h> #include <stdlib.h> void main(int argc, char *argv[]) { int a,b; clrscr(); printf("\n\t Two number addition....\n"); if(argc < 3)

{

printf("Not sufficient arguments...");

exit(0);

}

a = atoi(argv[1]); b = atoi(argv[2]);

printf("\n\t Sum of Two given numbers %d \n",(a+b));

getch();

/******************************

CMD04.C:: Copy the content of file to another *******************************/

main(int argc, char *argv[ ] ) { FILE *fp1,fp2; char ch; fp1=fopen(file1,”r”); if(fp1==NULL)

{ printf(“file not found”);

} fp2=fopen(file2,”w”); while(!feof(fp1)) { ch=getc(fp1); putc(ch,fp2); } printf(“file copied successfully”); getch(); }

Page 86: Programming In C Language| 2010 · PDF fileProgramming In C Language| 2010 Page No :1 Prepared By, Rushabh P Madhu (9662140014) WHAT IS A LANGUAGE ? Language is

Programming In C Language| 2010

Page No

:86 Prepared By, Rushabh P Madhu (9662140014)

A block of memory may be allocated using the function malloc(). The function reserves a block of memory of specified size and returns a pointer of type void. This means that we can assign it to any type of pointer. it takes the following form.

Ptr = (cast_type *) malloc(byte_size)

Ptr is a pointer of type cast_type. The malloc returns a pointer of cast_type to an area of

memory of size byte_size. For example,

X = (int *) malloc(100*sizeof(int));

On successful execution of this statement a memory space equivalent to “100 times for the size of int” bytes is reserved and the address of the first byte of the memory allocated is assigned to the pointer x of type int. Similarly statement

Cptr = (char *) malloc(10);

Allocates 10 byte of space for the cptr of type char. We may also use malloc to allocate space for complex data types such as structures. For example,

Stptr = (struct store*)malloc(sizeof(struct store));

Where stptr is pointer of type struct store. The malloc allocates a block of contiguous bytes. The allocation can fall if the space in the heap is not sufficient to satisfy the request. If it fails it returns a NULL.

Calloc()

Calloc is memory allocation function that is normally used for requesting memory space at runtime for storing derived data types such as arrays and structures. Calloc allocates multiple block of storage, each of the same size and then sets all bytes to zero. The general form of calloc is ;

Ptr = (cast_type *) calloc(n,elem_size);

The above statement allocates contiguous space of n blocks. Each of size elem_size. All bytes are initialized to zero and a pointer to the first byte of allocated region is returned. If there is not enough space, a NULL pointer is returned. The following segment of program allocates space to a structure variable.

struct student

{

char name[25];

Page 87: Programming In C Language| 2010 · PDF fileProgramming In C Language| 2010 Page No :1 Prepared By, Rushabh P Madhu (9662140014) WHAT IS A LANGUAGE ? Language is

Programming In C Language| 2010

Page No

:87 Prepared By, Rushabh P Madhu (9662140014)

float age;

long int id_num;

};

typedef struct student record;

record *stptr;

int class size=30;

stptr = (record *) calloc(class_size, sizeof(record));

Her record is of type struct student, having three members name, age and id_num. The calloc allocates memory to hold data for 30 such records.

� PROGRAM LIST

1.Printf () Statement.

(1) Print "Shivam " (2) Print Your Name On screen. (3) Print Address on screen.

2.Scanf() statement.

(1) Enter the value of an integer variable and print it on screen. (3) Input two numbers and prints its square and cube. (4) Input two numbers and prints its Addition, Substraction, Multiplication, and Division. (5) Verify the formula of Simple Interest. (6) Input a Rupees and prints its value converted into Dollar. (7) Input a Number of Chairs and its Total Cost and Prints the Cost of Each chair. (8) Verify the formula l=(c+d)*(g+h). (9) Verify the formula x=((k-4)*(a*4))/100 (10) verify the formula s=((4*a+c)-2*a*b)/100 (11) Find Cofound interest verify the formula a=p*(1+(r/100)/n)-p (12) Verify the formula t=((v+s)+(l-m)*l) (13) Calculate the area of circle. (14) Calculate the area of Triangel. (15) Verify the formula c=(a+b)*(a+b)

3.If...Else statement:

(1) Enter value and check it is less, equal or greater than zero. (2) Input 2 number and print the maximum among them. (3) Input 2 number and print the maximum among them. (without If statement) (4) Input 2 number and print the minimum among them. (5) Input 2 number and print the minimum among them. (without If statement) (6) Input 3 number and print the maximum among them. (7) Input the age of 5 student and print the number of student having age less than or equal to 21 and greater than 21.

Page 88: Programming In C Language| 2010 · PDF fileProgramming In C Language| 2010 Page No :1 Prepared By, Rushabh P Madhu (9662140014) WHAT IS A LANGUAGE ? Language is

Programming In C Language| 2010

Page No

:88 Prepared By, Rushabh P Madhu (9662140014)

(8) To make the result of class. (9) Print & calculate area of circle, area of triangle & (f+g)*(f+g) & simple interest & exit in one program. (10) Print & calculate addition, substrection, multiplication & division of two value in one progarm using if() statement. (11) Make progarm of General knowledge test (similar to KBC). (12) Input a number & print the number is odd or even.

(13) Get a character in lower case form user and display it in upper case.

(14) Get a character from user and print tell that is it vowel or consonant.

Make all above programs using switch() statement.

Get a character from user and decide is it vowel or consonant. (Use switch)

� Get a Single interger value from the user and display appropriate day of week in string.

� Get a Single interger value from the user and display appropriate Name of month in string.

� Get a Single interger value from the user and check whether it is character, vowel or consonant and display appropriate message on screen.

� Get a Percentage from the user and display it’s grade on screen using switch statemenent.

Looping structure (while, do...while, for)

1. print 1 to 10. 2. print 2,4,6,8,10, 3. print 1,3,5,7,9, 4. print 1,2,4,8,16,32,64, 5. print 10 to 1 6. print 1,10,2,9,3,8,4,7,5,6, 7. print 2,11,20,28,25,41,46,50,53,55,56, 8. print first 100 even number.

9. print first 100 odd number.

10. print first 50 natural number.

11. print the total of 1 to 50. 12. print the total of 1/2+2/3+....+9/10. 13. print the total of 1-2+3-4+5-6+7-8+9-10. 14. print the total of first 100 even numbers.

15. print the total of first 100 odd numbers.

16. find sum for this series 0.1+0.02+0.003+0.0004+0.000005.

17. Except one no from user and display Reverse if it.

18. Except one no from user and display sum of its digits.

19. Except one no from user and display its factorial.

Page 89: Programming In C Language| 2010 · PDF fileProgramming In C Language| 2010 Page No :1 Prepared By, Rushabh P Madhu (9662140014) WHAT IS A LANGUAGE ? Language is

Programming In C Language| 2010

Page No

:89 Prepared By, Rushabh P Madhu (9662140014)

20. Except one no from user and find if it is prime or not.

21. Except one no from user and find if it is Armstrong or not.

22. Print 0 1 1 2 3 5 8 13 21 34 55 … (Fibonanci series)

Page 90: Programming In C Language| 2010 · PDF fileProgramming In C Language| 2010 Page No :1 Prepared By, Rushabh P Madhu (9662140014) WHAT IS A LANGUAGE ? Language is

Programming In C Language| 2010

Page No

:90 Prepared By, Rushabh P Madhu (9662140014)

5. Nested looping structure.

Pattern-I Pattern-II Pattern-III

*

**

***

****

*****

*

**

***

****

*****

*

**

***

****

*****

12345 12345 12345 12345 12345

11111 22222 33333 44444 55555

1 2 3 4 5 2 4 6 8 10 3 6 9 12 15 4 8 12 16 20 5 1015 20 25

A A A A A B B B B B C C C C C D D D D D E E E E E

1 22 333 44444 555555

1 12 123 1234 12345

5 54 543 5432 54321

1 21 321 4321 54321

1 2 3 4 5 6 7 8 9 10 1112131415

1 01 010 1010 10101

1 10 101 1010 10101

a b c d e f g h i j k l m n o

A bb ccc dddd eeeee

z y x w v u t s r q p o n m l

1 10 100 1000 10000

5 45 345 2345 12345

Implement all above program with Pattern-II & Pattern-III

12345 1234 123 12 1

12345 2468 369 48 5

54321 5432 543 54 5

54321 4321 321 21 1

12345 2345 345 45 5

55555 4444 333 22 1

2 4 6 8 10 4 6 8 10 6 8 10 8 10 10

a b c d e b c d e c d e d e e

Implement all above program with Pattern-I & Pattern-II

6. Array & Pointer

Page 91: Programming In C Language| 2010 · PDF fileProgramming In C Language| 2010 Page No :1 Prepared By, Rushabh P Madhu (9662140014) WHAT IS A LANGUAGE ? Language is

Programming In C Language| 2010

Page No

:91 Prepared By, Rushabh P Madhu (9662140014)

1. Accept 5 numbers in an array and display it.

2. Accept 10 numbers in an array, sort it and display it.

3. Accept 4 numbers in 2-d array.

4. Accept 9 numbers in form of matrix. (3 X 3 matrix)

5. Accept 10 numbers in an array and store it in another array.

6. Accept 10 numbers in an array and find total of positive and negative no.

7. Accept 5 numbers in an array and find maximum and minimum value.

8. Accept 5 numbers in an array and calculate average of it.

9. Accept values in 3 X 4 array and find out row total, column total, maximum, minimum and total.

10. Create a program that shows concept of pointer.

11. Create a program to swap two values (Pass by reference)

12. Create a program to accept 10 numbers in an array and sort it with the help of pointer.

Built in functions

1. Accept one no and display its absolute value. 2. Accept one no and display its log. 3. Accept one no and display its square root. 4. Get 2 no from user and display base^exp. (2^3=8)

5. Get a string from user and display length of that string.

6. Get a string from user and copy it in another variable.

7. Get two strings from user and compare weather both are same or not.

8. Get a string from user and display reverse of it.

9. Get two strings from user and merge it into first string.

10. Get a string from user and display it in lower case.

11. Get a string from user and display it in upper case.

8. User Define Function

1. Create a user define function named sum which accept 2 arguments (of integer type) and return the sum of them.

2. Create a user define function named avg which pass array as argument (of integer type) and return its average value.

3. Create a user define function named evenodd which accept one argument (of integer type) and return if the number is even or odd.

4. Create a user define function named fact which accept one argument (of integer type) and return the factorial of given number.

5. Create a user define function named prime which accept one argument (of integer type) and display that the no is prime or not. (no need to return value)

6. Create a user define function named triangle which accept one argument (of integer type) and display a triangle like.

Page 92: Programming In C Language| 2010 · PDF fileProgramming In C Language| 2010 Page No :1 Prepared By, Rushabh P Madhu (9662140014) WHAT IS A LANGUAGE ? Language is

Programming In C Language| 2010

Page No

:92 Prepared By, Rushabh P Madhu (9662140014)

7. (If you have given 4 as argument)

8. 1 9. 1 2 10. 1 2 3 11. 1 2 3 4 12. Create a user define function named power which accept two arguments

(of integer type) (i) base (ii) expon and display the base^expon value.

13. Create a user define function named Sroot which accept one argument (of integer type) and display the square root of that no.

14. Create a user define function named ASCII which accept one argument (of character type) and display ASCII value of that character.

15. Create a user define function named CHR which accept one argument (of integer type) and display character of that ASCII value.

16. 9. Structure 17. Create a structure named student that have member variable roll no, name,

m1, m2, m3, sum, average, and grade. Program ask for roll no, name, m1, m2, m3 and calculate sum, average and grade.

18. Create a structure named EMP that have member variables employee no,

employee name, basic salary, DA, HRA, TA , PF and Gross Salary.

19. In above structure create an array of structure. 20. In above structure create an array of structure and use pointer. 21. Write a program to find size of structure.

10. File Handling

1. Write a programme to create a file.

2. Write a programme to read a file.

3. Write a programme to copy one file to another file.

4. Write a programme to add data into an existing file.

5. Create a database for a person, which includes information like person id, person name, age, phone no, height. Give the facility to add the data, read the data & person id should not be duplicate.

6. Write a program to accept file name form command line argument and write data into it.

7. Write a program which accept two file name form command line argument arg1 and arg2, copy the content of arg1 to arg2.

8. Write a program to understand the use of getc(), putc().

9. Write a program to understand the use of getch(), putch().

10. Write a program to understand the use feof(), fgetc(), fgets(), fputc(), fputs(), fread(), fwrite(), ftell() and fseek().

Important Question

1) Write history of C in brief.

2) Write full forms of the given abbreviations

Page 93: Programming In C Language| 2010 · PDF fileProgramming In C Language| 2010 Page No :1 Prepared By, Rushabh P Madhu (9662140014) WHAT IS A LANGUAGE ? Language is

Programming In C Language| 2010

Page No

:93 Prepared By, Rushabh P Madhu (9662140014)

BASCI, COBOL, MS-DOS, BCPL

3) Write a short note on importance of C language in programming.

4) Write basic structure of C language program and explain its each part.

5) Explain the processes:

a. How to open a new program

b. How to use C language editor

c. How to compile a program (different ways to compile)

d. How to run a program

6) What does a compiler do when you compile your program?

7) What is the need to compile a program?

8) Explain C is free form language in brief.

9) Explain use of printf statement in programming and its use with ‘\n’ character.

10) What does curly brackets ({) indicate in C programming?

11) Write syntax of printf and scanf statements and explain use of scanf

statement with example.

12) What is datatype? Why it is require in C language? List all datatypes that you know with its suitable example.

13) What is ‘#’ sign called in C language? Where it is useful in C programs? Why we use this in programs explain with an example.

14) What is variable? Explain its usefulness in C language.

15) Write a program that finds simple interest.

16) Write a program that finds greatest number from the given three numbers.

17) Explain character set of C language category wise.

18) List keywords of C language.

19) Explain arithmetic and relational operators with examples.

20) What is use of ‘if’ statement in programming? Explain with an example.

21) What is use of ‘if … else’ statement in programming? Explain with an example.

22) Write a program that reads a number and prints the number is ODD or EVEN.