Ansi c Programming Concept (2)
Ansi c Programming Concept (2)
V
4.3 Part of user-Defined Function 72
4.4 Function Returning Nothing 74
4.5 Function Calls 75
4.6 Functions Category 76
4.7 Recursion 82
4.8 Passing Arrays to Function 86
4.9 Pass two-Dimensional Array to a Function 88
4.10 Scope of the variables 89
4.11 Structures 96
4.12 Accessing structure Members 101
4.13 Coping and Comparing Structure Variables 103
4.14 Arras of Structures 104
4.15 Memory Allocation Structure Format 105
4.16 Nested Structures 106
4.17 Structures and Function 108
4.18 Unions 110
VI
ANSI C PROGRAMMING CONCEPT
1.1 INTRODUCTION TO C:
C is a popular general purpose, high-level programming language
that was originally developed by Dennis M. Ritchie to develop the
UNIX operating system at Bell Labs. C was orininally first
implemented on the DEC PDP-11 computer in 1972.
The UNIX operating system and virtually all Unix applications are
written in the C language. C has now become a widely used
professional language for various reasons.
The history and development of C is illustrated.
R. SIVARASAN 1
ANSI C PROGRAMMING CONCEPT
ANSI C STANDARD:
For many years there was no standard version of „C‟ language. Due
to this reason, portability feature of „C‟ language was not provided from
one computer to another computer. To overcome this discrepancy a
committee was set up in the summer of 1983 to create a standard C version
tha is popularly known a ANSI(American National standard Institute)
STANDARD. The ANSI C standard was adopted in December of 1989
and the first copy of c language was introduced in the market in 1990.
Today all compilers of C support to ANSI standard.
a) Interpreters
An Interpreter reads only one line of a source program at a time
and converts it to object codes. In case of any errors, the same will
be indicated instantly.
The program written with an interpreter can easily be read and
understood by the other users as well. So security is not provided.
Anyone can modify the source code.
Hence it is easier than compilers. But the disadvantage is that it
consumes more time for converting a source program to an object
program.
b) Compilers
A compiler reads the entire program and converts it to the object
code.
It provides errors not of one line but errors of the entire program.
Only error free programs are executed. It consumes little time for
converting a source program to an object program.
R. SIVARASAN 2
ANSI C PROGRAMMING CONCEPT
R. SIVARASAN 3
ANSI C PROGRAMMING CONCEPT
In this example <stdio.h> file is included i.e. all the definitions and prototypes
of function defined £je are available in the current program. This file is
also compiled with original program.
Global Declaration:
This section declares some variables that are used in more than
one function. these variable are known as global variables. These variables
must be declared outside of all the
Function Main:
Every program written in С language must contain main ()
function. Empty – parenthesis after main are necessary. The function
main () is the starting point of every 'C' program. Mi: n of the program
always begins with the function main (). Except the main () function,
other sections may not be necessary. The program execution starts with
the opening brace ( { ) К with the closing brace ( } ). Between these two
braces the programmer should declare the and the executable part.
Declaration Part:
The declaration part declares the entire variables that are used in
executable part. The initialization of variables is also done in this section.
The initialization means providing to the variables.
Executable Part:
This part contains the statements following the declaration of the
variables. This part contains a set of statements or a single statement.
These statements are enclosed between
-
User-defined function:
The functions defined by the user are called user-defined functions.
These functions are generally defined after the main () function. They
R. SIVARASAN 4
ANSI C PROGRAMMING CONCEPT
7. Main :
main() is a collection of the set of statements. Statements are
always enclosed belongs to main() within pairs of {} (opening and
closing braces).For ex.
void main()
{
1st statement;
2nd statement;
}
R. SIVARASAN 5
ANSI C PROGRAMMING CONCEPT
8. Declaration:
Any variable used in the program must be declared before
using it. For ex,
int a,b,c; /*declaration*/
a=a+b; /*usage*/
9. For input use scanf("%d,%f",&a,&c); function i.e syntax is scanf("<
string1>,< string2>,...",&variable1 ,&variable2..);
10. For output use printf("%d,%f",&a,&c); function i.e syntax is
printf("<string1>,< string2>",variable1,variable2); , & is used in scanf
function is must because it is "Address of operator". It gives the
location number used by variable.
11. Linking:
#include<stdio.h> stands for standard input output,
#include<conio.h> stands for control input output. These are most
commonly used for Linking.
Syntax: Hello_World . c
R. SIVARASAN 6
ANSI C PROGRAMMING CONCEPT
Windows system
Step 1: Locate the TC.exe file and open it. You will find it at
location C:\TC\BIN\.
Step 2: File > New (as shown in above picture) and then write your C
program
#include<stdio.h>
int main()
{
printf("hello World!");
return 0;
}
R. SIVARASAN 7
ANSI C PROGRAMMING CONCEPT
Step 3: Save the program using F2 (OR file > Save), remember the
extension should be “.c”. In the below screenshot I have given the name as
helloworld.c.
Step 4: Compile the program using Alt + F9 OR Compile > Compile (as
shown in the below screenshot).
R. SIVARASAN 8
ANSI C PROGRAMMING CONCEPT
Step 5: Press Ctrl + F9 to Run (or select Run > Run in menu bar ) the C
program.
Step 6: Alt+F5 to view the output of the program at the output screen.
R. SIVARASAN 9
ANSI C PROGRAMMING CONCEPT
1.5 C TOKENS:
A tokens is an individual words and punctuation marks are
called token.
More than on token can appear in a single line separated by
white spaces.
White space may be blank, carriage return or tab
C TOKENS
Keywords
Constant Operator
Int s s
Float
If
Else -12.04 + - * /
Goto
Break , ect
1000
-20 < >=
Identifiers Strings Special
Symbols
A0 “month”
BASICPAY “Daya” { }
[ ]
Basicpay “ABC”
# &
Total_pay
1.5.1 KEYWORDS:
All keywords have fixed meanings and these meanings
cannot be changed.
Its serve as basic building blocks for program statements
Keywords should be written in lowercase.
R. SIVARASAN 10
ANSI C PROGRAMMING CONCEPT
1.5.2 IDENTIFIERS:
Identifiers are names given to variables, functions, arrays and other
user defined objects. These are user defined names.
Rules:
1) Identifiers are formed with alphabets, digits and a special character
underscore (_).
2) The first character must be an alphabet (or underscore).
3) Only first 31 characters are significant.
4) Cannot use a keyword.
5) Must not contain white space.
Example:
Invalid identifiers:
1.5.3 CONSTANTS:
C Constants are also like normal variables. But, only difference
is, their values can not be modified by the program once they are
defined.
Constants refer to fixed values. They are also called as literals
Constants may be belonging to any of the data type.
R. SIVARASAN 11
ANSI C PROGRAMMING CONCEPT
CONSTANTS
NUMERIC CHARACTER
CONSTANT CONSTANTS
INTEGER CONSTANT
Decimal integers
R. SIVARASAN 12
ANSI C PROGRAMMING CONCEPT
Octal integers:
Valid example:
0.01342 +9.249 -0.0008 Normal Type of real constants
R. SIVARASAN 13
ANSI C PROGRAMMING CONCEPT
R. SIVARASAN 14
ANSI C PROGRAMMING CONCEPT
1.6 Variables:
A variable is a data name that may be used to store a data
value. Constant that remain unchanged during the execution of a program,
a variable may take different value at different times during execution.
Variable name can be chosen by the programmer in a
meaningful way so as to reflect its function or nature in the program.
R. SIVARASAN 15
ANSI C PROGRAMMING CONCEPT
1. Local Variable:
The scope of local variables will be within the function only.
These variables are declared within the function and can‟t be
accessed outside the function.
In the below example, m and n variables are having scope within
the main function only. These are not visible to test function.
Like wise, a and b variables are having scope within the test
function only. These are not visible to main function.
Example:
#include<stdio.h>
void test();
int main()
{
int m = 22, n = 44; /* m, n are local variables of main function
m and n variables are having scope within
this main function only.These are not visible
to test funtion.
If you try to access a and b in this function,
you will get 'a' undeclared and 'b' undeclared
error */
printf("\n values : m = %d and n = %d", m, n);
test();
}
2. Global Variable:
The scope of global variables will be throughout the program.
These variables can be accessed from anywhere in the program.
This variable is defined outside the main function. So that, this
variable is visible to main function and all other sub functions.
R. SIVARASAN 16
ANSI C PROGRAMMING CONCEPT
Example
#include<stdio.h>
void test();
int m = 22, n = 44;
int a = 50, b = 80;
int main()
{
printf("All variables are accessed from main function");
printf("\nvalues: m=%d:n=%d:a=%d:b=%d", m,n,a,b);
test();
}
3. Environment Variables:
Environment variable is a variable that will be available for all C
applications and C programs.
We can access these variables from anywhere in a C program
without declaring and initializing in an application or C program.
The inbuilt functions which are used to access modify and set these
environment variables are called environment functions.
R. SIVARASAN 17
ANSI C PROGRAMMING CONCEPT
1. Signed
2. Unsigned
3. Long
4. Short
Note: These are used only with the basic data types int and char. Long can
be used with double.
Type Storage size Value range
Char(or)
1 byte -128 to 127 or 0 to 255
signed
unsigned char 1 byte 0 to 255
-32,768 to 32,767 or -
int 2 or 4 bytes
2,147,483,648 to 2,147,483,647
unsigned int 2 or 4 bytes 0 to 65,535 or 0 to 4,294,967,295
short 2 bytes -32,768 to 32,767
unsigned short 2 bytes 0 to 65,535
long 4 bytes -2,147,483,648 to 2,147,483,647
unsigned long 4 bytes 0 to 4,294,967,295
float 4 byte 1.2E-38 to 3.4E+38
double 8 byte 2.3E-308 to 1.7E+308
long double 10 byte 3.4E-4932 to 1.1E+4932
R. SIVARASAN 18
ANSI C PROGRAMMING CONCEPT
3) Pointers to void
A pointer of type void * represents the address of an object, but not
its type.
For example, a memory allocation function void *malloc( size_t size );
returns a pointer to void which can be casted to any data type.
1.7.2 USER DEFINED DATA TYPES:
User defined data types are data types defined by the user. They are
1) Enumeration
2) Structure
1) Enumeration
This allows us to define our own data type with predefined values.
Syntax
enum userdefined_name{ value1, value2, …….. value n };
Where
enum keyword
userdefined_name valid c name
value1 value2 value n list of constants and are clled
members internally these are
treated as integers. That is
value 1 = 0, value 2 = 1……
value n = n-1.
Example:
To define a variable which can take values as Jan, Feb, Mar,… Dec
Definition
enum month{ Jan,Feb,Mar,Apr,……..Dec};
internally Jan=0, Feb=1, Mar=2,……. Dec=11 will be stored.
R. SIVARASAN 19
ANSI C PROGRAMMING CONCEPT
2) Structure:
A structure is defined as data type to represent different type of
data with a single name. The data items in a structure are called members
of the structure
Defining a structure:
A structure definition contains a keyword struct and user defined
tag-field followed by the members of the structure within braces.
Syntax:
struct tag-field
{
datatype member1;
datatype member2;
---------
----------------
datatype member n;
}
Example:
Consider student information consisting of number, age,
sex. The structure definition can be done as follows
struct student
{
int number;
int age;
char sex;
};
Three members namely number, age and sex of different data types. The
name of the structure is student.
R. SIVARASAN 20
ANSI C PROGRAMMING CONCEPT
1) Arrays
2) Pointer
3) Function
Array: An array is a fixed size sequenced collection of element of the
same data type
R. SIVARASAN 21
ANSI C PROGRAMMING CONCEPT
R. SIVARASAN 22
ANSI C PROGRAMMING CONCEPT
1.9 OPERATORS:
An operator is a symbol that tells the computer to perform
certain mathematical or logical manipulations.
TYPE OF OPERATORS:
1.9.1ARITHMETIC OPERATORS:
Symbol Meaning
+ Addition or Unary plus
- Subtraction or Unary minus
* Multiplication
/ Division
% Modulo Division
R. SIVARASAN 23
ANSI C PROGRAMMING CONCEPT
R. SIVARASAN 24
ANSI C PROGRAMMING CONCEPT
Symbol Meaning
&& Logical AND
|| Logical OR
! Logical NOT
Syntax
Expression 1 Logical operators Expression 2
R. SIVARASAN 25
ANSI C PROGRAMMING CONCEPT
Syntax:
OP V ; [OR] V OP;
R. SIVARASAN 26
ANSI C PROGRAMMING CONCEPT
Example:
int x;
int y;
// Increment operators
x = 1;
y = ++x; // x is now 2, y is also 2
y = x++; // x is now 3, y is 2
// Decrement operators
x = 3;
y = x--; // x is now 2, y is 3
y = --x; // x is now 1, y is also 1
Syntax:
Exp1 ? Exp2 : Exp3 ;
Example:
a=4 b=7;
X=(a>b) ? a : b ;
R. SIVARASAN 27
ANSI C PROGRAMMING CONCEPT
0 0 0 0 0
0 1 0 1 1
1 1 1 1 0
1 0 0 1 1
A = 0011 1100
B = 0000 1101
-----------------
A&B = 0000 1100
A|B = 0011 1101
A^B = 0011 0001
~A = 1100 0011
The following table lists the bitwise operators supported by C. Assume variable
'A' holds 60 and variable 'B' holds 13, then –
Operat
Description Example
or
sizeof(a), where a is
sizeof() Returns the size of a variable.
integer, will return 4.
R. SIVARASAN 28
ANSI C PROGRAMMING CONCEPT
Syntax:
Variable = expression ;
Priority
This represents the evaluation of expression starts from "what"
operator.
Associativity
It represents which operator should be evaluated first if an
expression is containing more than one operator with same priority.
Operator Priority Associativity
*, /, % 3 Left to right
+, - 4 Left to right
|| 7 Left to right
R. SIVARASAN 29
ANSI C PROGRAMMING CONCEPT
?: 8 Right to left
Example 1:
Rules
1) First, parenthesized sub expression from left to right are evaluated.
2) If parentheses are nested, the evaluation begins with the innermost
sub-expression.
3) Arithmetic expressions are evaluated from left to right using the
rules of precedence.
4) the expressions within parentheses assume highest priority
R. SIVARASAN 30
ANSI C PROGRAMMING CONCEPT
Here, the value of a has been promoted from int to double and we
have not had to specify any type-casting operator.This is known as
a standard conversion.
The usual arithmetic conversions are implicitly performed to cast
their values to a common type. The compiler first performs integer
promotion; if the operands still have different types, then they are
converted to the type that appears highest in the following
hierarchy –
Example :-
#include<stdio.h>
#include<conio.h>
void main()
R. SIVARASAN 31
ANSI C PROGRAMMING CONCEPT
{
int i=20;
double p;
clrscr();
getch();
}
Output:-
R. SIVARASAN 32
ANSI C PROGRAMMING CONCEPT
getch();
}
Output :-
R. SIVARASAN 33
ANSI C PROGRAMMING CONCEPT
Syntax:
if(test condition)
{
statement block;
}
next statement;
R. SIVARASAN 34
ANSI C PROGRAMMING CONCEPT
Flow Diagram:
If
Test
Statement block
Condition False
True
Next statement
EXAMPLE
int main()
{
int m=40,n=40;
if (m == n)
{
printf("m and n are equal");
}
}
OUTPUT:
m and n are equal
R. SIVARASAN 35
ANSI C PROGRAMMING CONCEPT
Syntax:
if(test condition)
{
statement block-1;
}
else
{
statement block-2;
}
next statement;
Flow Diagram:
false If True
Statement block Test Statement
-1 Condition block
-2
Next statement
Example:
#include <stdio.h>
int main()
{
int m=40,n=20;
if (m == n)
{
R. SIVARASAN 36
ANSI C PROGRAMMING CONCEPT
R. SIVARASAN 37
ANSI C PROGRAMMING CONCEPT
Example
#include <stdio.h>
int main()
{
int m=40,n=20;
if (m>n) {
printf("m is greater than n");
}
else if(m<n) {
printf("m is less than n");
}
else {
printf("m is equal to n");
}
}
OUTPUT:
m is greater than n
R. SIVARASAN 38
ANSI C PROGRAMMING CONCEPT
Syntax:
switch(expression)
{
case label-1:
statement block-1;
break;
case label-2:
statement block-2;
break;
case label-n:
statement block-n;
break;
default
default statement;
break;
}
next statement
When this statement is executed the computer first evaluates the
value of the expression in the keyword switch. This value is successively
compared with the case label-1,label-2 label-n. If a case label matches
with the value, the statement block associated with the case label is
executed. Then the control is transferred to the next statement.
If none of the case matches with the value, the default statement
block is executed.
R. SIVARASAN 39
ANSI C PROGRAMMING CONCEPT
Flow Diagram:
If
Test
condition
Label 1
Next statement
Label n -1
Label 2
Statement block - 2
Label n
Statement block - n
Default
Default Statement
block
Next Statement
EXAMPLE:
#include<stdio.h>
int main( )
{
int day;
printf("\n Enter the number of the day:");
scanf("%d", &day);
switch(day)
{
case 1:
printf("Sunday");
break;
case 2:
printf("Monday");
R. SIVARASAN 40
ANSI C PROGRAMMING CONCEPT
break;
case 3:
printf("Tuesday");
break;
case 4:
printf("Wednesday");
break;
case 5:
printf("Thursday");
break;
case 6:
printf("Friday");
break;
case 7:
printf("Saturday");
break;
default:
printf("Invalid choice");
}
return 0;
Output:
Thursday
R. SIVARASAN 41
ANSI C PROGRAMMING CONCEPT
1) While statement
2) Do . . . . while statement
3) For statement
Rules:
1. The test condition should be any relational or logical expression
enclosed within brackets.
2. If the body of the loop contains more than one statement, the { }
brackets are must.
Loop
S.no Name Syntax Description
Where,
exp1 – variable initialization
for (exp1; exp2; ( Example: i=0, j=2, k=3 )
1 for expr3) exp2 – condition checking
{ statements; } ( Example: i>5, j<3, k=3 )
exp3 – increment/decrement
( Example: ++i, j–, ++k )
where,
while (condition)
2 while condition might be a>5,
{ statements; }
i<10
do { statements;
do } where,
3
while while condition might be a>5,
(condition); i<10
R. SIVARASAN 42
ANSI C PROGRAMMING CONCEPT
Syntax:
while ( test condition )
{
body of the loop ;
}
next statement ;
The computer first evaluates the test condition. If the vale is false,
the control is transferred to next statement. If the value is true, then the
body of the loop is executed reputedly until the test condition becomes
false. When the test condition becomes false the control is transferred to
next statement.
Flow Diagram
Test
False
Statement block
Condition
True
R. SIVARASAN 43
ANSI C PROGRAMMING CONCEPT
Example:
#include <stdio.h>
int main()
{
int i=3;
while(i<10)
{
printf("%d\n",i);
i++;
}
}
OUTPUT:
3456789
Syntax:
do
{
body of the loop;
}
while ( test condition ) ;
next statement ;
R. SIVARASAN 44
ANSI C PROGRAMMING CONCEPT
Flow Diagram:
True
Test
Condition
False
Example:
#include <stdio.h>
int main()
{
int i=1;
do
{
Printf(“Display the values “);
printf("Value of i is %d\n", i);
i++;
}while(i<=4 && i >=2);
R. SIVARASAN 45
ANSI C PROGRAMMING CONCEPT
OUTPUT:
Display the values
Value of i is 1
Value of i is 2
Value of i is 3
Value of i is 4
Syntax:
For ( initial condition ; test condition ; increment or decrement )
{
Body of the loop ;
}
Next statement ;
Where
1) Initial condition is used to set initial values to control variables.
2) Test condition is used to check the control variable. According to
this the loop is executed or not
3) Increment or decrement is used to change the value of the control
variable.
R. SIVARASAN 46
ANSI C PROGRAMMING CONCEPT
FLOW DIAGRAM:
False
Test
Condition Next of the loop
True
Increment or decrement
of control variable
Example:
#include <stdio.h>
int main()
{
int i;
for(i=0;i<10;i++)
{
printf("%d ",i);
}
}
OUTPUT:
0123456789
R. SIVARASAN 47
ANSI C PROGRAMMING CONCEPT
ARRAY:
array is defined as a group of related data items that share a
common name with different index values. The index value starts from 0
to n-1.
array_name[subscript];
Rules:
1) array_name must be valid C-variable name.
2) name of the array should be unique.
3) the elements in the array should be of same type
4) the subscript is always an integer
5) the subscript value cannot be negative.
6) The subscript must be given within square brackets after the
array name.
7) if there are more than one subscript each should be given in
separate square brackets.
Syntax:
array_name[subscript];
Example: a[7];
R. SIVARASAN 48
ANSI C PROGRAMMING CONCEPT
Syntax: array_name[subscript]
Example:
1) a[3]
where:
a and name of the arrays.
3 is subscript data element or size of the array
2) grade[20]
grade name of the arrays.
20 is subscript data element
or size of the array
Syntax:
datatype array_name[size];
Where
datatype int float char etc.
array_name variable name.
Size number of contiguous location in the
memory to be reserved.
Example:
1) int mark[50];
This declares an integer type array named as mark having
50 memory location to store 50 integer data
R. SIVARASAN 49
ANSI C PROGRAMMING CONCEPT
2) char name[8]
This declares the name as a character array (string) variable that
can hold a maximum of 8 characters. Suppose we read the following string
constant into the string variable name.
“WELCOME”
each character of the string is treated as an element of the array
name and is stored in the memory
'W'
'E'
'L'
'C'
'O'
'M'
'E'
'\0'
Syntax:
static datatype array_name[size]={ list of values};
Where
static key word
datatype type of data found in the array such as int,
float, char etc.
array_name variable name.
Size number of contiguous locations in the
memory to be reserved.
List of values initial values to be given to the array. This
should be separated by commas.
R. SIVARASAN 50
ANSI C PROGRAMMING CONCEPT
Example:
1) static float salary [ ] = {4.50,10.25,27.47,7.58};
this declares salary as a real array and the size of the array is
automatically allocated by counting the number of values. Here computer
counts the value as four and assigns the size as 4.
if the size of the array is grater than the number of values in the list,
then the unused locations are filled with zeros as given below,
Example:
write a program to find the smallest number and its position in a
given one dimensional array.
#include<stdio.h>
void main()
{
int I, j, n, small, pos;
int a[50];
printf(“Give the vlaue of n”);
scanf('%d”,&n);
for(i=0; i<n; i++)
sccanf(“%d”,a[i]);
small=a[0];
pos=0;
R. SIVARASAN 51
ANSI C PROGRAMMING CONCEPT
Syntax:
array_name[subscript 1][subscript 2]
where
subscript 1 row number
subscript 2 column number
Example:
A[2][2]
Syntax:
datatype array_name[row size][column size];
R. SIVARASAN 52
ANSI C PROGRAMMING CONCEPT
Where
datatype int, char, float etc.
array_name variable name.
Row size maximum number of rows in the table.
Column size maximum number of column in the table.
Rules:
1) array_name must be valid C-variable name.
2) name of the array should be unique.
3) the elements in the array should be of same type
4) the subscript is always an integer
5) the size of the array is got by multiplying the row size and
column size.
5) the subscript value cannot be negative.
6) The subscript must be given within square brackets after the
array name.
Example
int mark [3][2];
Column 0 Column 1
Row 0 Mark[0][0] Mark [0][1]
Row 1 Mark [1][0] Mark [1][1]
Row 2 Mark [2][0] Mark [2][1]
The row number and column number mark[0][0] …... mark[2][1] are
called address of the locations.
Syntax:
R. SIVARASAN 53
ANSI C PROGRAMMING CONCEPT
where
static key word
datatype type of data found in the array such as int,
float, char etc.
array_name variable name.
Size number of contiguous locations in the
memory to be reserved.
List of values initial values to be given to the array. This
should be separated by commas.
Example:
static int mark[3][3]={8,2,9,28,34,43,15,20,5};
Mark[0][0] Mark[0][1]
8 2
mark[1][0] Mark[1][1]
7 10
R. SIVARASAN 54
ANSI C PROGRAMMING CONCEPT
Example:
write a program to read a n x m matrix.
#include<stdio.h>
void main()
{
int a[20][20] , I , j , m , n;
scanf(“%d %d”, &n,&m);
for ( i=0; i<n; i++ )
for(j=0 ; j< m; j++)
scanf(“ %d”, &a[i][j] );
}
Syntax:
array_name[subscript 1][subscript 2]............. [subscript m];
where:
subscript 1 row number
subscript 2 column number
R. SIVARASAN 55
ANSI C PROGRAMMING CONCEPT
Syntax:
char variable_name[size];
where
char datatype
variable_name variable name.
Size maximum number of characters in
the string including '\0'
Example:
char class[15] ;
Syntax:
static dataype variable_name[size]= string ;
Example:
static char state[15] = “ TAMIL NADU”;
This declares state as a string variable having 15 characters
and is stored as shown below.
S S S S S S S S S S S S
[0] [1] [2] [3] [4] [5] [6] [7] [8] [9] [10] [11]
T A M I L N A D U \0 \0
R. SIVARASAN 56
ANSI C PROGRAMMING CONCEPT
scanf function:
scanf function with the format specification %s is used to read a
string of characters. The most familiar input function scanf function.
Syntax:
scanf ( “%s”,variable_name);
the problem with scanf function is the reading stops when it finds a
white space character in the input string.
A white space includes blanks, tabs, carriage returns, form feeds,
and w lines.
Example:
char name[15];
scanf (“%s”, name);
Example:
Write a C program to illustrate how to read string from terminal.
#include <stdio.h>
int main(){
char name[20];
printf("Enter name: ");
scanf("%s",name);
printf("Your name is %s.",name);
return 0;
R. SIVARASAN 57
ANSI C PROGRAMMING CONCEPT
D e n n i s \0 ? ? ? ? ? ? ? ?
Output
Enter name: Dennis Ritchie
Your name is Dennis.
Here, program will ignore Ritchie because, scanf() function takes only
string before the white space.
GETCHAR FUNCTION
the function is used to read a string chracter.
Example:
#include <stdio.h>
int main(){
char name[30],ch;
int i=0;
printf("Enter name: ");
while(ch!='\n') // terminates if user hit enter
{
ch=getchar();
R. SIVARASAN 58
ANSI C PROGRAMMING CONCEPT
name[i]=ch;
i++;
}
name[i]='\0'; // inserting null character at end
printf("Name: %s",name);
return 0;
}
GETS FUNCTIONS:
This function is used to read a string of text containing
characters until a new line character(whitespaces) „\n‟ is entered. The
library function gets available in the <stdio.h> header file.
Example:
char str[10];
Gets(str);
Printf(“ % s ” , str );
[OR ]
char str[40];
gets( :”%s”,gets(str));
Input: “SIVA”
Output:
S I V A \0 ? ? ? ? ?
Example:
int main(){
char str[30];
printf("Enter string: ");
gets(str); //Function to read string from user.
R. SIVARASAN 59
ANSI C PROGRAMMING CONCEPT
printf("string: ");
puts(str); //Function to display string.
return 0;
}
Syntax:
Printf( “ %s “, variable_name ) ;
Where
variable_name array name or string .
Example:
#include<stdio.h>
Void main
{
char str[15] = “ dennis ritchie
R. SIVARASAN 60
ANSI C PROGRAMMING CONCEPT
printf(“%s\n”, str);
printf(“ %15.6s “, str);
printf(“ %15.9s”, str);
}
Output:
dennis ritchie
dennis
dennis rit
putchar function:
like getchar() function , there is analogous function putchar for
writing characters one at a time to the terminal. It takes the form as shown
below
Syntax: putchar(variable_name);
Example:
#include<stdio.h>
Int main()
{
Char str[10];
Printf(“Enter a string or character\n”);
s=getchar();
str[10] =s;
printf(“given string or character is: “);
putchar(str);
return 0;
}
Output:
Enter a string or character
program
piven string or character is: program
R. SIVARASAN 61
ANSI C PROGRAMMING CONCEPT
puts function:
pts function is a function which is used to display string on the
terminal.
Example:
#include<stdio.h>
Void main()
{
char str[] = “ PROGRAMMING IN C\n”;
Puts(str);
Puts(“programming in c”);
}
Output:
PROGRAMMING IN C
Programming in c
String 1= 0 1 2 3 4 5 6 7 8 9 0 1 2
V E R Y \0
String 2 = 0 1 2 3 4 5
G O O D \0
0 1 2 3 4 5
String 3= B A D \0
R. SIVARASAN 62
ANSI C PROGRAMMING CONCEPT
Example:
The result is
0 1 2 3 4 5 6 7 8 9 0 1 2
V E R Y G O O D \0
Program:
#include <stdio.h>
#include <string.h>
int main( )
{
char source[ ] = " fresh2refresh" ;
char target[ ]= " C tutorial" ;
OUTPUT:
R. SIVARASAN 63
ANSI C PROGRAMMING CONCEPT
String 1 = 0 1 2 3 4 5
G O O D \0
String 2 = 0 1 2 3 4 5
Result
string 1 = 0 1 2 3 4 5
G O O D \0
String 2 0 1 2 3 4 5
G O O D \0
Example:
#include <stdio.h>
#include <string.h>
int main( )
{
char source[ ] = "fresh2refresh" ;
char target[20]= "" ;
printf ( "\nsource string = %s", source ) ;
R. SIVARASAN 64
ANSI C PROGRAMMING CONCEPT
Note:
Returns 0 if str1 is same as str2.
Returns <0 if strl < str2.
Returns >0 if str1 > str2
Example:
#include <stdio.h>
#include <string.h>
int main( )
{
char str1[ ] = "fresh" ;
char str2[ ] = "refresh" ;
int i, j, k ;
i = strcmp ( str1, "fresh" ) ;
j = strcmp ( str1, str2 ) ;
k = strcmp ( str1, "f" ) ;
R. SIVARASAN 65
ANSI C PROGRAMMING CONCEPT
Example:
#include<stdio.h>
#include<string.h>
int main()
{
char str[15] = "Hello";
R. SIVARASAN 66
ANSI C PROGRAMMING CONCEPT
return 0;
}
Output :
String before strrev( ) : Hello
String after strrev( ) : olleH
Example :
#include<stdio.h>
#include<string.h>
int main()
{
char str[ ] = "Modify This String To Upper";
printf("%s\n", strupr(str));
return 0;
}
Output:
MODIFY THIS STRING TO UPPER
R. SIVARASAN 67
ANSI C PROGRAMMING CONCEPT
Example:
#include<stdio.h>
#include<string.h>
int main()
{
char str[ ] = "MODIFY This String To LOwer";
printf("%s\n",strlwr (str));
return 0;
}
Output: modify this string to lower
String
fuction Syntax Description example
strncat ( ) Strncat( s1, s2, n); Appends a strncat ( str2, str1, 3 ); –
portion of string First 3 characters of str1
to another is concatenated at the end
of str2.
strncpy ( ) Strncpy ( s1, s2, 5); Copies given strncpy ( str1, str2, 4) – It
number of copies first 4 characters of
characters of one str2 into str1.
string to another
R. SIVARASAN 68
ANSI C PROGRAMMING CONCEPT
Syntax:
char variable_name [row size] [column size];
R A J
J O S E P H
J E S T I N
S U D H A K A R
S I V A
R. SIVARASAN 69
ANSI C PROGRAMMING CONCEPT
FUNCTION
4.1 INTRODUCTION:
A function is a block of code that performs a specific task.
Function is classified as one of the derived data types in c. There are two
type of functions in c. they are
1) Library Function
2) User Defined Function
Function
User defined
Library functions
functions
Library functions:
Which are not required to be written by the programmer. But these
are available in separate files and the programmer has to include it in the
appropriate places. Function prototype and data definitions of these
functions are written in their respective header file.
Example:
<strdio.h> header file printf , scanf , etc
R. SIVARASAN 70
ANSI C PROGRAMMING CONCEPT
Syntax:
Example:
1) int addNumbers(int a, int b); // function prototype
R. SIVARASAN 71
ANSI C PROGRAMMING CONCEPT
FUNCTION DEFINITION:
Definition of functions:
Function definition also known as function implementation. A
function should be defined before it is used. A function has two parts
1) Function Header
2) Function Body
Syntax:
function_type function_name( list of arguments ) Function
{ Header
local variable declaration;
executable statement-1;
executable statement-2;
............ Function
........... Body
return ( expression);
}
R. SIVARASAN 72
ANSI C PROGRAMMING CONCEPT
Where
function _type Represents the data type of the value returned by the
function. if the return type is not explicitly
specified, c will assume that it is an void type.
List of arguments the variables that will receive the data sent by the
calling program.
Local variable
declaration declaration and statements necessary for performing
the required task. The body enclosed in braces.
Rules:
1. function header should not terminate with semicolon.
2. List of arguments and argument declaration are optional.
3. If the function has no list of arguments and empty
parentheses is a must.
4. The expression in the return statement is optional.
5. The parentheses around the expression in the return
statement is optional.
Example:
#include <stdio.h>
int addNumbers(int a, int b); // function prototype
int main()
{
int n1,n2,sum;
printf("Enters two numbers: ");
R. SIVARASAN 73
ANSI C PROGRAMMING CONCEPT
scanf("%d %d",&n1,&n2);
sum = addNumbers(n1, n2); // function call
printf("sum = %d",sum);
return 0;
}
int addNumbers(int a,int b) // function definition
{
int result;
result = a+b;
return result; // return statement
}
Syntax:
Void function_name(list of arguments)
Example of function:
int factorial(int x)
{
int r=1;
if(x==1) return 1;
else r=x*factorial(x-1);
return r;
}
Factorial is the name of the function. It has one formal parameters
x. the statement body has another variable of the formal parameters x. the
return statement returns the value of r to other function.
R. SIVARASAN 74
ANSI C PROGRAMMING CONCEPT
Syntax:
function_name ( list of arguments );
Where
Function_name already defined function name.
Rules:
1. Function_name should be the name used in the function definition
called function.
2. Data type of the arguments should match with the already defined
function called function arguments.
3. The called function returns only one value per call.
Example:
#include<stdio.h>
int sum(int , int); //Prototype or Declaration
int main()
{
int x, y, result;
printf("Enter value of x and y: ");
scanf("%d %d", &x, &y);
result=sum(x, y); //calling of function-sum
printf("Sum of %d + %d = %d", x, y, result);
return 0;
}
//Definition of function sum
R. SIVARASAN 75
ANSI C PROGRAMMING CONCEPT
Advantage of function:
It provides modularity to the program.
Easy code Reusability. You just have to call the function by its
name to use it.
In case of large programs with thousands of code lines, debugging
and editing becomes easier if you use functions.
R. SIVARASAN 76
4.6 FUNCTIONS CATEGORY:
We have seen different ways of calling function. A Function is
depending on whether arguments are present or not and whether a values is
returned or not there are four types of functions.
Syntax:
Function does not return a value
Void function_name ( );
Example:
Program:
#include<stdio.h>
void area(); // Prototype Declaration
void main()
{
area();
}
void area()
{
float area_circle;
float rad;
printf("\nEnter the radius : ");
scanf("%f",&rad);
area_circle = 3.14 * rad * rad ;
printf("Area of Circle = %f",area_circle);
}
Output:
Enter the radius : 3
Area of Circle = 28.260000
R. SIVARASAN 78
ANSI C PROGRAMMING CONCEPT
Example:
#include<stdio.h>
#include<conio.h>
void main()
{
float sum;
float total();
clrscr();
sum = total();
printf(" Sum = %f\n" , sum);
}
float total()
{
float a, b;
a = 2.0 ;
b = 10.0 ;
return(a+b);
}
Output:
sum = 12.000000
R. SIVARASAN 79
ANSI C PROGRAMMING CONCEPT
Function accepts argument but it does not return a value back to the
calling Program.
It is Single (One-way) Type Communication.
Generally Output is printed in the Called function
Example:
#include<stdio.h>
#include<conio.h>
//----------------------------------------
void area(float radi); //Prototype Declaration
//----------------------------------------
void main()
{
float radi;
printf("nEnter the radius : ");
scanf("%f",&radi);
area(radi);
getch();
}
R. SIVARASAN 80
ANSI C PROGRAMMING CONCEPT
//----------------------------------------
void area(float radi)
{
float ar;
ar = 3.14 * radi * radi ;
printf("Area of Circle = %f", ar);
}
Output:
Enter the radius : 6
Area of Circle = 113.040000
} Control
R. SIVARASAN 81
ANSI C PROGRAMMING CONCEPT
Example:
#include <stdio.h>
main()
{
int i , n , value ;
printf ( “enter the value of n \n “ ) ;
scanf ( “ % d “ , &n ) ;
for ( i = 0 ; i < = n ; i + + )
{
value = square ( i ) ;
printf ( “ % d “ , i , value ) ;
}
}
square (m)
int m ;
{
int temp ;
temp = m * m ;
return ( temp ) ;
}
Output:
Enter n value
4
0 1 4 9 16
R. SIVARASAN 82
ANSI C PROGRAMMING CONCEPT
4.7 RECURSION:
1. A recursion function is one that calls itself again and again.
2. The normal function will be called by other functions by its name.
But the recursive function will be called by itself as long as the
condition is satisfied.
3. Recursion is a special case of this process.
Syntax:
return_type recursive_func ([argument list])
{
statements;
... ... ...
recursive_func ([actual argument]);
... ... ...
}
Statement
True
Condition
False
Remaining Statements
Stop
R. SIVARASAN 83
ANSI C PROGRAMMING CONCEPT
1) Direct Recursion
2) Indirect Recursion
Direct Recursion:
A function is said to be direct recursive if it calls itself directly
Function contain without argument
void recursion_name( )
{
……………….
………………..
recursion_name( ) ;
…………………
}
int main ( )
{
…………………………
recursion_name ( );
………………..
}
Example:
Main( )
{
Printf(“ this is direct recursion function example \n”);
Main( );
// function call itself
}
Indirect Recursion :
A function is said to be indirect recursive if it calls another function
and this new function calls the first calling function again.
R. SIVARASAN 84
ANSI C PROGRAMMING CONCEPT
Example:
The following example calculates the factorial of a given number
using a recursive function.
#include<stdio.h>
int factorial(int n)
{
if(n==0)
return 1;
else
return (n * factorial(n-1));
}
int main()
{
int num,f;
printf("Enter a number: ");
scanf("%d",&num);
f=factorial(num);
R. SIVARASAN 85
ANSI C PROGRAMMING CONCEPT
printf("Factorial of %d = %d",num,f);
return 0;
}
Explanation:
let us assume num=3.
Since the value of num is not equal to 0 the statement,
Fact=n * factorial(n-1)
R. SIVARASAN 86
ANSI C PROGRAMMING CONCEPT
Function call
Syntax:
function_name ( array_name, size_of_the_array );
Function definition
Syntax:
data_type function_name (array_name, size_of_the_array )
formal argument declaration;
Rules:
1. The function name in the function call and in function definition
should be same.
2. Type of the actual and formal arguments should be same.
3. The array name in the formal argument is declared with empty
brackets.
4. The function prototype must show that the argument is an array.
Example:
1) pass a single element of an array to function
#include <stdio.h>
void display(int a)
{
printf("%d",a);
}
int main(){
int big[]={6.20.33,14};
display(big[3]); //Passing array element c[3] only.
return 0;
}
Output: 14
R. SIVARASAN 87
ANSI C PROGRAMMING CONCEPT
R. SIVARASAN 88
ANSI C PROGRAMMING CONCEPT
Output:
Enter n numbers
53 56 24 63 28 14 36 91
After sort element is
14 24 28 36 53 56 63 91
Example:
#include <stdio.h>
void display(int array_name[2][2]);
int main()
{
int array_name[2][2],i,j;
printf("Enter 4 numbers:\n");
for(i=0;i<2;++i)
for(j=0;j<2;++j){
scanf("%d",&c[i][j]);
}
display(array_name); /* passing multi-dimensional array
to function */
return 0;
}
void display(int array_name[2][2]){
/* Instead to above line, void display(int array_name[][2]){
is also valid */
int i,j;
R. SIVARASAN 89
ANSI C PROGRAMMING CONCEPT
printf("Displaying:\n");
for(i=0;i<2;++i)
for(j=0;j<2;++j)
printf("%d",array_name[i][j]);
}
Input: 5 3 15 2
Output: 5 3
15 2
1) Automatic variables
2) External variables.
3) Static variables.
4) Register variables.
Syntax:
auto data_type variable 1, variable 2, ………………
variable n;
where
auto keyword to define automatic variable.
Data_type valid c data type such as int, float, ect.
Variable 1 to variable n valid identifier name
void main ( )
{
auto int p=5; // local variable declaration
and initialization
………………..
++p; // call the local variable
…………………
}
function1( )
{
float x = 3.1; // local variable declaration
and initialization
float y = 2.0; // local variable declaration
and initialization
……………….
……………..
x = x + y; // call the local variable
…………..
}
R. SIVARASAN 91
ANSI C PROGRAMMING CONCEPT
Example:
#include <stdio.h>
Void main ()
{
int p, q; /* local variable p and q declaration */
int r; /* local variable r declaration*/
p = 10; /* actual initialization to variable */
q = 20;
r = (p *p) / (q*q)
printf ("value of p= %d, q = %d \n", p, q);
printf(“ the result of expression \n r=%d”, r);
}
Output:
P = 10 q = 20
The result of expression
R = 0.25
Global variables or External variables:
The variables which are declared outside the function are called
external variables, usually on top of the program.
The variable is not declared internally or a specific function, these
are common to all the function in the program.
The variable are alive and active throughout the program.
When the variable definition will automatically allocate storage
space.
The referred by the variable is same name and same data type.
It also called as global variable, because the accessing limited is
entire programming.
R. SIVARASAN 92
ANSI C PROGRAMMING CONCEPT
Syntax:
Where
Extern key word to define external variable
data_type valid c data type such as int, float,..
ect.
Variable 1 to variable n valid identifier name
R. SIVARASAN 93
ANSI C PROGRAMMING CONCEPT
Example:
#include <stdio.h>
void student( void ) ; // function prototype
int stud_no ; // global variable stude_no
is declaration
main()
{
student() ; // function call
printf( "The students number is %d\n", stud_no ) ;
}
void student( void ) // function definition
{
Stud_no = 25 ;
}
Output:
The student number is 25
Static variable:
Static variables are variables which retain the values till the end of
the program. A variable can be declared static using the keyword static.
Syntax:
Static variable
Internal External
R. SIVARASAN 94
ANSI C PROGRAMMING CONCEPT
Register variables:
Variable also declared inside a function or block
The variable should be kept in one of the CPU registers,
The variable accessing is much faster than a memory
accessing.
The variable are stored in the registers are called register
variables.
Scope of the variable until end of function or block
Syntax:
Register data_type variable
Example:
Void main ( )
{
Register int a = 0 ;
Auto int b = 3 ;
Auto char = „ Z ‟ ;
}
R. SIVARASAN 95
ANSI C PROGRAMMING CONCEPT
STRUCTURES
4.11.1 Introduction:
Array and pointers are powerful tools to represent a group of data
items of same dat typed with a single name. But c
languageprovides a data type named as structures to do this task.
Structures defined as a collection of data items of different types
using a single name.
Array element access takes less Structure elements take more time
4
time than structures. than Array.
Structure is a programmer-
5 Array is a derived data type
defined data type
R. SIVARASAN 96
ANSI C PROGRAMMING CONCEPT
Syntax:
struct structure_name
{
data_type1 member1;
data_type2 member2;
data_type3 member3;
.........................
…………………
};
R. SIVARASAN 97
ANSI C PROGRAMMING CONCEPT
Syntax:
structure structure_name
{
data_type member1;
data_type member2;
……………………….
………………………
data_type member n;
};
variable1, variable2, …………, variable n;
Syntax:
Example:
Struct employee
{
Int emp_no;
Char emp_name[15];
Int salary;
};
employee1, employee2, employee3;
R. SIVARASAN 98
ANSI C PROGRAMMING CONCEPT
Syntax:
typedef struct
{
data_type member1;
data_type member2;
…………………
…………………..
data_type membern;
} variable;
struct home_address {
typedef struct home_address{
int local_street;
int local_street;
char *town;
char *town;
char *my_city;
char *my_city;
char *my_country;
char *my_country;
};
}addr;
………………
………………
………………
……………….
struct home_address var1 = {55,
addr var1 = {55, "Dayal bagh", "Agra",
"Dayal bagh", "Agra", "India"};
"India"};
R. SIVARASAN 99
4.11.7 Structure initialization:
The members of the structure variable can be assigned initial
values at compile time.
The structure should be declared as static type.
Syntax:
Example:
Structure
# include <stdio.h>
Struct employee
{
Int emp_no = 210 ;
Char name[15] = { “ ramkumar ” };
ANSI C PROGRAMMING CONCEPT
Syntax:
Structure_variable . member_name
Example:
Write a c program to assign values to the member of a structure named
employee and to display the employe no, name, salary detail.
#include<stdio.h>
struct employee;
{
R. SIVARASAN 101
ANSI C PROGRAMMING CONCEPT
int emp_no;
char emp_name[15];
float salary;
};
Void main( )
{
struct employee detail;
printf(“GIVE THE EMPLOYEE DETAILS\n;);
printf(“ENTER THE EMPLOYEE NUMBER :”);
scanf(“Emp_no=%d”, & detail.emp_no);
printf(“ENTER THE EMPLOYEE NAME :”);
scanf(“Emp_name=%d”, & detail.emp_name();
printf(“ENTER THE EMPLOYEE SALARY :”);
scanf(“Emp_salary=%d”, & detail.salary);
printf(“Emp_no=%d”, detail.emp_no);
printf(“Emp_name=%d”, detail.emp_name);
printf(“Emp_salary=%d”, detail.salary);
}
Input:
GIVE THE EMPLOYEE DETAILS
ENTER THE EMPLOYEE NUMBER
1024
ENTER THE EMPLOYEE NAME
RAJ
ENTER THE EMPLOYEE SALARY
40000
OUTPUT:
Emp_no = 1024
Emp_name = RAJ
Emp_salary = 4000
R. SIVARASAN 102
ANSI C PROGRAMMING CONCEPT
Syntax:
structure_variable2 = structure_variable1
Example:
struct employee
{
int no;
char name [20];
int salary;
};
void main( )
{
int x;
struct employee emp1 = { 9203,”jeo”,25000);
struct employee emp2 = { 9321,”mark”,15000);
struct employee emp3;
emp3 = emp1 ;
x =( (emp3.salaray == emp1.salary)&& (emp3.name ==
emp1.name) ) ? 1: 0 ;
printf(“The employee 1 details\n”);
R. SIVARASAN 103
ANSI C PROGRAMMING CONCEPT
Syntax:
struct structure_name structure_variable[size] ;
R. SIVARASAN 104
ANSI C PROGRAMMING CONCEPT
Example:
Struct class student[3];
the declaration describe information about two student namely
student1 and student2.
Struct student
{
Char name[15];
Int age;
};
Stuct student stud_bio[3];
Array index no
S_bio[0] S_bio[1] S_bio[2]
Array element
s_bio 0 s_bio 0 s_bio1 s_bio1 s_bio 2 s_bio 2
[0] [1] [0] [1] [0] [1]
index no
Element
R. SIVARASAN 105
ANSI C PROGRAMMING CONCEPT
Example:
Struct student
{
Int stud_no;
Char stud_name[20];
Int percentage;
};
Int main ( )
{
Struct student information[4] = {{1001,”Daniel”,
90},{1002.”joseph”,70},{1003,”sharma”,60},{1004,”mark”,91}};
For(i=0;i<4;i++);
{
Print(“%d,%s,%d \n”, information.
}
}
R. SIVARASAN 106
ANSI C PROGRAMMING CONCEPT
data_type member1;
data_type member2;
……………………….
………………………
data_type membern;
};
variable1, …… , variablen;
};
variable1, variable2, …………,
variablen;
structure
Member 1
Member 2
Structure1
Member 1
Member
Example:
struct student_information
{
char name[30];
int age;
// inner structure definition
struct stud_address
{
R. SIVARASAN 107
ANSI C PROGRAMMING CONCEPT
char locality[30];
char city[20];
int pincode;
}address;
}student;
Calling function:
The actual arguments are then treated independently like ordinary
variables.
This is the most elementary method and becomes unmanageable
and inefficient when the structure size is large.
Syntax:
function_name ( structure_variable_name );
where
function name name of the called function
structure _variable_name actual argument variable name of
the defined structure.
R. SIVARASAN 108
ANSI C PROGRAMMING CONCEPT
Called function:
The method involves passing of a copy of the entire structure to the
called function.
The function is working on a copy of the structure, any changes to
structure members within the function are not reflected in the
original structure
Necessary for the function to return the entire structure back to the
calling function.
Syntax:
data_type function_name(variable_name)
struct structure_name variable_name;
{
………………..
…………………..
return(expression);
}
Example:
Write a program to pass address of structure variable to user
defined function and display the contents.
#include<stdio.h>
#include<conio.h>
struct book
{
char name[28];
char author[30];
int pages;
};
void main()
{
struct book b1 = { “ PROBLEM SOLVING USING C”,”R.
SIVARAJ”,982};
show(&b1);
}
R. SIVARASAN 109
ANSI C PROGRAMMING CONCEPT
Output:
4.18 UNIONS
Union is like a structure data type in which all the members share
the same memory area.
In the structure each member has its own memory location
whereas, members of unions have same memory location.
The compiler allocates a memory space that is large enough to
store the largest variable type in the union.
Syntax:
Union union_tag_field
{
Data_type member1;
Data_type member2;
……………….
Data_type member;
} variable1,variable2,….. variable;
where
union keyword to define union
union_tag_field name of the union – valid name
member1 to member n different data type of data item or member
function.
R. SIVARASAN 110
ANSI C PROGRAMMING CONCEPT
Example:
union item
{
int m;
float x;
char c;
}It1;
Explanation:
This declares a variable It1 of type union item.
This union contains three members each with a different data type.
However only one of them can be used at a time. This is due to the fact
that only one location is allocated for a union variable, irrespective of its
size. The compiler allocates the storage that is large enough to hold largest
variable type in the union. In the union declared above the
member x requires 4 bytes which is largest among the members in 16-bit
machine. Other members of union will share the same address.
Uses of unions:
Unions conserve memory space.
They are useful for applications involving number of variables,
where values need not be assigned to all elements at one time.
R. SIVARASAN 111
ANSI C PROGRAMMING CONCEPT
Structure C Union
The address of each The address is same for all the members
member will be in of a union. This indicates that every
ascending order This member begins at the same offset value.
indicates that memory for
each member will start at
different offset values.
R. SIVARASAN 112
ANSI C PROGRAMMING CONCEPT
Program:
#include<stdio.h>
#include<conio.h>
void main ( )
{
union result
{
int marks;
{
int marks;
char grade;
};
struct res
{
char name[20];
int age;
union result perf;
};
data;
clrscr( );
printf(“size of union:%d\n”,sizeof(data.perf));
printf(“size of structure:%d\n”,sizeof(data));
}
Output:
Size of union: 2
Size of structure: 19
R. SIVARASAN 113
ANSI C PROGRAMMING CONCEPT
Variable memory
Name addresses
Ptr 53 0XA1
64 0XA2
0x101A 0XA3
62
Variable memory
Name addresses
10
A 0XA
43
B 0XB
C 2 0XC
D 5 0XD
R. SIVARASAN 114
ANSI C PROGRAMMING CONCEPT
Syntax:
data_type *pointer_variable_name ;
where
data_type Type of the variable pointed by pointer
variable such as int, float, etc.
* To identify the variable as pointer
pointer_variable_nam Valid variable name or identifier name, to
point to an data.
Rules:
1. Pointer variables should be a valid variable name.
2. Asterisk ( * ) is not the part of the variable name but it is to denote
the type of the variable as pointer.
3. Data type refers to the type of the variable pointer by the pointer
variable.
4. Initially the pointer does not point to anything byt the programmer
must assign it a value.
Example:
Int *p; // integer pointer
Float *q
Declares the variable p as a pointer variable that points to an integer data
type and another pointer variable q is to points to an float type of data..
R. SIVARASAN 115
ANSI C PROGRAMMING CONCEPT
Example:
int a = 10 ;
int *ptr ; //pointer declaration
ptr = &a ; //pointer initialization
[or]
int *ptr = &a ; //initialization and declaration together
the memory address of the variable a is assigned to the pointer variable
*ptr. If 20 is the address of the variable a. ptr got the value 20.
Program:
#include<stdio.h>
void main ( )
{
int a;
int *b;
a = 50;
b = &a;
printf(“ the content of the pointer b= %d \n”,*b);
printf(“the address of the pointer b= %d \n”, b);
}
R. SIVARASAN 116
ANSI C PROGRAMMING CONCEPT
Output:
The content of the pointer b=50;
The address of the pointer b= 25363
Example:
Write a program to perform different arithmetic operations using
pointers.
R. SIVARASAN 117
ANSI C PROGRAMMING CONCEPT
#include<stdio.h>
#include<conio.h>
Void main ( )
{
Int a=20, b=10, *p, *q;
P = &a;
Q=&b;
Clrscr( );
prinrf(“\n addition a+b =%d”,*p+b);
prinrf(“\n subtraction a-b =%d”,*p-b);
prinrf(“\n division a/b =%d”,*p/*q);
}
Output:
Addition a + b =30
Subtraction a-b = 10
Division a/b= 2
Example:
int arr[4] = { 3,6,8,10 };
Assuming that the base address of arr is 100 and each integer requires two
byte, the five element will be stored as follows
R. SIVARASAN 118
ANSI C PROGRAMMING CONCEPT
value 3 6 8 10
Address
100 102 104 106
Here variable arr will give the base address, which is a constant pointer
pointing to the element, arr[0]. Therefore arr is containing the address of
arr[0] i.e 1000.
arr is equal to &arr[0] // by default
We can declare a pointer of type int to point to the array arr.
int *p;
p = arr;
or p = &arr[0]; //both the statements are equivalent.
Program:
#include<stdio.h>
void main( )
{
static int a[5] ={ 30,100,50,20,90};
int *p;
int i;
p=&a[0];
printf(“contents of the arra \n”);
for(i=0;i<5;i++)
printf(“%d \n “, *(p+1));
}
Output:
30
100
50
20
90
R. SIVARASAN 119
ANSI C PROGRAMMING CONCEPT
0 1
15 30 0X
50 20 1X+1
EXAMPLE:
Write a program to display array elements and their address using
pointers.
#include<stdio.h>
void mani( )
{
int i,j=1, *r;
int a[2][2] ={ {6,9},{8,9} );
clrscr();
print(“elements of an array with their address\n”);
r=&a[0][0];
for(i=0;i<4;i++,j++)
{printf(“%5d[%5u]”,*®,r);
r++;
if(j=2);
j=0;
}
}
R. SIVARASAN 120
ANSI C PROGRAMMING CONCEPT
}
OUTPUT:
Elements of an array with their address.
6 [2002] 9 [2004]
8 [2006] 9 [2008]
Syntax:
data_type array_name[size] = { };
Example:
Char *str = “welcome”
To create a string for the literal and then stores its address in the pointer
variable str
The pinter str now points to the first character of the string “welcome”
w E L C O M E \0
str
Program:
Write a program to read string from keyboard and display it using
character pointer.
#include<stdio.h>
void main ( )
{
char name[15],*ch;
printf(“enter your name:”);
gets(name);
R. SIVARASAN 121
ANSI C PROGRAMMING CONCEPT
ch=name;
// store base address of string name
while(*ch!=‟\0‟)
{
printf(“%c”,*ch);
ch++;
}
}
Output:
Enter your name: suresh
suresh
syntax:
data_type (* function_pointer_name)( );
Where
* function_pointer_name pointer to a function name
#include<stdio.h>
Int main( )
{
Int z;
Z = 100;
Change(&z);
Printf(“%d \n”, z);
R. SIVARASAN 122
ANSI C PROGRAMMING CONCEPT
}
Change(int *r)
{
*p = *p+200;
}
Output:
300
Example:
#include <stdio.h>
#include <conio.h>
int* big(int*, int*);
void main()
{
int p=15;
int q=92;
int *z;
z=big(&p, &q);
printf("%d The biggest no",*z);
}
int* big(int *x, int *y)
{
if(*x > *y)
return x;
R. SIVARASAN 123
ANSI C PROGRAMMING CONCEPT
else
return y;
}
Output:
The biggest no 92
Syntax:
struct structure_name {
member1;
member2;
.
.
};
int main()
{
struct structure_name *ptr;
}
Example:
#include <stdio.h>
#include <string.h>
struct student
{
int id;
R. SIVARASAN 124
ANSI C PROGRAMMING CONCEPT
char name[25];
float percentage;
};
int main()
{
int i;
struct student record1 = {1, "Raju", 90.5};
struct student *ptr;
ptr = &record1;
printf("Records of STUDENT1: \n");
printf(" Id is: %d \n", ptr->id);
printf(" Name is: %s \n", ptr->name);
printf(" Percentage is: %f \n\n", ptr->percentage);
return 0;
}
Output:
Records of STUDENT1:
Id is: 1
Name is: Raju
Percentage is: 90.500000
R. SIVARASAN 125
ANSI C PROGRAMMING CONCEPT
FILE:
We used scanf and printf function to read and write data to and
from the computers though the console. If computers deal with large
amount of data as input (read) and output (output) then both methods are
not efficient. The best way is to use files to give data to the computers and
get data from the computer.
Syntax:
File * pointer_variable ;
Where
file defined data type
pointer_variable pointer to the data type file
Example:
FILE *fp;
The statement declares the variable fp as a “pointer to data type FILE”. As
the file stated earlier, FILE is a structure that is defined in the I/O library.
Type of file:
There are two types of files
1) Sequential File
2) Random Access File
R. SIVARASAN 126
ANSI C PROGRAMMING CONCEPT
1) Sequential File:
In this type data are kept sequentially. If we want to read the last
record of the file we need to read all the records before that record.
It take more time
If we desire to access the 10th record then the first 9 records should
be read sequentially for reaching to the 10th record.
Function Operation
fopen( ) Creates a new file for read / write operation
Feof( ) Test the end of file condition
Fclose( ) Closes a file associated with file pointer
READ OPERATION
fscanf( ) Reads all types of data values from a file.
getw( ) Reads an integer from the file.
Fgetc( ) Reads the character from current pointer
position and advances the pointer to next
character.
Getc ( ) Same as fgetc ( )
R. SIVARASAN 127
ANSI C PROGRAMMING CONCEPT
WRITE OPERATION
putc( ) Writes string to the file.
fprintf( ) Writes all types of data values to the file.
putw ( ) Writes an integer to the file
Random access file
fseek( ) Sets the pointer position anywhere in the file.
Ftell ( ) Return the current position of the pointer in the
given file
1) Opening a file
Opening of file creates a link between the operating system and the
file function. we have to specify the name of file and its‟s mode to the
operating system. The important task is carried out by the structure file that
is defined in stdio.h header file.
Syntax:
FILE *pointer_variable;
Pointer_variable = fopen(“file_name”,”mode”);
Where
pointe_variable variable which contains the address of the type FILE
file_name name of the file.
R. SIVARASAN 128
ANSI C PROGRAMMING CONCEPT
Example:
FILE *fpt
Fpt = fopen(“myfiles”,”r”);
The file myfile is opened for reading. If the file does not present an error
will occur
Syntax:
Feof(pointer_variable)
This function returns a non – zero value if the end of file is reached, else
zeo.
R. SIVARASAN 129
ANSI C PROGRAMMING CONCEPT
2) Close a file:
An opened file must be closed after all operations on it have been
completed. His ensures that all outstanding information associated with the
file is flushed out from the buffers and all liks to the file are broken.
Syntax:
Fclose(file_pointer_variable) ;
Example:
...........
...........
FILE *fp1,fp2;
Fp1 = fopen(“INPUT”,”w”);
Fp2 = fopen(“OUTPUT”,”r”);
……………
Fclose(fp1);
Fclose(fp2);
This program opens two files and closes them after all operations
on them are completed once a file is closed its file pointer can be reused
for another file
.
3) READING A FILE
Fscanf ( ) Function:
fscanf ( ) The fscanf function is used to read data items to the file
whose pointer is opened in the reading mode. fscanf function performs
Input operations on files.
Syntax:
Fscanf(pointe_variable, “control_string”,list) ;
Where
pointer_variable The pointer which contains the address of the file.
control_string The format commands such as %s, %d, %f etc.
list list of variable or string to be read from the file.
R. SIVARASAN 130
ANSI C PROGRAMMING CONCEPT
Example:
Program:
Write a program to enter dat into the text file and read the same.
Use “w+” file mode use fscanf() to read the contents of the file.
#include<stdio.h>
void main( )
{
file *fp; //file pointer defining
char text[20];
int age;
fp = fopen (“text.txt”,”w+”); // open a file operation fopen(
)
clrscr ( );
printf(“name \t age \n”);
scanf(“%s %d”,text,&age);
fprintf(fp,”%s %d”,text,age); //write a file operation using
fprintf( )
printf(“name \t age \n”);
fscanf(fp,”%s %d”,text,&age); // read a file operation
using fscanf( )
printf(“%s \t %d \n”,text,age);
fclose(fp); // file close operation fclose( )
}
R. SIVARASAN 131
ANSI C PROGRAMMING CONCEPT
Output:
Name age
Ram 25
Getw ( ) Function:
These functions return the integer value from a file and increase the
file pointer. These functions would be useful when we deal with only
integer data.
Syntax:
Number =getw (file_pointer);
Where
Number integer value
getw Reads an integer from the file
file_pointer The pointer which contains the address of the file.
Example:
FILE *fp
int num;
fp=fopen (“input”, "r”);
while (num=getw(fp)!=EOF)
printf(“%d”, num);
Where read an integer value from the file whose file pointer is fp
and assigned the reading numbers to num. The reading is terminated when
getw encounters the end of file mark EOF.
Getc ( ) Function:
This function reads a single character from the opened file and
moves the file pointer. It returns EOF, if end of file is reached. Getc( ) is
used to read a character from a file that has been opened in read mode.
R. SIVARASAN 132
ANSI C PROGRAMMING CONCEPT
Syntax:
character_variable = getc(file_pointer);
Where
character_variable single character variable name like as
A, C, R, ect
getc reads a single character file function key
Example:
file *fp;
char c;
fp=fopen (“input”, “r”);
while(c=getc(fp)!=Eof) // read a single character
putchar ( c ); // write a single character
Program:
#include<stdio.h>
#include<process.h>
void main( )
{
file *f;
chara c;
clrscr ( );
f=fopen(“ mydata.txt”,”r”);
If(f==NULL)
{
printf(“\n cannot open file”);
exit(1);
}
R. SIVARASAN 133
ANSI C PROGRAMMING CONCEPT
while(c=getc(f)!=EOF)
pring(“%d”,c);
fclose(f);
}
Output:
Akash
Ram
Suresh
Siva
Fgetc ( ) Function:
This function is similar to getc ( ) function. it also reads a character
and increases the file pointer position. If any error or end of file is reached
it returns EOF.
Syntax:
character_variable = fgetc(file_pointer);
where
character_variable single character variable name like as
A,C,R,ect
fgetc Reads a character and increases the file
pointer position.
Example:
file *fp;
char c;
fp=fopen (“input”, “r”);
while(c=fgetc(fp)!=Eof) // read a single character
putchar ( c ); // write a single character
R. SIVARASAN 134
ANSI C PROGRAMMING CONCEPT
Writing a file
Fprintf ( ) Function:
Fprintf ( ) this function is used for writing characters, strings,
integers, floats etc. to the file. It contains one more parameter that is file
pointer, which points the opened file.
Syntax:
Fprintf(pointe_variable, “control_string”,list) ;
Where
pointer_variable The pointer which contains the address of the file.
control_string The format commands such as %s, %d, %f etc.
list list of variable or string to be read from the file.
Example:
Program:
Write a program to open a myfile and write a some text using
fprintf ( ) function. open the file and verify the contents.
#include<stdio.h>
#include<conio.h>
void main( )
{
FILE *fp;
char myfile[50];
fp = fopen(“myfile.txt”,”w”);
R. SIVARASAN 135
ANSI C PROGRAMMING CONCEPT
clrscr ( );
printf(“enter text here:”);
gets(text);
fprintf(fp,”%s”,text);
fclose(fp);
}
Output:
Enter text here: have a good day.
Putc ( ) Function:
The function is used to write a single character into a file.if an error
occurs it returns EOF.
Syntax:
Example:
FILE *fp;
Char C;
Fp=fopen(“input”, “w”);
While (c = getchar( c )!= EOF)
Putc(c, fp); //write a single character
Putw ( ) Function:
The simplest I/O integer oriented function is putw( ). „putw‟ is used
to create an integer value to a file that has been opened in write mode. The
general form statement is
R. SIVARASAN 136
ANSI C PROGRAMMING CONCEPT
Syntax:
Putw(num,file_pointer);
Example :
FILE *fp
Int num;
Fp=fopen (“INPUT”, "w”);
Scanf(“%d”, & num);
While (num!= fp)
Putw(num,fp);
Scanf(“%d”, & num);
Where read a number through to the variable „num‟ and put the
number into the file whose file pointer is fp. The waiting is terminted when
„Putw‟ encounters the end of file mark Eof (i.e,num=0)
Fseek ( ) function:
This function is used to move the file pointer to any desired
location within the file.
Syntax:
Fseek (pointer_variable, offset, position);
Where
Pointer_variable pointer which contains address of the file
Offset this gives the number of positions to be moved from
the location given in position ot must be a long
integer.
position it is a integer number
R. SIVARASAN 137
ANSI C PROGRAMMING CONCEPT
Integer Location in
Constant
Values the file
Beginning of
0 SEEK_SET
the file
Current
1 SEEK_CUR position of the
file pointer.
Example:
Fseek(fp,10,seek_cur)
Ftell( ) function:
This function is used to return the current position of the pointer in
the given file.
Syntax:
N= ftell(pointer_variable);
Where
Ftell keyword to return the current position.
R. SIVARASAN 138
ANSI C PROGRAMMING CONCEPT
Example:
FILE *ptr;
Long n;
……………
…………………
N=ftell(pt);
…………….
Syntax:
Where
program_name name of the executable program wit .exe
string1,string2,…. String n list of arguments.
R. SIVARASAN 139
ANSI C PROGRAMMING CONCEPT
Argc = n+1
Argv[0] = program name
Argv[1] = string 1
Argv[2] = string 2
…………………..
…………………..
Argv[n] = string n
Example:
main(argc,argv)
int argc;
char *argv[ ];
…………
………….
Int this argc = 3
Argv[0] = prg
Argv[1] = file1
Argv[2] = file2
Program:
#include<stdio.h>
#include<conio.h>
Int Main(int argc,char *argv[ ])
{
Int x;
Clrscr ( );
Printf(“\n total number of argument are %d \n”,argc);
For (x=0;x<argc;x++)
Printf(“%s\t”,argv[x]);
Getch( );
R. SIVARASAN 140
ANSI C PROGRAMMING CONCEPT
Return 0;
}
Output:
Total number of arguments are 4
C:\TC\C.EXE A B C
Explanation:
To execute this program one should create its executable file and
run it from the command prompt with required arguments. The above
program is executed using following steps.
C:\TC>C.EXE HELP ME
R. SIVARASAN 141
ANSI C PROGRAMMING CONCEPT
1. malloc()
2. calloc()
3. realloc()
4. free()
Function Syntax
R. SIVARASAN 142
ANSI C PROGRAMMING CONCEPT
Malloc() Function In C
Syntax:
Program:
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
int main()
{
char *mem_allocation;
/* memory is allocated dynamically */
mem_allocation = malloc( 20 * sizeof(char) );
if( mem_allocation== NULL )
{
printf("Couldn't able to allocate requested memory\n");
}
else
{
strcpy( mem_allocation,"Dynamically_mem_allocation");
R. SIVARASAN 143
ANSI C PROGRAMMING CONCEPT
}
printf("Dynamically allocated memory content : " \
"%s\n", mem_allocation );
free(mem_allocation);
}
OUTPUT:
calloc()
Syntax
ptr=(cast-type*)calloc(n,element -size);
R. SIVARASAN 144
ANSI C PROGRAMMING CONCEPT
ptr=(float*)calloc(25,sizeof(float));
Program:
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
int main()
{
char *mem_allocation;
/* memory is allocated dynamically */
mem_allocation = calloc( 20, sizeof(char) );
if( mem_allocation== NULL )
{
printf("Couldn't able to allocate requested memory\n");
}
else
{
strcpy( mem_allocation,"fresh2refresh.com");
}
printf("Dynamically allocated memory content : " \
"%s\n", mem_allocation );
free(mem_allocation);
}
R. SIVARASAN 145
ANSI C PROGRAMMING CONCEPT
OUTPUT:
realloc()
Syntax
ptr=realloc(ptr,newsize);
Program:
#include <stdio.h>
#include <stdlib.h>
int main(){
int *ptr,i,n1,n2;
printf("Enter size of array: ");
R. SIVARASAN 146
ANSI C PROGRAMMING CONCEPT
scanf("%d",&n1);
ptr=(int*)malloc(n1*sizeof(int));
printf("Address of previously allocated memory: ");
for(i=0;i<n1;++i)
printf("%u\t",ptr+i);
printf("\nEnter new size of array: ");
scanf("%d",&n2);
ptr=realloc(ptr,n2);
for(i=0;i<n2;++i)
printf("%u\t",ptr+i);
return 0;
}
free()
R. SIVARASAN 147
ANSI C PROGRAMMING CONCEPT
Syntax
free(ptr);
#include <stdio.h>
#include <stdlib.h>
int main(){
int n,i,*ptr,sum=0;
printf("Enter number of elements: ");
scanf("%d",&n);
ptr=(int*)malloc(n*sizeof(int)); //memory allocated
using malloc
if(ptr==NULL)
{
printf("Error! memory not allocated.");
exit(0);
}
printf("Enter elements of array: ");
for(i=0;i<n;++i)
R. SIVARASAN 148
ANSI C PROGRAMMING CONCEPT
{
scanf("%d",ptr+i);
sum+=*(ptr+i);
}
printf("Sum=%d",sum);
free(ptr);
return 0;
}
R. SIVARASAN 149
ANSI C PROGRAMMING CONCEPT
Bibliography:
R. SIVARASAN 150