0% found this document useful (0 votes)
10 views

C.3

The document outlines the evolution of programming languages from first generation machine language to fourth generation languages, emphasizing the use of mnemonics and high-level languages. It discusses programming techniques such as procedural and object-oriented programming, as well as the structure of C programming, including constants, variables, data types, and operators. Additionally, it provides an overview of algorithms, pseudo code, and flowcharts as tools for problem-solving in programming.

Uploaded by

somnathjana7896
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
10 views

C.3

The document outlines the evolution of programming languages from first generation machine language to fourth generation languages, emphasizing the use of mnemonics and high-level languages. It discusses programming techniques such as procedural and object-oriented programming, as well as the structure of C programming, including constants, variables, data types, and operators. Additionally, it provides an overview of algorithms, pseudo code, and flowcharts as tools for problem-solving in programming.

Uploaded by

somnathjana7896
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 67

Prepared by A.

Mandal
Generation of Programming Language

First Generation
In first generation language, all the instructions were given in the binary form and is referred to as
machine language or Low Level Language (LLL). It is very difficult for us to write or read instructions
written in binaries. Consider the following instruction written in binaries:

0100 00011001 0101 01010011

Second Generation
In second generation language, instructions are written with mnemonics to simplify the program.
The symbolic instruction language is known as Assembly Language. In order to execute these
instructions, all mnemonics are converted into binaries with the help of a translator known as
Assembler. The program written using mnemonics is called source program and the binary form is
called object program.

Source Program

Assembler

Object Program

Assembly Language programs are commonly used to write programs for electronics controls using
microprocessor, e.g. computerised copier machine, computerised telephone billing etc.

Third Generation
In third generation languages, instructions are written using English language with symbols and digits. Third
generation languages are also known as High Level Language (HLL). The commonly used high level languages
are FORTRAN, BASIC, COBOL etc.
In order to execute the instructions, the source program is translated into binary form by compiler or
interpreter.

Source Program

Compiler/
Interpreter

Object Program
Prepared by A. Mandal
Fourth Generation
Fourth generation languages refer to software packages which are mostly written in one of the languages
(FORTRAN, C etc.) for any specific application. It is very useful or users to perform a task without writing
programs. The user has to enter the command to call the program which is readily available in the package.
This language is also called command line language. Some commonly used 4 GL packages are dBase, FoxPro,
Oracle etc.

Computer Programming
A program has a set of instructions written in correct order to get the desired result. The method of writing
the instruction to solve the given problem is called programming.

Programming Techniques
There are two types of Programming techniques commonly used:
i) Procedural Programming
ii) Object Oriented programming (OOP)

Procedural Programming
In procedural programming, for a given problem, variables are identified and instructions are written using
the variables in correct sequence to get the required result. Sometimes the program required unconditional
transfer of control from one part of the program to another. The procedural programming method is
commonly used to solve scientific and engineering problems involving variables.

Object Oriented Programming


In object oriented programming, objects which have data related to a person or item are used. The program
can be written using many functional blocks. These blocks contain instructions similar to procedural
programming.
Prepared by A. Mandal
Algorithm
It is a complete step by step representation of the solution of the problem, represented in English like
language. An algorithm can be quit abstract or quit detailed.

Write an algorithm to find the average of n numbers:

Abstract Algorithm

1. START
2. Read n numbers
3. Add these n numbers
4. Divide the addition result by n to get the average
5. Print the average
6. STOP

Detailed Algorithm

1. START
2. Read the value of n
3. Assign 0 to sum
4. Repeat n times
5. Read number
6. Add number to sum
7. End repeat
8. Divide sum by n to get the average
9. Print average
10. STOP

Pseudo Code
It is a formal representation than algorithm. In pseudo code, each of the steps will be written via operators
and statements equivalent to some programming language instruction. An algorithm can be written in the
form of pseudo code as follows:

1. START
2. Read n
3. sum← 0
4. for i← 1 to n do
5. Read numberi
6. sum←sum+numberi
7. End for
8. average←sum/n
9. Print average
10. STOP

Flow Chart
A flow chart is a symbolic or diagrammatic representation of an algorithm. The various symbols used in
flowchart are:
Prepared by A. Mandal
Symbol Meaning

START/STOP

Input/Output

Processing

Checking/Decision making

Connector (Represents continuity of the flowchart in another place/page)

Arrows (Represents direction of flow)

Example:
Draw a flowchart to find the sum and product of given two numbers.

START

Read a, b

sum←a+b

product←a×b

Print sum,
product

STOP
Prepared by A. Mandal
Introduction to C
History of C:
‘C’ seems a strange name for a programming language. But this strange sounding language is one of
the most popular computer languages today because it is a structured, high-level, machine
independent language. It allows software developers to develop programs without worrying about
the hardware platforms where they will be implemented.
The history and development of C is illustrated below:-

1960 ALGOL International Group

1967 BCPL Martin Richards

1970 B Ken Thompson

1972 Traditional C Dennis Ritchie (at Bell Laboratory)

1978 K&R C Kernighan and Ritchie

1989 ANSI C ANSII Committee

1990 ANSI/ISO C ISO Committee

1999 C99 Standardization Committee

Features of C language:

i. C is structured & procedural language.


ii. C is high level language.
iii. C is lower case sensitive language.
Prepared by A. Mandal
Applications of C:

 General applications
 Database systems
 Spread sheets
 Graphic packages
 CAD applications
 Word processors etc.

Advantages of C:

 Machine Independence: C is a high level language. C codes can be compiled on different


machines and the produce the same output when executed.

 Economy of expression: C is a compact and coherent programming language. The code is


quite cryptic and so, small length of codes can perform complex tasks.

 Data structures: There are several ways to store data in C, which allows easy access to data
in C.

 Operator richness: C supports a wide range of operators to handle arithmetic and logical
calculations.

Disadvantage of C:

 Difficult to debug: C gives a lot of freedom to the developer, but it appears a bit complex for
a new comer to find what is wrong with a program.

 Loosely syntaxed: C allows a lot of freedom in coding. We can put the symbol (;) at the end
of a statement. We can also put blank lines, white spaces anywhere we want in the
program. There is no fixed place to start or end a line. This can give rise to codes that are
difficult to understand by reading.
Prepared by A. Mandal
Basic Structure of C Program:

Documentation Section

Link Section
Definition Section

Global Declaration Section

main() function section


{
Declaration Part
Executable Part
}

Subprogram Section

Function 1
(User-defined functions)
Function 2
-------
--------
Function n
-

The documentation section consists of a set of comment lines giving the name of the program, the
author and other details, which the programmer would like to use later.

The link section provides instructions to the compiler to link functions from the system library.

The definition section defines all symbolic constants.

There are some variables that are used in more than one function. Such variables are called global
variables and are declared in the global declaration section that is outside of all the functions. This
section also declares all user-defined functions.

Every C program must have one main() function section. This section contains two parts,
declaration and executable part. The declaration part declares all the variables used in the
executable part. There is at least one statement in the executable part. The program execution
begins at the opening brace and ends at the closing brace.

The subprogram section contains all the user-defined functions that are called in the main function.
Prepared by A. Mandal
Constants, Variables and Data Types
A programming language is designed to help process certain kinds of data consisting of
numbers, characters and strings and to provide useful output known as information. Like any other
language, C has its own vocabulary and grammar. Now we will discuss the concept of constants and
variables and their types as they relate to C programming language.

Character Set:

The characters in C are grouped into the following categories:


1. Letters
2. Digits
3. Special Characters
4. White Spaces

Letters: Uppercase A to Z and Lowercase a to z


Digits: 0 to 9
Special Characters:

, comma & ampersand


. period ^ caret
; semicolon * asterisk
: colon - minus sign
? question mark + plus sign
‘ apostrophe < less than sign
“ quotation mark > greater than sign
! exclamation mark ( left parenthesis
| vertical bar ) right parenthesis
\ back slash [ left bracket
~ tilde ] right bracket
_ under score { left brace
$ dollar sign } right brace
% percent sign # number sign

White Spaces:
Blank space, Horizontal tab, Carriage return, New line, Form feed.
Prepared by A. Mandal

C Tokens:

In a passage of text, individual words and punctuation marks are called tokens. Similarly, in a C
program the smallest individual units are known as C tokens. C has six types of tokens as shown
below.

C Tokens

Keywords Constants Strings Operators

float -15.5 “ABC” + -


while 100 “year” */

Identifiers Special Symbols

main []
amoun {}
t

Keywords:

Keywords are some special words which have fixed meaning and cannot be changed. Keywords
serve as basic building blocks for program statements. ANSI C supports 32 keywords.

auto double int struct


break else long switch
case enum register typedef
char extern return union
const float short unsigned
continue for signed void
default goto sizeof volatile
do if static while

Identifiers:

Identifiers refer to the names of variables, functions and arrays. These are user defined names and
consist of a sequence of letters and digits with a letter as first character.

Constants:

Constants in C refer to fixed values that do not change during the execution of a program. C
supports several types of constants.
Prepared by A. Mandal

Constants

Numeric Constants Character Constants

Integer Real Single Character String


Constants Constants Constants Constants

(20, 12) (13.04, 33.256) (‘A’, ‘X’) (“Year”, ”ABC”)

Backslash Character Constants: (Escape Sequence)

Constant Meaning
\a Audible alert(bell)
\b Back space
\f Form feed
\n New line
\r Carriage return
\t Horizontal tab
\v Vertical tab
\’ Single quote
\” Double quote
\? Question mark
\\ Backslash
\0 null

Variables:
A variable is a data name that may be used to store a data value. Unlike constants that remain
unchanged during the execution of a program, a variable may take different values at different
times during execution.

Rules for Making a Variable Name:

1. They must begin with a letter. Some system permits underscore as the first character.
2. ANSI standard recognize a length of 31 characters. However length should not be normally
more than eight characters. Since only first eight characters are treated as significant by
many compilers.
3. Uppercase and lower case are significant. That is the variable Total is not same as total.
4. White spaces are not allowed.
5. Except underscore (_) all other special characters are not allowed.
Prepared by A. Mandal
Data Types:
C is reach in its data type. Data type indicates what kind of data should be stored in a variable.
Types of data may be integer, floating point, character etc. There are 3 types of data type in C.
1) Primary of fundamental data type (Ex: int, char, float etc.)
2) Derived data type (Ex: array, pointer)
3) User defined data type (Ex: structure, union)

Primary Data Type:


Primary data types are:
i) Integer type
Ex:
Signed Unsigned
short int unsigned short int
int unsigned int
long int unsigned long int

ii) Character type


Ex:
Signed Unsigned
char Unsigned char
iii) Floating point type
Ex:
float
double
long double
iv) Void type
v) Ex: void

Size & Range of Data types:

Data Type Size(bits) Range


char 8 -128 to 127
unsigned char 8 0 to 255
short int 8 -128 to 127
unsigned short int 8 0 to 255
int 16 -32768 to 32767
unsigned int 16 0 to 65535
long int 32 -2147483648 to 2147483647 (231 to 231-1)
unsigned long int 32 0 to 4294967295
float 32 3.4E-38 to 3.4E+38
double 64 1.7E-308 to 1.7E+308
long double 80 3.4E-4932 to 1.1E+4932
Prepared by A. Mandal

Operators
An operator is a symbol that tells the computer to perform certain mathematical or logical
manipulation. C operators are:

1.Arithmetic Operators
These operators are used for arithmetical calculation. Arithmetic operators are:
Operators Meaning
+ Addition or unary plus
- Subtraction or unary minus
* Multiplication
/ Division
% Modulo division
2. Relational Operators
Comparisons can be done with the help of these operators. Relational operators are:
Operators Meaning
< Is less than
<= Is less than or equal to
> Is greater than
>= Is greater than or equal to
== Is equal to
!= Is not equal to
3. Logical Operators
These operators are used when we want to test more than one condition and make decisions.
Logical operators are:
Operators Meaning
&& Logical AND
|| Logical OR
! Logical NOT
When all the conditions are true then AND operator returns the value true otherwise it returns
false.
If any one the condition is true then OR operator returns the value true otherwise it returns false.
If the condition is true then NOT operator returns false otherwise it returns true.

4. Assignment Operators
This operator is used to assign the result of an expression to a variable. ‘=’ is the assignment
operator.
Shorthand Assignment Operators
Statement with simple assignment operator Shorthand notation
a=a+1 a+=1
a=a-1 a-=1
a=a*(n+1) a*=n+1
a=a/(n+1) a/=n+1
a=a%b a%=b
Prepared by A. Mandal

5. Increment & Decrement Operators


The operator ++ adds 1 to the operand. So it is called increment operator.
Ex:
int a=10;
a++; it means 1 is added to the previous value of a. Now a=11.

The operator -- subtracts 1 from the operand. So it is called decrement operator.


Ex:
int a=10;
a--; it means 1 is subtracted from the previous value of a. Now a=9.

6. Conditional Operator
A ternary operator pair “?:” is called conditional operator. It uses to construct conditional
expression of the form:
Exp1? Exp2 : Exp3
Exp1 is evaluated first. If it is true then the Exp2 is evaluated and it becomes the value of the
expression. Otherwise Exp3 is evaluated and it becomes the value of the expression.
Ex:
int a=10, b=15;
x=(a>b)? a : b;
The value of x will be the value of b.

7. Bitwise Operators
These operators are used for testing bits or shifting them right or left. Bitwise operator may not be
applied to float or double. These operators are:
Operators Meaning
~ Bitwise 1’s complement
| Bitwise OR
& Bitwise AND
^ Bitwise Exclusive OR
<< Bitwise left shift
>> Bitwise right shift

8. Special Operators
C supports some special operators such as comma operator, sizeof operator, pointer operators (&
and *) and member selection operators (. and ->).

Pre Increment and Post Increment:


In pre increment first 1 is added to the operand and then the expression is evaluated using new
value. We can perform pre increment by putting ++ operator at the front of an operand.
Ex: ++a;
In post increment first the expression is evaluated using old value and then 1 is added to the
operand. We can perform pre increment by putting ++ operator at the end of an operand.
Ex: a++;
Example using expression:
int x=10,b,c;
Prepared by A. Mandal
b=(++x)*2;
c=(b++)*3;
Here the value of b=22 and value of c=66

Type conversion in Expression:


Implicit type conversion
C permits mixing of constants and variables of different types in an expression. C automatically
converts any intermediate value to the proper type so that the expression can be evaluated without
loosing any significance. This automatic conversion is known as implicit type conversion. In this type
of conversion “lower” type is automatically converted into “higher” type.

Ex:
int a=10,b=20;
float c=2.5,d;
d=a+b+c;
The value of d is converted into float because in the expression a+b+c, a and b are integer but c is
float. So the result is converted to float.

long double
Conversion
double
Hierarchy
float

Unsigned long int

long int

unsigned int

int

Short char

Explicit type conversion


In some times automatic conversion is not possible in expression. For example
int a=5,b=2;
float c;
c=a/b;
In this situation a and b are integer. So the division result will be in integer. But the original result is
float (2.5). In this situation automatic conversion is not possible. We have to convert the result into
float by force. This conversion is known as Explicit conversion or Casting a value.

Syntax:
(type)variable/Expression;
So the above example can be written as
int a=5,b=2;
float c;
c=(float)a/b;
Prepared by A. Mandal

Operator precedence and associativity:


The precedence is used to determine how an expression involving more than one operator is
evaluated. The operator at the higher level of precedence is evaluated first. The operators of the
same precedence are evaluated either from ‘left to right’ or ‘right to left’ depending on the level.
This is known as associativity property of an operator.
Ex: Consider the expression x=a+b*c
At first the operator ‘*’ is evaluated and then ‘+’ is evaluated.
Operator Associativity Rank
() Left to Right 1
[]
+ Right to Left 2
-
++
--
!
~
*
&
sizeof
(type)
* Left to Right 3
/
%
+ Left to Right 4
-
<< Left to Right 5
>>
< Left to Right 6
<=
>
>=
== Left to Right 7
!=
& Left to Right 8
^ Left to Right 9
| Left to Right 10
&& Left to Right 11
|| Left to Right 12
?: Right to Left 13
= Right to Left 14
*= /= %=
+= -= &=
^= |=
<<= >>=
, Left to Right 15
Prepared by A. Mandal
Decision Making and Branching:
C possess decision making capabilities by supporting the following statements:

1. Simple if statement
2. if-else statement
3. Nested if statement
4. else-if statement
5. switch statement
6. Conditional operator statement
7. goto statemets

Simple if statement
An if statement consists of a boolean expression followed by one or more statements. If the
condition is true the statement will be executed.
The general form of simple if statement is:

if(Test condition)
{
Statements;
}

The statements may be a single statement or a group of statements. If the condition is true then
the statements will be run; otherwise it will be skipped.

if-else statement

The general form of if-else statement is:

if(Test condition)
{
Statements;
}
else
{
Statements;
}

The statements may be a single statement or a group of statements. If the condition is true then
the if block statements will be run; otherwise else block statements will be run.
Prepared by A. Mandal
Nested if-else statement

if(Test condition)
{
if(Test condition)
{
Statements;
}
else
{
Statements;
}
}

else
{
if(Test condition)
{
Statements;
}
else
{
Statements;
}
}

else-if statement

if(Test condition)
{
Statements;
}
else if(Test condition)
{
Statements;
}
else if(Test condition)
{
Statements;
}
.
.
.
.
.
else
{
Statements;
}
Prepared by A. Mandal
Character functions :
SL FUNCTIONS DESCRIPTION
NO.
1 isalnum(c) If c is an alphanumeric character then it returns true otherwise
false
2 isalpha(c) Returns true if c is an alphabate
3 isdigit(c) Returns true if c is digit
4 islower(c) Returns true if c is lower case
5 isupper(c) Returns true if c is upper case
6 isprint(c) Returns true if c is a printable character
7 ispunct(c) Returns true if c is a puntution mark
8 isspace(c) Returns true if c is a white space character

Character conversion function :


SL FUNCTIONS DESCRIPTION
NO
1 toupper(c) Converse the character into upper case
2 tolower(c) Converse the character into lower case

SWITCH CASE STATEMENT


Syntax :
Switch(expression/variable)
{
case value 1:
Statements;
break;
case value 2:
Statements;
break;
.
.
.
default:
Statements;
break;
}

Note :
The expression is an integer or character expression. Value1,value2 are constant or constant
expression are known as case label.

Limitation of switch case :


1. A float expression cannot be tested using a switch.
2. Case can never have variable expression.
3. Multiple cases cannot use same expression.
4. Range cannot be checked using switch.
Prepared by A. Mandal
GOTO STATEMENT
C supports the goto statement to branch unconditionally from one point two another point in
the program.
The goto requires a label in order to identify the place where the goto is to be made. A label
is any valid variable name and must be followed by a (:). The label is placed immediately before the
statement where the control is to be transferred.

Syntax:
goto label; label:
--------------- Statement;
--------------- ------------------------
--------------- ------------------------
--------------- ------------------------
Label: goto label;
Statement;

Conditional Operator Statement:


The general syntax of conditional operator statement is:
Exp1? Exp2: Exp3
If the ‘Exp1’ is true then ‘Exp2’ is the answer; otherwise ‘Exp3’ is the answer.

LOOPING:
In looping, sequences of statements are executed until some conditions for termination of
the loop are satisfied. A program loop therefore consists of two segments, one known as the body
of the loop and other known as control statement. The control statement tests certain condition
and then directs the repeated execution of the statements contain in the body of the loop.
Example:
while(condition) //control statement
{
Statements; //body of the loop
}

Entry and exit controlled loop:


Depending on the position of the control statement in a loop, a control structure may be classified
either as the entry controlled loop or as the exit controlled loop.
In the entry controlled loop, the controlled condition tested before the start of the
loop execution. If the conditions are not satisfied then the body of the loop will not be executed.

In the case of an exit controlled loop, the test is performed at the end of the body of the
loop and therefore the body is executed unconditionally for the first time.
Entry and exit controlled loop are known as pre-test and post-test loop respectively.
Prepared by A. Mandal

Entry Entry

Body of the
Test False
Loop
Condition
?

True
True Test False
Body of the Condition
?
Loop

Exit controlled loop


Entry controlled loop

Counter controlled and sentinel controlled loop :


When we know in advance exactly how many times the loop will be executed, we use a counter
controlled loop. We use a counter variable known as counter. The counter must be initialized,
tested and updated properly for the desired loop operation. A counter controlled loop is sometimes
called definite repetition loop.
In a sentinel controlled loop, a special value called a sentinel value is used to change
the loop controlled expression from true to false. For example when reading data we may indicate
the end of data by a special value like -1. A sentinel controlled loop is often called indefinite
repetition loop.

Category of loops:
There are three types of loop available in C. These are:
1. while loop
2. do-while loop
3. for loop

While Loop
It is an entry controlled loop. The condition is evaluated and if the condition is true then body of the
loop is executed. After execution of the body the condition is once again evaluated and if it is true
then body of the loop executed once again. This process continues until the condition become
false.
Syntax:
while(condition)
{
Statements;
}
Prepared by A. Mandal
do-While Loop
It is an exit controlled loop. At first body of the loop is executed then condition is tested. If the
condition is true then body of the loop is executed again. This process continues until the condition
become false.
Syntax:
do
{
Statements;
} while(condition);

for Loop
It is an entry controlled loop. Initialization of control variable done at first. Then the condition is
evaluated. If the condition is true then body of the loop is executed. Then control variable is
incremented or decremented and condition is evaluated again. If the condition is true then body of
the loop is executed once again. This process continues until the condition become false.

Syntax:
for(initialization; condition; increment/decrement)
{
Statements;
}

Additional features of for loop

1) The initialization section contains more than one initialization statements separated by “,”.
2) Like initialization section the increment/decrement section contain more than one part
separated by comma.

Ex.-
for(i=0,j=0;i<=10;i++,j--)
{
…………….
…………….
…………….
}
3) The test condition may have any compound relation and the testing need not be limited
only to the loop control variable.
Ex.-
for(i=1;i<20&&sum<100;i++)
{
……………..
……………..
}
4) It is also permissible to use expression in the assignment statements of initialization and
increment section.
Ex.-
for(x=(m+n)/2;x>0x=x/2)
{
…………..
…………..
…………..
}
5) Another unique aspect of for loop is that one or more sections can omitted, if necessary.
Prepared by A. Mandal
Ex.-
n=123;
for(;n>0;)
{
…………….
…………….
…………….
}
6) We can setup time delay loops using the null statement as follows:

for(i=0;i<=1000;i++)
;
Jumping from loops
‘break’ statement:-
When a break statement is encountered inside a loop,the loop is immediately exited
and the program continues with the statement immediately following the loop. When the loops are
nested,the break would only exit from the loop containing it.
Ex.-
while(conditon)
{
…………….
…………….
…………….
break;
…………….
…………….
}

continue statement:-
C support another jumping statement called continue. This statement causes the loop
to be continued with next iteration after skipping any statements in between. The continue
statement tells the compiler “skip the following statements and continue with the next iteration”.

while(condition)
{
………………
……………..
continue;
…………….
…………….
}
Prepared by A. Mandal
Array
An array as a collection of variables of the same type which are stored in contiguous memory
locations.
Ex: int a[10];

Type of Array
1. Single dimensional array
2. Two dimensional array
3. Multi dimensional array

Single dimensional array


A list of items can be given one variable name using only one subscript and such a variable is called
one dimensional array.

Declaration
Data_type array_name[size];
Ex:
int a[5];

a[0] a[1] a[2] a[3] a[4]

Initialization
Data_type array_name[size]={list of values};

Ex:
int a[3]={7,10,15};
Here
a[0]=7
a[1]=10 and
a[2]=15

We can also write without size as following:


int a[]={7,10,15};

Another method
int a[3];
a[0]=7;
a[1]=10;
a[2]=15;
If only one element is initialized then remaining elements of the array will be set to zero.
Ex:
int a[3]={3};
Here
a[0]=3
a[1]=0 and
a[2]=0
Prepared by A. Mandal
Two dimensional array
When an array has two dimension, row and column; it is called two dimensional array.

Declaration
Data_type array_name[row_size][col_size];
Ex:
int a[2][3];

a[0][0] a[0][1] a[0][2]


a[1][0] a[1][1] a[1][2]

Initialization
Int a[2][3]={ {4,7,9},{3,9,5} };
Here
a[0][0]=4
a[0][1]=7
a[0][2]=9
a[1][0]=3
a[1][1]=9
a[1][2]=5
Prepared by A. Mandal
Strings
A string is a sequence of characters that is treated as a single data item. Any group of characters
defined between double quotation marks is a string constant.
Example – “Man obviously made to think.”

Declaration of String
char string_name[size];
Ex:
char str[20];

Initialization of String
char string_name[size]=”value”
Ex:
char str[5]=”GOOD”
or
char string_name[]=”value”
Ex:
char str[]=”GOOD”

G O O D \0

Reading string from keyboard


scanf(“%s”,string_variable);
Ex:
scanf(“%s”,str);

gets() and puts() function


gets(): It is used to read a string from keyboard with space.
Syntax:
gets(string_variable);
Ex: gets(str)
puts(): It is used to print an entire string.
Syntax:
puts(string_variable);
Ex:
puts(str);

String handling functions


strcat(): It is used to join two strings together. It takes the following form:

strcat(string1,string2);
string1 & string2 are two strings. When the function is executed, string2 is appended to string1 and
string2 remain unchanged.
Example:
Assume that
string1=”Good” and string2=”Morning”
strcat(string1,string2) will result
string1=”GoodMorning” and string2=”Morning”
Prepared by A. Mandal
strcpy(): It is used to assign the content of a string variable into another string variable. It takes the
following form:
strcpy(string1,string2);
The above function assigns the content of string2 to string1. string2 remain unchanged.
Example:
Assume that
string1=”Good” and string2=”Morning”
strcpy(string1,string2) will result
string1=”Morning” and string2=”Morning”
strupr(): It converts entire string content into upper case. It takes the following form:

strupr(string1);
Example:
Assume that
string1=”Good”
strupr(string1) will result
string1=”GOOD”

strlwr(): It converts entire string content into lower case. It takes the following form:

strlwr(string1);
Example:
Assume that
string1=”GooD”
strlwr(string1) will result
string1=”good”

strrev(): It is used to reverse a string content. It takes the following form:

strrev(string1);
Example:
Assume that
string1=”Good”
strrev(string1) will result
string1=”dooG”

strlen(): It returns the number of characters present in a string. It takes the following form:

n=strlen(string1);
Here string1 is a string variable and n is an integer variable.
Example:
Assume that
string1=”Good”
n=strlen(string1);
The value of n will be 4.

strcmp(): It compares two strings. If the strings are equal it returns 0 or if first string is largest it
returns +ve value or if second string is largest it returns –ve value. Actually it returns the ASCII value
differences of first non matching character from first string to second string. It takes the following
form:

n=strcmp(string1,string2);
Prepared by A. Mandal
Example:
Assume that
string1=”Amit” and string2=”Amal”
n=strcmp(string1,string2)
The value of n will be 8.
Because the first non matching characters are ‘i’ and ‘a’. ASCII value of ‘i’ is 105 and ‘a’ is 97. So the
ASCII value difference is (105-97)=8

stricmp(): It works same as strcmp() but it ignores the case.

strncpy(): It copies only the leftmost n characters of the source string to target string variable.
It takes the following form:
strncpy(target_string, source_string, n);

strncmp(): It compares the leftmost n character of first string to second string.


It takes the following form:
strncmp(string1,string2,n);

strncat(): It concatenates leftmost n characters of string2 to the end of string1. It takes the
following form:

strncat(string1,string2,n);

strstr(): It is used to search a substring whether it is present or not in another string. It takes the
following form:

strstr(string1,string2);
It searches string1 to see whether string2 is present or not inside string1. If present then it returns
the position of the first occurrence of the string2 otherwise it returns null pointer.

strchr(): It is used to determine the existence of a character in a string. It returns the position of the
first occurrence of the character. It takes the following form:

strchr(string,character);

strrchr():It is used to determine the existence of a character in a string. It returns the position of the
last occurrence of the character. It takes the following form:
strrchr(string,character);
Prepared by A. Mandal
Pointer
A pointer is a derived data type in C. Pointer contains memory addresses as their values. It is used
to access and manipulate data stored in memory. On other hand we can say that the variable which
can store the address of another variable is called pointer variable.
Ex:
int *p;

Variable Value Address

a 179 5000

P (Pointer) 5000 5002

Advantages of using pointer


Pointers are frequently used in C, as they offer a number of benefits to the programmers. They
include:
4. Pointers are more efficient in handling arrays and data tables.
5. Pointers can be used to return multiple values from a function via function argument.
6. Use of pointer array to character string results in saving of data storage space in memory.
7. Pointer allows C to support dynamic memory allocation.
8. They increase the execution speed of a program.

Declaration of Pointer variables


The declaration of pointer variable takes the following form:
Data_taype *pointer_variable;
Ex:
int *ptr;
**The data type of pointer variable must be same with the data type of the variable being pointed.

Initialization of pointer variable


Once pointer variable has been declared we can use the assignment operator to initialize the
variable. Example:

int a=10;
int *p; // declaration of pointer variable
p=&a; // initialization of pointer variable
We can also combine the initialization as
int *p=&a;
** Note that p=address of variable a
*p= value of variable a
Prepared by A. Mandal
Programming example
Write a program to initialize an integer variable and a pointer variable. Display the value and
address of this integer variable using pointer variable.

#include<stdio.h>
#include<conio.h>
void main()
{
int a=10;
int *p;
p=&a;
clrscr();
printf(“\n The value of a is %d”,a);
printf(“\n The address of a is %u”,&a);
printf(“\n The value of a is %d”,*p);
printf(“\n The address of a is %u”,p);
getch();
}

Pointer to pointer or chain of pointer


When a pointer variable points another pointer variable then it is called pointer to pointer.

p2 p1 a
Address of p1 Address of a Value

Here p2 is pointer to pointer because p2 contains the address of another pointer variable p1.
We can declare a pointer to pointer variable using **.

Example: int **p2;

Programming Example

#include<stdio.h>
#include<conio.h>
void main()
{
int a=10, *p1, **p2;
clrscr();
p1=&a;
p2=&p1;
printf(“\n Value of a is %d”,**p2);
printf(“\n Address of a is %u”,*p2);
printf(“\n Address of p1 is %u”,p2);
getch();
}
Prepared by A. Mandal
Pointer increment and scale factor
When we increment a pointer, its value is increased by the length of the data type that it points to.
This length is called the scale factor.

Data types Scale factor (Bytes)


char 1
int 2
long int 3
float 4
double 8

Pointer and array


When an array is declared, the compiler allocates a base address and sufficient amount of storage
to contain all the elements of the array in contiguous memory locations. The compiler also defines
the array name as a constant pointer to the first element.
Write a program using pointer to compute the sum of all elements stored in an array.
#include<stdio.h>
#include<conio.h>
void main()
{
int a[20],n,sum=0,i;
int *p;
clrscr();
p=a; // p=&a[0];
printf(“\n Enter no. of array elements: “);
scanf(“%d”,&n);
printf(“\n Enter %d elements:”,n);
for(i=0;i<n;i++)
{
scanf(“%d”,(p+i));
sum=sum+*(p+i);
}
printf(“\n Sum=%d”,sum);
getch();
}

Pointer and String


We can create strings using pointer variables of type char. For example:

char *str=”GOOD”;
The pointer str now points to the first character of the string “GOOD” as:

G O O D \0

str
Prepared by A. Mandal
Programming Example
Write a program using pointer to find the length of a string.

#include<stdio.h>
#include<conio.h>
Void main()
{
char *str=”Delhi”;
int len;
char *ptr=str;
clrscr();
printf(“\n The string is: %s”,str);
while(*cptr!=’\0’)
{
ptr++;
}
len=ptr-str;
printf(“\n Length is: %d”,len);
getch();
}

D e l h i \0

str ptr

Array of pointers

Write a program to input 5 strings and display them using array of pointer.

#include<stdio.h>
#include<conio.h>
Void main()
{
char *str[5];
int i;
clrscr();
printf(“\n Enter 5 strings: “);
for(i=0;i<5;i++)
scanf(“%s”,str[i]);
printf(“\n The strings are:”);
for(i=0;i<5;i++)
printf(“\n%s”,str[i]);
getch();
}
Prepared by A. Mandal
Functions
A function is a self-contained block of code that performs a particular task. Once a function has
been defined, it can be treated as a ‘black box’ that takes some data from the main program and
returns a value.

Types of Function
There are two types of functions:
a) Built-in functions: Functions which are defined in C library and performs a predefined task is
called built-in or library functions. User can’t modify them. Ex: printf(), scanf() etc.
b) User defined functions: Functions which are defined by users and performs user defined
task is called user defined functions. User can modify those functions.

Need for user defined functions:


1. It facilitates top down modular programming. In this programming style, high level logic of
overall problem is solved first while the details of each lower level function are addressed
later.
2. The length of a source program can be reduced by using function at the appropriate places.
3. It is very easy to locate and isolate a faulty function for further investigation.
4. A function may be used by many other programs. This means that C programmer can built
on what others have already done, instead of starting all over again from scratch.

Elements of user defined function:


In order to make use of a user defined function, we need to establish three elements that are
related to function.
1. Function declaration: Like variables all functions in a C program must be declared before
they are invoked. It is also known as function prototype. It takes the following form:
Return_type function_name(Parameter_list);
Ex: int sum (int a, int b);

2. Function definition: The function definition is an independent program module that is


specially written to implement the requirements of the function. It is also known as function
implementation. It takes the following form;

Return_type function_name(Parameter_list)
{
//Body of the function
.
.
.
.
Return statement; //if required otherwise omitted
}
Ex:
int sum(int a, int b)
{
int c;
c=a+b;
return(c);
}
Prepared by A. Mandal
3. Function call: A function can be called by simply using the function name followed by a list
of actual parameter or arguments. It takes the following form:

If function returns a value then


Variable=function_name(actual_parameter);
Ex:
n=sum(10,20);
or
n=sum(a,b);

If function returns no value then


function_name(actual_parameter);
Ex:
sum(10,20);
or
sum(a,b);

Category of Functions:-
i) Functions with no arguments and no return values.
ii) Functions with arguments and no return values.
iii) Functions with no arguments but return a value.
iv) Functions with arguments and one return value.

A simple program with function (Function with no arguments and no return values):-

#include<stdio.h>
#include<conio.h>
void main()
{
clrscr();
void india(void); //Function prototype declaration
printf(\n Now I am in America \n”);
india(); //Function calling
printf(“\n Now I am in Kanada \n”);
india(); //Function calling
printf(“\n Now I am in Japan \n”);
india(); //Function calling
getch();
}
void india(void) //Function Definition
{
Printf(“\n Now I am in my country INDIA \n”);
}

Output:-

Now I am in America
Now I am in my country INDIA
Now I am in Kanada
Now I am in my country INDIA
Now I am in Japan
Now I am in my country INDIA
Prepared by A. Mandal
Function with no arguments and no return values:-

Addition of two number using Function:-

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

clrscr();
void add(); //Function prototype declaration
printf(“Addition Program \n\n “);
add(); //Function calling
getch();
}
void add() //Function Definition
{

int a=10, b=15, c;


c= a+b;
printf(“The addition result = %d ” , c);
}

Output:-

Addition Program

The addition result = 25

Functions with arguments and no return values.

Calculate area and perimeter of a circle using function:-

#include<stdio.h>
#include<conio.h>
#define P 3.14 //Global variable
void area(int r); //Function prototype declaration
void peri(int r); //Function prototype declaration
void main()
{

int x;
clrscr();
printf(“\n Enter radious : “);
scanf(“ %d “, &x);
area(x); //Function calling
peri(x); //Function calling
getch();
}
Prepared by A. Mandal
void area(int r) //Function Definition
{
float a;
a=P * r * r;
printf("\n\n The area = %.2f " , a);
}
void peri(int r) //Function Definition
{
float per;
per=2 * P * r;
printf("\n\n The perimeter = %.2f " , per);
}

Output:-

Enter radious: 3
The area = 28.26
The perimeter = 18.84

Functions with no arguments but return a value:-

Addition of two numbers using function:-

#include<stdio.h>
#include<conio.h>
int add(); //Function prototype declaration
void main()
{
int x;
clrscr();
x=add(); //Function calling
printf("\n\n The addition result = %d" , x);
getch();
}

int add() //Function Definition


{
int a=10,b=15,c;
c=a+b;
return(c);
}

Output:-

The addition result = 25


Prepared by A. Mandal
Functions with arguments and one return value.

Find the area of circles whose radious are 3 unit, 4 unit and 7 unit using function.

#include<stdio.h>
#include<conio.h>
#define P 3.14 // Global constant
float area( int r); //Function prototype declaration

void main()
{
float a;
clrscr();
a=area(3); //Function calling
printf("\n\n The area = %.2f ", a);
a=area(4); //Function calling
printf("\n\n The area = %.2f ", a);
a=area(7); //Function calling
printf("\n\n The area = %.2f ", a);
getch();
}

float area(int r) //Function Definition


{
float x;
x=P*r*r;
return(x);
}

Output:-

The area = 28.26

The area = 50.24

The area = 153.86


Prepared by A. Mandal
***Recursive Function:-

Defn:-
A function is called ‘recursive‘ if a statement within a body of this function calls the same
function. This is known as recursion.

Find the factorial of a number using recursive function:-

#include<stdio.h>
#include<conio.h>
int fact(int n); //Function prototype declaration
void main()
{
int n, f;
clrscr();
printf("\n\n Enter a number: ");
scanf("%d" , &n);
f=fact(n); //Function calling
printf("\n\n The factorial = %d", f);
getch();
}

int fact(int n) //Function Definition


{
int ft;
if(n==1||n==0)
{
return(1);
}
else
{
ft=n*fact(n-1);
}
return(ft);
}

Output:-

Enter a number: 5

The factorial = 120


Prepared by A. Mandal
***Write a program to calculate HCF of two numbers using recursive function.
#include<stdio.h>
#include<conio.h>
int hcf(int n1, int n2);
void main()
{
int n1, n2,h;
clrscr();
printf("Enter two positive integers: ");
scanf("%d%d", &n1, &n2);
h=hcf(n1,n2);
printf("H.C.F of %d and %d = %d", n1, n2,h);
getch();
}
int hcf(int n1, int n2)
{
if (n2!=0)
return hcf(n2, n1%n2);
else
return n1;
}

*** Calculate nth Fibonacci number using recursion.

#include <stdio.h>
#include<conio.h>
int fibo(int);

void main()
{
int num;
int result;

printf("Enter the nth number in fibonacci series: ");


scanf("%d", &num);
result = fibo(num);
printf("The %d number in fibonacci series is %d\n", num, result);
getch();
}

int fibo(int num)


{
if (num == 0)
{
return 0;
}
else if (num == 1)
{
return 1;
}
else
{
return(fibo(num - 1) + fibo(num - 2));
Prepared by A. Mandal
}
}

Actual & Formal Parameter:


Parameters used in the function call are known as actual parameters.
Ex: c=add(a,b); //function call
Here a and b are actual parameters.

Parameters used in function definition are known as formal parameters.


Ex: int add(int p, int q) //function definition
{
int c;
c=p+q;
return (c);
}
Here p and q are formal parameters.

Local Variables
 Local variables scope is confined within the block or function where it is defined. Local
variables must always be defined at the top of a block.
 When a local variable is defined - it is not initialized by the system, you must initialize it
yourself.
 When execution of the block starts the variable is available, and when the block ends the
variable 'dies'.
Global Variables
 Global variable is defined at the top of the program file and it can be visible and modified by
any function that may reference it.
 Global variables are initialized automatically by the system when you define them!
 If same variable name is being used for global and local variable then local variable takes
preference in its scope. But it is not a good practice to use global variables and local
variables with the same name.

Data Type Default Value


int 0
char '\0'
float 0
pointer NULL

Block:
A set of statements enclosed in a set of braces is known as a block. A block can have its own
declarations and other statements.

void main()
{ //outer block
int a=20;
…………
{ //inner block
int b=10;
…………..
}
}
Prepared by A. Mandal
Passing one dimensional array to a function
Rules:
1. The function must be called by passing only the name of the array.
2. In the function definition, the formal parameter must be an array type; the size of the array
does not need to be specified.
3. The function prototype must show that the argument is an array.

Write a program to input some integer elements and sort them into ascending order using function.

#include<stdio.h>
#include<conio.h>
void sort(int a[], int n)
{
int t, i, j;
for(i=0;i<n;i++)
{
for(j=i+1;j<n;j++)
{
if(a[j]<a[i])
{
t=a[i];
a[i]=a[j];
a[j]=t;
}
}
}
Printf(“\n After sorting:”);
for(i=0;i<n;i++)
printf(“\n %d”,a[i]);
}
void main()
{
int x[20],i,n;
clrscr();
printf(“\n Enter the number of elements: “);
scanf(“%d”,&n);
printf(“\n Enter the %d elements: “,n);
for(i=0;i<n;i++)
scanf(“%d”,&x[i]);
sort(x, n);
getch();
}

Passing two dimensional array to a function


Rules:
1. The function must be called by passing only the name of the array.
2. In function definition we must indicate that the array has two dimensions by including two
sets of brackets.
3. The size of second dimension must be specified.
4. The prototype declaration should be similar to the function header.
Prepared by A. Mandal
Write a program to find sum and average of all elements of a matrix.

#include<stdio.h>
#include<conio.h>
int sum(int a[][10], int m, int n)
{
int s=0, i, j;
for(i=0;i<m;i++)
{
for(j=0;j<n;j++)
{
s=s+a[i][j];
}
}
return(s);
}

float average(int a[][10], int m, int n)


{
float avg;
avg=sum(a,m,n)/(float)(m*n);
return(avg);
}

void main()
{
int x[10][10], i, j, r, c,p;
float q;
clrscr();
printf(“\n Enter order of the matrix: “);
scanf(“%d%d”,&r,&c);
printf(“\n Enter %d elements: “,r*c);
for(i=0;i<r;i++)
for(j=0;j<c;j++)
scanf(“%d”,&a[i][j]);
p=sum(x,r,c);
q=average(x,r,c);
printf(“\n Sum=%d and Average=%d”,p,q);
getch();
}

Call by value
Whenever we called a function and passed the values of variables as its argument this is known as
Call by Value. In this case if we change the value of formal parameters then actual parameter
remain unchanged.

Ex:
Write a program using function to swap the value of two variables.
Prepared by A. Mandal
#include<stdio.h>
#include<conio.h>
void swapv(int a, int b)
{
int c;
c=a;
a=b;
b=c;
printf(“\n In sub function a=%d and b=%d”,a,b);
}
void main()
{
int a=10, b=20;
clrscr();
swapv(a,b);
printf(“\n In main function a=%d and b=%d”,a,b);
getch();
}

Output:
In sub function a=20 and b=10
In main function a=10 and b=20

Call by reference
When we called a function if we pass the address of a variable as its argument this is known as Call
by reference. In this case if we change the value of formal parameters then the value of actual
parameters will be changed.

Ex:
Write a program using function to swap the value of two variables.
#include<stdio.h>
#include<conio.h>
void swapr(int *a, int *b)
{
int c;
c=*a;
*a=*b;
*b=c;
printf(“\n In sub function a=%d and b=%d”,*a,*b);
}
void main()
{
int a=10, b=20;
clrscr();
swapr(&a,&b);
printf(“\n In main function a=%d and b=%d”,a,b);
getch();
}
Output:
In sub function a=20 and b=10
In main function a=20 and b=10
Prepared by A. Mandal
Function returning pointer
Write a program to find the largest between two numbers.

#include<stdio.h>
#include<conio.h>
int *large(int *a, int *b)
{
If(*x>*y)
return(x);
else
return(y);
}

void main()
{
int a=20, b=10;
int *p;
clrscr();
p=large(&a,&b);
printf(“\n Largest number is %d”,*p);
getch();
}

Pointer to a function or function pointer


Declaration
Return_type (*pointer_name)(type of arguments);
Exalple:
float (*ptr)(float,float);
Initialization
Pointer_name=function_name;
Exalple:
ptr=mult
Here mult is the function name.

Ex:
#include<stdio.h>
#include<conio.h>
float mult(float a,float b)
{
return (a*b);
}
void main()
{
float (*ptr)(float,float); //function pointer declaration
float x;
clrscr();
ptr=mult; //initialization of pointer
x=(*ptr)(3,5); //function call using pointer
printf("\n Multiplication result is %f",x);
getch();
}
Prepared by A. Mandal
Storage Class
A storage class tells us:
i) Where the variables would be stored.
ii) What will be the initial value of the variable, if initial value is not specifically assigned.
iii) What is the scope of the variable; i.e. in which functions the value of the variable would be
available.
iv) What is the life of the variable; i.e. how long would the variable exist.

There are four types of storage classes available in C:


i) Automatic storage class
ii) External storage class
iii) Register storage class
iv) Static storage class

Automatic storage class


Automatic variables are defined inside a function in which they are to be utilized. They are created
when the function is called and destroyed automatically when the function is exited. Automatic
variables are local to the block in which they are declared. A variable declared inside a function
without storage class specification is by default automatic. It is declared using ‘auto’ keyword.

Storage Memory

Default initial value Garbage value

Scope Local to the block in which it is defined.

Life Till the control remains within the block in


which it is defined.

Example:

#include<stdio.h>
#include<conio.h>
void main()
{
auto int x=10;
clrscr();
printf(“x=%d”,x);
getch();
}

O/P
x=10
Prepared by A. Mandal
External storage class
The variable that are both alive and active throughout the program are known as external variables.
They are also known as global variables. They can be accessed by any function in the program. It is
declared using ‘extern’ keyword explicitly.

Storage Memory

Default initial value Zero

Scope Global

Life As long as program’s execution does not


come to an end.

Example:

#include<stdio.h>
#include<conio.h>
int i=0; //Global variable

void incr()
{
i++;
printf(“\n %d”,i);
}

void decr()
{
i- -;
printf(“\n %d”,i);
}
void main()
{
clrscr();
incr();
incr();
decr();
decr();
getch();
}

O/P
1
2
1
0
Prepared by A. Mandal
Using extern keyword

#include<stdio.h>
#include<conio.h>
void main()
{
extern int y;
clrscr();
printf(“\n y=%d”,y);
getch();
}
int y=20;

O/P
y=20

Register storage class


Using this storage class we can store a variable in one of the machine’s register instead of keeping it
into the memory. Since the register access is fast than a memory access, keeping the frequently
accessed variables in the register will lead to faster execution of programs. We can declare this
using ‘register’ keyword.

Storage Register

Default initial value Garbage value

Scope Local to the block in which it is defined.

Life Till the control remains within the block in


which it is defined.
Example:
#include<stdio.h>
#include<conio.h>
void main()
{
register int i;
for(i=1;i<=10;i++)
printf(“\n %d’,i);
getch();
}

O/P
1
2
3
4
5
6
7
8
9
10
Prepared by A. Mandal
Static storage class
As the name suggests, the value of static variables persists until the end of the program. A ststic
variable is declared using ‘static’ keyword.

Storage Memory

Default initial value Zero

Scope Local to the block in which it is defined.

Life Value of the variable persists between


different function call.

Example

#include<stdio.h> #include<stdio.h>
#include<conio.h> #include<conio.h>
void incr() void incr()
{ {
int i=0; static int i=0;
i++; i++;
printf(“\n %d”,i); printf(“\n %d”,i);
} }
void main() void main()
{ {
clrscr(); clrscr();
incr(); incr();
incr(); incr();
incr(); incr();
getch(); getch();
} }

O/P O/P
1 1
1 2
1 3
Prepared by A. Mandal
Structure & Union

Structure
Structure is a user defined data type which allows to combine data items of different kinds. It is a
convenient tool for handling a group of logically related data items. For example, it can be used to
represent a set of attributes such as student_name, roll and marks.

Defining a structure
The general format of a structure definition is:

struct tag_name
{
data_type member1;
data_type member2;
………………………
………………………
……………………..
};

Example:

struct student
{
char name[20];
int roll;
float marks;
};
Declaration of structure variable

struct student
{
char name[20];
int roll;
float marks;
}s1,s2;
OR

struct student
{
char name[20];
int roll;
float marks;
};

struct student s1,s2;


Prepared by A. Mandal
Initialization of structure variable

struct student
{
char name[20];
int roll;
float marks;
} s1={“Amal”,1,92.0},s2={“Ajit”,2,88.0};

OR

struct student
{
char name[20];
int roll;
float marks;
};

struct student s1={“Amal”,1,92.0};


struct student s2={“Ajit”,2,88.0};

Accessing structure member


The general syntax for accessing structure member is:
Structure_variable_name.member_variable_name

Example:

struct student
{
char name[20];
int roll;
float marks;
}s1,s2;

s1.name //Accessing structure member

Copying and Comparing structure variables


Two variables of the same structure type can be copied the same way as ordinary variables. If
person1 and person2 belong to the same structure, then the following statement is valid:

person1=person2;

However the statements such as

person1==person2
person1!=person2
are not permitted. We can compare structure members individually.
Prepared by A. Mandal
***Write a program to create a structure called “book” which contains book title, author, pages
and price. Take details of two books and display the details.

#include<stdio.h>
#include<conio.h>

struct book
{
chat btitle[15];
char author[20];
int page;
float price;
};
void main()
{
struct book b1={“ANSI C”,”E Balagurusamy”,600,325.0};
struct book b2={“Let Us C”,”Y Kanitkar”,650,350.0};
clrscr();
printf(“\n Book Name: %s Author: %s Pages: %d Price: %.2f”,b1.btitle,b1.author,b1.page,b1.price”);
printf(“\n Book Name: %s Author: %s Pages: %d Price: %.2f”,b2.btitle,b2.author,b2.page,b2.price”);
getch();
}

O/P
Book Name: ANSI C Author: E Balagurusamy Pags: 600 Price: 325.00
Book Name: Let Us C Author: Y Kanitkar Pags: 650 Price: 350.00

Structure within structure


*** Write a program to create a structure called address which contains Village, Post and PS.
Then create another structure called employee which contains name, address and salary. Take
details of an employee and print the details.

#include<stdio.h>
#include<conio.h>
struct address
{
char vill[15];
char po[15];
char ps[15];
};

struct employee
{
char name[20];
struct address add;
float sal;
};
Prepared by A. Mandal
void main()
{
struct employee emp;
clrscr();
printf(“\n Enter name of an employee: “);
scanf(“%s”, emp.name);
printf(“\n Enter village, post and ps: “);
scanf(“%s%s%s”, emp.add.vill,emp.add.po,emp.add.ps);
printf(“\n Enter salary: “);
scanf(“%f”, &emp.sal);
printf(“\n Name: %s”,emp.name);
printf(“\n Vill: %s PO: %s PS: %s”,emp.add.vill,emp.add.po,emp.add.ps);
printf(“\n Salary: %.2f”, emp.sal);
getch();
}

Array of structure
*** Write a program to create a structure called Student which contains name, roll and marks.
Take the details of n students and arrange them according to their marks from highest to lowest.

#include<stdio.h>
#include<conio.h>

struct student
{
char name[20];
int roll;
float marks;
};

void main()
{
struct student s[50];
struct student temp;
int n, i, j;
clrscr();
printf(“\n How many students? “);
scanf(“%d”,&n);
for(i=0;i<n;i++)
{
printf(“\n Enter name, roll and marks of student %d”,(i+1));
scanf(“%s%d%f”,s[i].name,&s[i].roll,&s[i].marks);
}

for(i=0;i<n;i++)
{
for(j=i+1;j<n;j++)
{
if(s[j].marks>s[i].marks)
{
temp=s[i];
s[i]=s[j];
s[j]=temp;
Prepared by A. Mandal
}
}
}

printf(“\n Name Roll Marks”);


for(i=0;i<n;i++)
printf(“\n %s %d %.2f”,s[i].name,s[i].roll,s[i].marks);

getch();
}

Structure pointer
***Write a program to create a structure called “book” which contains book title, author, pages
and price. Take details of two books and display the details using structure pointer.

#include<stdio.h>
#include<conio.h>

struct book
{
chat btitle[15];
char author[20];
int page;
float price;
};
void main()
{
struct book *b1;
clrscr();
printf(“\n Enter book name, author, pages and price: “);
scanf(“%s%s%d%f”, b1->btitle, b1->author,&b1->page,&b1->price);

printf(“\n Book Name: %s Author: %s Pages: %d Price: %.2f”,b1->btitle,


b1->author,b1->page,b1->price);
getch();
}

O/P
Enter book name, author, pages and price: Let_Us_C Y_Kanitkar 650 350

Book Name: Let_Us_C Author: Y_Kanitkar Pags: 650 Price: 350.00


Prepared by A. Mandal
Union
A union is a special data type available in C that enables you to store different data types in the
same memory location. We can define a union with many members, but only one member can
contain a value at any given time. Unions provide an efficient way of using the same memory
location for multi-purpose.

Example

#include<stdio.h>
#include<conio.h>

union student
{
char name[20];
int roll;
float marks;
};

void main()
{
union student st;
clrscr();
printf(“\n Enter student name: “);
scanf(“%s”,st.name);
printf(“\n Name is: %s”,st.name);
printf(“\n Enter roll: “);
scanf(“%d”,&st.roll);
printf(“\n Roll is: %d”,st.roll);
printf(“\n Enter mark: “);
scanf(“%f”,&st.marks);
printf(“\n Mark is: %.2f”,st.marks);
getch();
}

O/P

Enter student name: Amal


Name is: Amal
Enter roll: 10
Roll is: 10
Enter mark: 87
Mark is: 87.00
Prepared by A. Mandal
Difference between structure and union

i) Structure is defined using keyword struct. On the other hand union is defined using
keyword union.
ii) The amount of memory required to store a structure variable is the sum of the size of all
the members.
On the other hand, in case of unions, the amount of memory required is always equal to
that required by its largest member.
iii) In case of structure, each member has their own memory space but In union, one block
is used by all the member of the union.

Difference between structure and array

i) An array is a collection of related data elements of same type. But Structure can have
elements of different types.
ii) An array is a derived data type. But A structure is a user-defined data type.
iii) Any array behaves like a built-in data types. All we have to do is to declare an array
variable and use it. But in the case of structure, first we have to design and declare a
data structure before the variable of that type are declared and used.
Prepared by A. Mandal
DYNAMIC MEMORY ALLOCATION:
The process of allocating memory at run time is known as dynamic memory. There
are four library routines known as “memory management functions” that can be used for allocating
and freeing memory during program executions.
MEMORY ALLOCATION FUNCTIONS
Function Task
malloc Allocates request size of bytes and returns a pointer to the first byte of the
allocated space.
calloc Allocates space for an array of elements,initializes them to zero then returns a
pointer to the memory.
Free Frees previously allocated space.
Realloc Modifies the size of previously allocated space.

ALLOCATING A BLOCK OF MEMORY : MALLOC


A block of memory may be allocated using the function malloc. The malloc function
reserves a block 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 *) malloac(byte-size);
ptr is a pointer of type cast-type. The malloc returns a pointer (of cast-type) to an area of memory
with size byte-size.
Example:
x= (int *) malloc (100 *sizeof(int));

ALLOCATING MULTIPLE BLOCKS OF MEMORY : CALLOC


calloc is another memory allocation function that is normally used for requesting
memory space at run time for storing derived data types such as arrays and structures. While
malloc allocates a single block of storage space, calloc allocates multiple blocks of storage, each of
the same size, and then sets all bytes to zero. The general formof calloc is:
ptr= (cast-type *) calloc (n,elem-size);

The above statements allocates contiguous space for n blocks, each of size elem-size bytes. All
bytes are initialized to zero and a pointer to the first byte of the allocated region is returned. If
there is not enough space, a null pointer is returned.
Example
. . . . .
. . . . .
struct student
{
char name[30];
float age;
longintid_num;
};
typedefstruct student record;
record *st_ptr;
intclass_size=30;
st_ptr=(record *)calloc(class_size, sizeof(record));
. . . . .
. . . . .
Prepared by A. Mandal
RELEASING THE USED SPACE : FREE
When we no longer need the data we stored in a block of memory, and we do not
intend to use that block for storing any other information, we may release that block of memory for
future use, using the free function.
free(ptr);

ALTERING THE SIZE OF A BLOCK: REALLOC


We can change the memory size already allocated with the help of the function
realloc. This process is called the reallocation of memory.
ptr=malloc(size);
Then reallocation of space may be done by the statement
ptr=realloc(ptr, newsize);

Example: write a program to store a character string in a block of memory space created by
malloc and then modify the same to store a larger string.
Ans : #include<stdio.h>
#include<stdlib.h>
#define null 0
main()
{
char *buffer;
/*Allocating memory*/
if(buffer= (char *)malloc(10)==NULL)
{
printf(“malloc failed.\n”);
exit(1);
}
printf(“Buffer of size %d created \n”,_msize(buffer));
strcpy(buffer,“HYDRABAD”);
printf(“\nBuffer contain:%s\n”,buffer);
/*Reallocation*/
if(buffer=(char *)realloc(buffer, 15)==NULL)
{
printf(“Reallocation failed. \n”);
exit(1);
}
printf(“\nBuffer size modified. \n”);
printf(“\nBuffer still contain: %s \n”,buffer);
strcpy(buffer, “SECUNDERABAD”);
printf(“\nBuffer now contains:%s \n”,buffer);
/*FREE MEMORY*/
free(buffer);
}
OUTPUT:
Buffer of size 10 created
Buffer contain: HYDERABAD
Buffer size modified
Buffer still contains: HYDERABAD
Buffer now contains: SECUNDERABAD
Prepared by A. Mandal
LINKED LISTS:
A completely different way to represent a list is to make each item in the list part of
a structure that also contains a “link” to the structure containing the next item. This type of list is
called a linked list because it is a list whose order is given by links form one item to the next.
Structure 1 structure 2 structure 3
item item item

ADVANTAGES OF LINKED LIST:


1. A linked list is dynamic data structure. Therefore, the primary advantage of
linked lists over arrays is that linked lists can grow or shrink in size during the
execution of a program. A linked list can be made just as long as required.
2. Another advantage is that a linked list does not waste memory space. It uses the
memory that is just needed for the list at any point of time. This is because it is
not necessary to specify the number of nodes to be used in the list.
3. The third and the most important advantage is that the linked list provide
flexibility is allowing the items to be rearranged efficiently. It is easier to insert
delete items by rearranging the links.
Prepared by A. Mandal
File Management in C
File
A file is a place on the disk where group of related data is stored. C supports a number of functions
that have the ability to perform basic file operation such as naming a file, opening a file etc.

File handling functions:-


Function Name Operation
fopen() Creates a new file for use or opens an existing file for use.
fclose() Closes a file which has been opened for use.
getc() Reads a character from a file.
putc() Writes a character to a file.
fprintf() Writes a set of data values to a file.
fscanf() Reads a set of data values from a file.
getw() Reads an integer from a file.
putw() Writes an integer to a file.
fseek() Sets the position to a desired point in the file.
ftell() Gives the current position in the file(in terms of bytes from the start()
rewind() Sets the position to the beginning of the file.

EOF End of File


BOF Beginning of File
File Modes:-

mode Description

"r" Opens a file for reading. The file must exist.

"w" Creates an empty file for writing. If a file with the same name already
exists, its content is erased and the file is considered as a new empty file.

"a" Appends to a file. Writing operations, append data at the end of the file.
The file is created if it does not exist.

"r+" Opens a file to update both reading and writing. The file must exist.

"w+" Creates an empty file for both reading and writing.

"a+" Opens a file for reading and appending.


Prepared by A. Mandal
Syntax for opening a file:-
FILE *fp;
fp=fopen(“filename”, ”mode”);

Here fp is a “pointer to the data type FILE”. FILE is a structure that is defined in the I/O library.

Example:-
FILE *f1;
f1=fopen(“Data.txt” , ”r”);
Syntax for closing a file:-
fclose(file_pointer);

Example:-
FILE *f1;
f1=fopen(“Data.txt”, “r”);
…………………..
fclose(f1);

Syntax of getc() :-
c=getc(fp);
Here c is a character type variable and fp is file pointer.

Syntax of putc() :-
putc(c , fp);

Here c is a character type variable and fp is a file pointer.

Syntax of getw() :-
n=getw(fp);
Here n is an integer type variable and fp is file pointer.

Syntax of putw() :-
putw(n , fp);
Here n is an integer type variable and fp is file pointer.
Prepared by A. Mandal
Sample Programs:-
******Write a C program to input some integer numbers to a file and display the numbers from
this file.

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

FILE *fp;
int number, i;
clrscr();
printf(“\n\n Enter numbers \n\n “);
fp=fopen(“data.txt” , “w”);
for(i=1, i<=30, i++)
{
scanf(“%d”, &number);
if(number == -1) break;
putw(number,fp);
}
fclose(fp);
fp=fopen("data.txt" , "r");
printf("\n\n The content of this file is:\n\n ");
while((number=getw(fp))!=EOF)
{
printf("%d ",number);
}
fclose(fp);
getch();
}

******Write a C program to input some characters to a file and display these characters from this
file.

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

FILE *f1;
char ch;
clrscr();
printf(“\n\n Enter text \n\n “);
f1=fopen(“text.txt” , “w”);
while((ch=getchar())!=EOF)
{

putc(ch,f1);
}
fclose(f1);
f1=fopen("text.txt" , "r");
Prepared by A. Mandal
printf("\n\n The content of this file is:\n\n ");
while((ch=getc(f1))!=EOF)
{
printf("%c ",ch);
}
fclose(f1);
getch();
}

The fpritnf and fscanf Function:


The general form of fprintf is-
fprintf(fp,”control string”,list);
The general format of fscanf is-
fscanf(fp,”control string”,list);
Example:
Write a program to open a file named INVENTORY and store in it the following data:
ITEM NAME NUMBER PRICE QUANTITY
AAA-1 111 17.50 115
BBB-2 125 36.00 75
C-3 247 31.75 104
Extend the program to read this data from the file INVENTORY and display the inventory table with the value
of each item.
Program:
#include<stdio.h>
main();
{
FILE *fp;
int number, quantity, i;
float price, value;
char item[10], filename[10];
printf(“Input file name\n”);
scanf(“%s”, filename);
fp=fopen(filename,”W”);
printf(“Input inventory data\n\n”);
printf(“Item name number price quantity\n”);
for(i=0;i<=3;i++)
{
fscanf(stdin,”%s %d %f %d”, item,&number,&price,&quantity);
fprintf(fp,”%s %d %.2f %d”, item, number, price, quantity);
}
fclose(fp);
fprintf(stdout,”\n\n”);
fp= fopen(filename,”r”);
printf(“Item name Number Price Quantity value\n ”);
for(i=1;i<=3;i++)
{
fscanf(fp,”%s %d %f %d”,item, &number, &price, &quantity);
value=price*quantity;
fprintf(stdout,”%-8s %7d %8.2f %11.2f\n”, item, number, price, quantity, value);
}
fclose(fp);
}
Prepared by A. Mandal
Output:
Input file name
INVENTORY
Input inventory data
Item name Number Price Quantity
AAA-1 111 17.50 115
BBB-2 125 36.00 75
C-3 247 31.75 104

Item name Number Price Quantity Value


AAA-1 111 17.50 115 2012.50
BBB-2 125 36.00 75 2700.00
C-3 247 31.75 104 3302.00

ERROR HANDLING DURING I/O OPERATIONS:


The feof function can be used to test for and end of file condition. It takes a FILE pointer as
its only argument and returns a nonzero integer value if all of the data from the specified file has been read,
and returns zero otherwise.
if(feof(fp))
printf(“End of data.\n”);
The ferror function reports the status of the file indicated. It also takes a FILE pointer as its
argument and returns a nonzero integer if an error has been detected up to that point, during processing.
It returns zero otherwise. The statement
if(ferror(fp)!=0)
printf(“An error has occurred.\n”);
would print the error massage, if the reading is not successful.
We know that whenever a file is opened using fopenfunction, a file pointer is returned. If the
file is not opened for some reason, then the function returns a NULL pointer. This facility can be used to test
whether a file has been opened or not. Example:
if(fp==NULL)
printf(“File could not be opened.\n”);
EXAMPLE:
Write a program to illustrate error handling in file operation.
Program:
#include<stdio.h>
main()
{
char *filename;
FILE *fp1, *fp2;
inti, number;
fp1= fopen(“TEST”, “W”);
for(i=o;i<=100;i+=10)
putw(I, fp1);
fclose(fp1);
printf(“\nInput file name\n”);
Open_file:
scanf(“%s”,filename);
if((fp2== fope(filename,”r”))==NULL)
{
printf(“Cannot open the file.\n”);
printf(“Type filename again.\n\n”);
Gotoopen_file;
}
else
{
for(i=1;i<=20;i++)
{
Prepared by A. Mandal
number=getw(fp2);
if(feof(fp2))
{
printf(“\nRan out of data.\n”);
break;
}
else
printf(“%d\n”,number);
}
fclose(fp2);
}

OUTPUT:
Input filename
TETS
Cannot open the file.
Type filename again.
TEST
10
20
30
40
50
60
70
80
90
100
Ran out of data.

RANDOM ACCESS TO FILES:


ftell takes a file pointer and return a number of type long, that corresponds
to the current position. This function is useful in saving the current position of a file, which can be used later
in the program. It takes the following form:
n= ftell(fp);
n would give the relative offset (in bytes) of the current position. This mean that n bytes have already been
read (or written).
rewind takes a file pointer and resets the position to the start of the file. For
example, the statements
rewind(fp);
n = ftell (fp);
fseekfunction is used to move the file position to a desired location within the file. It
takes the following form:
fseek(file_ptr, offset, position);

OPERATION OF fseek FUNCTION

Statements Meaning
fseek(fp,0L,0); Go to the beginning. (Similar to rewind)
fseek(fp,0L,1); Stay at the current position. (Rarely used)
fseek(fp,0L,2); Go to the end of the file, past the last character of the file.
fseek(fp,m,0); Move to (m+1)th byte in the file.
fseek(fp,m,0); Go forward by m bytes.
fseek(fp,m,0); Go backward by m bytes from the current position.
fseek(fp,m,0); Go backward by m bytes from the end. (Positions the file to the mth
character from the end.)
Prepared by A. Mandal
EXAMPLE: Write a program that uses the functions ftell and fseek.
A program employing ftell and fseek functions is shown in below. We have created a file RANDOM with
the following contents:
Position 0 1 2 …..25
Chrecter stored A B C …..Z
Program:
#include<stdio.h>
main()
{
FILE *fp;
long n;
char c;
fp = fopen(“RANDOM”,”w”);
while((c=getchar())!= EOF)
putc(c,fp);
printf(“No. of charecters entered = %ld\n”, ftell(fp));
fclose(fp);
fp = fopen(“RANDOM”,”r”);
n=0L;
while(feof(fp)==0)
{
fseek(fp,n,0); /*Position to (n+1)th character */
printf(“Position of %c is %ld\n”,getc(fp),ftell);
n=n+5L;
}
putchar(‘\n’);
fseek(fp,-1L,2); /*Position to the last character */
do
{
putchar(getc(fp));
}
while(!fseek(fp,-2L,1));
fclose(fp);
}
OUTPUT:
ABCDEFGHIJKLMNOPQRSTUVWXY^Z
No. of characters entered = 26
Position of A is 0
Position of F is 5
Position of K is 10
Position of P is 15
Position of U is 20
Position of Z is 25
Position of is 30
ZYXWVUTSRQPONMLKJIHGFEDCBA
Prepared by A. Mandal
Command Line Arguments
It is a parameter supplied to a program when the program is invoked. In fact main function can take
two arguments called argc and argv and the information contained in the command line is passed
onto the program through these arguments, when main is called up by the system.

The argument argc is an argument counter that counts the number of arguments on the command
line. The argument argv is an argument vector that stores the supplied arguments.

In order to access the command line arguments, we must declare the main function and its
parameter as follows:

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


{
……………….

……………….

……………….
}

Example:

Consider the following command in command line:


C:\>copyfile x_file y_file

Here
argc=3
argv[0]=copyfile
argv[1]=x_file
argv[2]=y_file

*** Write a program to copy the content of one file into another file using command line
arguments.

// File name copyfile.c

#include<stdio.h>
#include<conio.h>
#include<stdlib.h>
void main(int argc, char argv[])
{
FILE *fs, *ft;
Char ch;
If(argc!=3)
{
printf(“\n Improper number of arguments”);
exit(1);
}
fs=fopen(argv[1],”r”);
if(fs==NULL)
{
printf(“\n Cannot open source file”);
exit(2);
Prepared by A. Mandal
}
ft=fopen(argv[2],”w”);
if(ft==NULL)
{
printf(“\n Cannot open target file”);
exit(3);
}
while((ch=getchar())!=EOF)
{

putc(ch,ft);
}
fclose(fs);
fclose(ft);
}

The Preprocessor

The C Preprocessor is not a part of the compiler, but is a separate step in the compilation process.
In simple terms, a C Preprocessor is just a text substitution tool and it instructs the compiler to do
required pre-processing before the actual compilation. We'll refer to the C Preprocessor as CPP.

All preprocessor commands begin with a hash symbol (#). It must be the first nonblank character,
and for readability, a preprocessor directive should begin in the first column. The following section
lists down all the important preprocessor directives −
Directive Description

#define Substitutes a preprocessor macro.

#include Inserts a particular header from another file.

#undef Undefines a preprocessor macro.

#ifdef Returns true if this macro is defined.

#ifndef Returns true if this macro is not defined.

#if Tests if a compile time condition is true.

#else The alternative for #if.

#elif #else and #if in one statement.

#endif Ends preprocessor conditional.

#error Prints error message on stderr.

#pragma Issues special commands to the compiler, using a standardized method.


Prepared by A. Mandal
Macro
Macro substitution is a process where an identifier in a program is replaced by a predefined string
composed of one or more tokens. The preprocessor accomplishes this task under the direction of
the #define statement. This statement, usually known as macro definition takes the following
general form:

#define identifier value

If this statement is included in the program at the beginning, then the preprocessor replaces every
occurrence of the identifier in the source code by the value.

Example:

#define COUNT 100

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy