You are on page 1of 17

C Programming and Data Structures

(R20 Syllabus JNTUA,Anantapuramu)


UNIT-II
Syllabus
Functions, types of functions, Recursion and argument passing, pointers, storage allocation, pointers to functions,
expressions involving pointers, Storage classes – auto, register, static, extern, Structures, Unions, Strings, string
handling functions, and Command line arguments.

functions:

It performs the specific task. one of the strengths of c language is c functions. They are easy
to define and use. We have used functions in every program that we have discussed so far.However, they have
been primarily limited to the three functions namely main,printf and scanf.

types of fucntions
C functions can be classified into two categories, namely library functions and user defined
functions. Main is an example of user-defined functions.printf and scanf belong to the category of library
functions. We have also used other library functions such as sqrt,cos etc.

Elements of user defined functions:


In order to make use of a user defined function, we need to establish three elements that are
related to functions
1.Function prototype or function declaration
2.Function call
3.Function definition.
The function definition is an independent program module that is specially written to
implement the requirements of the function. In order to use this function we need to invoke it at a required place
in the program.This is known as function call.

Function proptype or function declaration : It represents to the compiler what is the return type and what
are the arguments are passing through the function calling and definition.
Syntax
return type or data type function name(datatype variablename1,datatype variablename2…..data type
variablenmen);
Example : int add(int,int);
function calling: By using function calling we can call the function number of times.
syntax: functionname(argument1,argument2…argument);
Example : add(a,b);
Function definition: A function definition , also known as function implementation shall include the following
elements
1.Functin type or return type
2.Functin name
3.List of parameters.
4.Local variable declarations
5.Function statements
6.Return statement
all the six elements are grouped into two parts, namely
function header(frist three elements) and
function body(second three elements)
A general format of a function definition to implement these two parts is given below
function_type function_name(Parameter list)
{
local variable declarations;
executable statements;
-------------------------
-------------------------
return statement;
}

or

return_type or data type function name(data type argument1,data type argument2…data type argument)
{
local variable declarations;
executable statements;
-----------------------
return statement;
}

Example:
int add(int x, int y)
{
int z;
z = x+y;
return(z);
}

Write a c program to add the two numbers in different ways using functions

No arguments and No return values;


#include<stdio.h>
#include<conio.h>
void add(void);
void main ( )
{
clrscr();
add();
getch();
}
void add(void)
{
int a,b,c;
printf(“\n Enter a,b values \n”);
scanf(“%d%d”,&a,&b);
c = a+b;
printf(“\n C = %d”,c);
}

Arguments with return values


#include<stdio.h>
#include<conio.h>
int add(int, int );
void main ( )
{
int a,b,c;
clrscr();
printf(“\n Enter a,b values \n”);
scanf(“%d%d”,&a,&b);
c = add(a,b);
printf(“c = %d”,c);
getch();
}
int add(int x, int y)
{
int z;
z = x+y;
return(z);
}
Arguments with no return values
#include<stdio.h>
#include<conio.h>
void add(int, int);
void main()
{
int a,b;
clrscr();
printf(“\n Enter a,b values \n”);
scanf(“%d%d”,&a,&b);
add(a,b);
getch();
}
void add(int x, int y)
{
int c;
c = x+y;
printf(“\n C = %d”,c);
}
No Arguments with Return values
#include<stdio.h>
#include<conio.h>
int add(void);
void main()
{
int c;
clrscr( );
c= add( );
printf(“\n c =%d”,c);
getch( );
}
int add(void)
{
int a,b, x;
printf(“\n Enter a,b values \n”);
scanf(“%d%d”,&a,&b);
x = a+b;
return(x);
}

Recursion: The process of calling a function by itself is called recursion and the function which calls itself is
called recursive function. Recursion is used to solve various mathematical problems by dividing it into smaller
problems.

Write a program to find the factorial using recursion


#include<stdio.h>
#include<conio.h>
long factorial(int);
int main()
{
int n;
long f;
clrscr();
printf(“\n Enter an integer to find its factorial \n”);
scanf(“%d”,&n);
if(n<0)
printf(“\n factorial of negative integers is not defined \n”);
else
{
f = factorial(n);
printf(“ %d! = %ld\n”,n,f);
}
return(0);
}
long factorial(int n)
{
if(n==0)
return 1;
else
return(n*factorial(n-1));
}
output:
Enter an integer to find its factorial
8
8! = 40320
Advantages
1. Reduce unnecessary calling of function
2.One can solve problems in easy way while its iterative solution is very big and complex.
Disadvantages
1. It is very difficult to trace(debug and understand)
2. Recursion uses more processor time.
3. Recursion takes a lot of stack space.

Argument passing
the process of information interchange between the calling function and called function
is known as parameter passing. These are two types.
a)call by value
b)call by reference

Call by value
when an argument is passed by value, the data item is copied to the function.Thus, any alteration
made to the data item with the function is not carried over into the calling routine. Hence it is restricted to return
only one value to the calling function.
void swap(int,int);
void main()
{
int a=10,b=20;
swap(a,b);
printf(“\n a = %d \t b = %d”,a,b);
}
void swap(int x,int y)
{
int t;
t = x;
x= y;
y = t;
printf(“\n x = %d \t y = %d”,x,y);
}
output: x =20 y =10
a =10 b=20
call by reference
When an argument is passed by reference , the address of a data item is passed to the
function the variables which are receiving the address are pointer variables. The contents of that address can be
accessed freely, either within the function or within the calling routine. Thus pointers provide a way to return
multiple data items from a function via function arguments.
void swap(int *,int *);
void main()
{
int a=10,b=20;
swap(&a,&b);
printf(“%d%d”,a,b);
}
void swap(int *x, int *y)
{
int t;
t = *x;
*x = *y;
*y = t;
}
output: 20 10

Pointer: Pointer is a memory variable that stores memory address. It will strores another variable address. It is
denoted by * pointer symbol
Features: 1.Pointers saves the memory space
2.Execution time with pointers is faster why because directly it is accessing memory locations.
3.Pointers are used in data structures also
Write a program to display the address of the variable
#include<stdio.h>
#include<conio.h>
void main()
{
int number;
clrscr();
printf(“\n Enter any number \n”);
scanf(“%d”,&number);
printf(“\n Address of the variable number = %u”,&number);
printf(“\n value of the number = %d”,number);
getch();
}
Output: Enter any number
18
address of the variable number = 25632
Value of the number = 18

Write a program to display the address of different variables together with their values
#include<stdio.h>
#include<conio.h>
void main()
{
int i = 20;
float j=90.9;
double k=899.99;
clrscr();
printf(“\n value of i = %d and address of i = %u”,i,&i);
printf(“\n value of j = %f and address of j = %u”,j,&j);
printf(“\n value of k = %lf and address of k = %u”,k,&k);
getch();
}
output: Value of i = 20 and address of i = 32362
Value of j =90.9 and address of j = 34562
Value of k = 899.99 and address of k = 42656

Write a program to display the value of variable and its location using pointer
#include<stdio.h>
#include<conio.h>
void main()
{
int v=10,*p;
clrscr();
p = &v;
printf(“\n Adress of v= %u”,&v);
printf(“\n Value of v through normal variable = %d”,v);
printf(“\n Value of V through poiner = %d”,*p);
printf(“\n Address of v through pointer variable = %u”,p);
getch();
}
output: address of v = 56456
value of v through normal variable = 10
value of V through pointer = 10
Address of v Through pointer variable = 56456

storage allocation or memory allocation:

Memory allocation is two types.1) Static memory allocation 2)Dynamic memory


allocation. In static memory allocation, memory is allocated to the variables and arrays at compile time.allocating
memory to the objects at the runtime is called dynamic memory allocation. To access the dynamic data pointers
are used.
Memory management funtions
four types of functions have been defined for dynamic memory allocation.
1)malloc 2)calloc 3) Realloc 4) Free

First three functions are used to allocate memory and the last one is to free the memory that
is not in use.All these functions are included in the standard library function, stdlib.h

malloc: Malloc function is used to allocate block of memory and return void pointer ,the address of first byte in
the memory.
Calloc:Calloc function is used to allocate memory dynamically for arrays. The only difference between calloc
and malloc is that, calloc sets memory to null character but malloc doesn’t.
Realloc: Realloc resizes the block of memory either deleting or extending the memory block.It allocates new
block, if the existing block can not be extended and copies the existing memory allocation to the new block and
deletes the old one.
Free: Free function is used to free the memory allocation allocated by malloc,calloc and realloc when they are no
longer in use and the memory block can be reused later.
pointer to function
In C language every variable has an address except register variables. We can access the
address of the variable using pointers. C functions also have an address. We invoke the function using its address
consider the following example.
Write a program to display address of user defined function.
#include<stdio.h>
#include<conio.h>
int show();
void main()
{
clrscr();
show();
printf(“%u”,show);
getch();
}
int show()
{
printf(“\n Address of function show is “);
return(0);
}
output: Address of function show is 650
Write a program to call function using pointer.
#include<stdio.h>
#include<conio.h>
int show(); /* function prototype */
void main()
{
int (*p) (); /* pointer declaration */
p = show; /* Assign address of show to pointer variable */
(*p) (); /* function call using pointer */
printf(“%u”,show);
getch();
}
int show()
{
clrscr();
printf(“\n Address of function show is “);
}
output
Address of function show is 531
Expressions involving pointers:
Like other variables, pointer variables can be used in expressions.
Write a program to perform different arithmetic operations using pointers
#include<stdio.h>
#include<conio.h>
void main()
{
int a=25,b=10,*p,*j;
p = &a;
j = &b;
clrscr();
printf(“\n Addition a+b = %d”,p+b);
printf(“\n substraction a-b = %d”,*p-b);
printf(“\n Product a*b = %d”,*p**j);
printf(“\n Division a/b = %d”,*p/*j);
printf(“\n a mod b = %d”,*p % *j);
getch();
}
output:
addition a+b = 35
substraction a-b = 15
product a*b = 250
Divison a/b = 2
a mod b = 5
Storage classes
To fully define a variable, it is required to define not only its type but also its storage class.
Storage classes in C divided into four types.
Automatic storage class
static storage class
 Register storage class
Extern storage class
Automatic storage class
If we don’t specify the storage class, C compiler assumes default storage class depending
upon the content of the variable. The default storage class in C is auto. Storage class of a variable gives
information about the location of the variable in which it is stored.
By defining a variable as automatic storage class, it is stored in the memory. The default
value of the variable will be garbage value.
Example: auto int a,b;
In the above example, the variables a and b declared as integer type and auto. The keyword
auto is not mandatory because the default storage class in c is auto.
Write a program using automatic storage class
#include<stdio.h>
#include<conio.h>
void main()
{
auto int a,b;
a = 5;
printf(“ a = %d b = %D”,a,b);
fun();
}
void fun()
{
auto int c= 10;
printf(“\n c = %d”,c);
}

output: 5 1234
10

In the above program a,b variables are declared as integer and auto. Variable a is initialized
but not variable b. The program displays a and c values. but displays garbage value for b.
Register storage class
When a varaiable is declared as register, it is stored in the CPU registers. To define a variable
as register storage class, the keyword register is used.If CPU can not strore the variables in CPU registers, then
the variables are assumed as auto and stored in the memory.
/* program to declare variable as register */
void main()
{
register int j=1;
do
{
printf(“%d\t”,j);
j++;
}
while(j<=10);
output: 1 2 3 4 5 6 7 8 9 10
Static Storage class
When a variable is declared as static, it is stored in the memory. The default value of the
variable will be zero.
/* program for static storage class */
#include<stdio.h>
#include<conio.h>
void main()
{
static int b;
int a;
printf(“\n a = %d b = %d”,a,b);
getch();
}
output: a = 1020 b = 0
In the above program the variables a and b are declared as integer. b is static variable.
Value of variable a is garbage value and b value is zero because b is defined as static.
Extern storage class
When a variable is declared as extern, it is stored in the memory. The default value is
initialized to zero. To define a variable as extern storage class the keyword extern is used. An extern variable is
also called as global variable.
#include<stdio.h>
#include<conio.h>
void main()
{
extern int e;
func1();
func2();
printf(“\n e = %d”,e);
}
int e =20;
func1()
{
extern int e;
printf(“ e = %d”,e);
}
func2()
{
extern int e;
printf(“\n e = %d”,e);
}
output:
e=20
e=20
e=20
Structures:
Structure is a collection of one or more variables of different data types grouped together under one single name.
structure syntax:
struct structurename
{
datatype variablename1;
datatype variablename2;
----------------------------
----------------------------
};
struct structurename objectname;
or
struct structurename
{
datatype variablename1;
datatype variablename2;
----------------------------
}objectname;
Example:
struct book
{
char name[30];
int pages;
float price;
};
struct book b1;

or

struct book
{
char name[30];
int pages;
float price;
}b1;

Write a program to declare structure and assign the values to the structure members.
#include<stdio.h>
#include<conio.h>
void main()
{
struct book
{
char name[30];
int pages;
float price;
};
struct book b1= {“c++”,600,1200};
clrscr();
printf(“ \n Book Name = %s”,b1.name);
printf(“\n Book Pages = %d”,b1.pages);
printf(“\n Book Price = %f”,b1.price);
getch();
}
output:
Book Name = c++
Book Pages= 600
Book Price =1200

Write a program to declare structure and assign the values using scanf function
#include<stdio.h>
#include<conio.h>
void main()
{
struct book
{
char name[30];
int pages;
float price;
};
struct book b1;
clrscr();
printf(“ \n Enter Book details \n”);
scanf(“%s%d%f”,b1.name,b1.pages,b1.price);
printf(“\n Book Name: %s”,b1.name);
printf(“\n Book Pages:%d”,b1.pages);
printf(“\n Book price:%f”,b1.price);
getch();
}

Output:
Enter Book details
c++, 1800, 1600
Book Name:c++
Book Pages:1800
Book Price:1600

Unions: Union is a collection of one or more variables of different data types grouped together under single
name.
Syntax: Union union_name
{
datatype variablename1;
datatype variablename2;
----------------------------
};
Union union_name object name;

Union is a variable, which is similar to the structure. It contains number of members like
structure but it holds only one object at a time. In the structure each member has its own memory location where
as, member of union have same memory locations. It can accommodate one member at a time in a single area of
storage. Union also contains members of types int,float,long arrays pointers etc. It allocates fixed specific bytes
of memory for access of data types irrespective of any data type.
The Union requires bytes that are equal to the number of bytes required for the largest
members. For example the union contains char,integer and long integer then the member of bytes reserved in the
memory for union is 4 bytes.

Write a program to find size of union and number of bytes reserved for it.

void main()
{
union result
{
int marks;
char grade;
};
struct res
{
char name[15];
int age;
union result perf;
}data;
clrscr();
printf(“\n size of union: %d”,sizeof(data.perf));
printf(“\n size of structure:%d”,sizeof(data));
getch();
}

output:
Size of union:2
Size of structure:19
Strings:
The string is a one-dimensional array of characters. For example “computer” is a string of 8
characters. However an N character array contains(n+1) array element. Because each one dimensional character
array(string) ends with a null character(\0).
Declaration and initialization

Write a program to read the string and print the string


#include<stdio.h>
#include<conio.h>
void main()
{
char letters[10];
printf(“\n Enter string \n”);
scanf(“%s”,letters);
printf(“%s”,letters);
getch();
}
output: Enter String
Hello
Hello

Write a program to assign the string and print character by character.


#include<stdio.h>
#include<conio.h>
void main()
{
char name[10] = {‘r’,’a’,’m’,’a’,’\0’};
int i;
clrscr();
for(i=0;name[i]!=’\0’;i++)
printf(“%c”,name[i]);
getch();
}
output: rama

Two dimensional character array:


These are arrays of arrays. Two dimensional character array consists of strings as individual
elements.
Write a program for reading and writing strings.
#include<stdio.h>
#include<conio.h>
void main()
{
int n,i;
char name[10][10];
clrscr();
printf(“\n Enter how many strings \n”);
scanf(“%d”,&n);
printf(“\n Enter strings \n”);
for(i=0;i<n;i++)
scanf(“%s”,name[i]);
printf(“\n The list are \n”);
for(i=0;i<n;i++)
printf(“\t%s”,name[i]);
getch();
}

output: Enter strings


hello
hai
bye
the list are hello hai bye
C provides string handling functions to peform the operations like copying ,finding length of a string, comparing
etc.
String handling functions:

strcpy()-function:It copies one string to the other


Syntax: strcpy(string1,string2);
The function copies the second string into first string. After the operation string1 and string2 contents are same.
Write a program to copy one string into other string
#include<stdio.h>
#include<conio.h>
#include<string.h>
void main()
{
char name1[20],name2[20];
clrscr();
printf(“\n Enter the first string \n”);
scanf(“%s”,name1);
printf(“\n Enter the second string \n”);
scanf(“%s”,name2);
strcpy(name1,name2);
printf(“\n name1= %s \n name2 = %s”,name1,name2);
getch();
}
output:
Enter the first string
Rama
Enter the second string
Krishna
name1 = Krishna
name2 = Krishna
strcmp function: This compares two strings character by character and returns one othree values{-1,0,1}.Its
syntax s as follows
strcmp(string1,string2);
it return negative value if the ASCII value of the character of the first string is less than the second string. It
returns zero if both strings are equal. It return positive value if the ASCII value of the character of the first string
is greater than that of second string.
Write a program to compare two strings
#include<stdio.h>
#include<conio.h>
#include<string.h>
void main()
{
char name1[20],name2[20];
int p;
clrscr();
printf(“\n Enter the first string \n”);
scanf(“%s”,name1);
printf(“\n Enter the second string \n”);
scanf(“%s”,name2);
p = strcmp(name1,name2);
if(p==0)
printf(“\n both strings are same \n”);
else
printf(“\n Both strings are not same \n”);
getch();
}
output
Enter the first string
Madam
Enter the second string
Madam
both strings are same
strcat( ) – function
This function is used to contatenate two strings i.e it appends one string at the end of other specified string.
syntax: strcat(string1,string2);

#include<stdio.h>
#include<conio.h>
#include<string.h>
void main()
{
char name1[20],name2[20];
int p;
clrscr();
printf(“\n Enter the first string \n”);
scanf(“%s”,name1);
printf(“\n Enter the second string \n”);
scanf(“%s”,name2);
strcat(name1,name2);
printf(“\n name1= %s \t name2 = %s”,name1,name2);
getch();
}
output
Enter the first string
Rama
Enter the second string
Krishna
name1 = Rama Krishna name2 = Krishna
strlen()-function
It returns the number of characters in the string(i.e string length). Here the length does not
include the ‘\0’(NULL character).
Write a program to find the length of a string
#include<stdio.h>
#include<conio.h>
#include<string.h>
void main()
{
char name1[20];
int p;
clrscr();
printf(“\n Enter the first string \n”);
scanf(“%s”,name1);
p = strlen(name1);
printf(“\n string length = %d”,p);
getch();
}
output
Enter the string
Kumar
string length is 5
strlwr()-function: It converts any upper case letters in the string to the lower case letters.
#include<stdio.h>
#include<conio.h>
#include<string.h>
void main()
{
char name1[20];
clrscr();
printf(“ Enter the first string \n”);
scanf(“%s”,name1);
strlwr(name1);
printf(“\n %s”,name1);
getch();
}
output: Enter the first string
HYDERABAD
hyderabad
strupr()-function: It converts any lower case letters in the string to the upper case letters.
#include<stdio.h>
#include<conio.h>
#include<string.h>
void main()
{
char name1[20];
clrscr();
printf(“ Enter the first string \n”);
scanf(“%s”,name1);
strupr(name1);
printf(“\n %s”,name1);
getch();
}
output: Enter the first string
hyderabad
HYDERABAD

Command line arguments


An executable program that performs a specific taks for operating system is called as
command.Some arguments are to be associated with the commands hence these arguments are called as
command line arguments. Thse associated arguments are passed to the program.
In c language every program starts with a main function and that it marks the beginning of the
program. We have not provided any arguments so far in the main function. Here we can make arguments in the
main like other functions. The main function can receive two arguments and they are (1) argc (2) argv
The information contained in the command line is passed on to the program through these arguments when the
main function is called up by the system.
1.Argument argc: An argument argc counts total number of arguments passed from command prompt. It
returns a value which is equal to total number of arguments passed thrgouh the main function.
2.Argument argv: It is a pointer to an array of character strings which contains names of arguments. Each word
is an argument.

Below the program illustrate the command line arguments.


Write a program to display number of arguments and their names
#include<stdio.h>
#include<conio.h>
void main(int argc, char *argv[])
{
int x;
clrscr();
printf(“\n total number of arguments are %d”,argc);
for(x=0;x<argc;x++)
printf(“%s\t”,argv[x]);
getch();
}
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.

1) compile the program


2) make its exe file(executable file)
3)switch to the command prompt.
4)make sure that the exe file is available in the current directory
5) type the following line
c:turboc2\Bin>command.exe A B C

In the above example command.exe is an executable file and “ A B C” are taken


as arguments. The total number of arguments including the program file name are 4.

You might also like