0% found this document useful (0 votes)
10 views21 pages

Unit-Iv Psc-Ug

This document covers key concepts in C programming related to functions, including their declaration, definition, and the advantages of using functions for modular programming. It also discusses data types such as structures, unions, and enumerated types, as well as storage classes and variable scope. Additionally, it explains recursion, parameter passing methods, and provides examples of sorting arrays and calculating GCD using recursive functions.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
10 views21 pages

Unit-Iv Psc-Ug

This document covers key concepts in C programming related to functions, including their declaration, definition, and the advantages of using functions for modular programming. It also discusses data types such as structures, unions, and enumerated types, as well as storage classes and variable scope. Additionally, it explains recursion, parameter passing methods, and provides examples of sorting arrays and calculating GCD using recursive functions.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 21

Problem Solving in C

UNIT IV
Functions: Introduction – using functions – Function
declaration/ prototype – Function definition – function call –
return statement – Passing parameters – Scope of variables –
Storage Classes – Recursive functions.
Structure, Union, and Enumerated Data Types: Introduction –
Nested Structures – Arrays of Structures – Structures and
Functions– Union – Arrays of Unions Variables – Unions inside
Structures – Enumerated Data Types.

Introduction: C program can be broken into one or more modules


known as functions. Each function can be developed independently
without depending on others. Every function is designed to perform
a well defined task. Below figure shows the interaction of two
functions i.e. main() calls function1().

Therefore main() is the calling function and function1() is the called


function. When executing main() a function call is encountered
instead of executing next statement in main function the control of
execution jumps to the function1() and executes it and return back
to main(). Now the execution of main continues.

Advantages of using functions:


1. It facilitates top-down modular programming.
2. Using functions we can easily write, read, modify and debug a
lengthy program.
3. The length of a program can be reduced by by using functions
at appropriate places.

Function declaration/ prototype: When user is using a


predefined function in the main() the corresponding header file is
included. If user is using a user defined function in the main() the
function declaration/prototype statement is to be included before the
main function. Function prototype tells compiler about number of
parameters function takes, data-types of parameters and return type
of function. By using this information, compiler cross checks function
parameters and their data-type with function definition and function
call. If we ignore function prototype, program may compile with
warning, and may work properly.
The general form of a function is

Krishnaveni Degree College :: Narasaraopet Page No. : 1


Problem Solving in C
UNIT IV
ret-type function-name(data types of parameter list);
Ex:
float sum(float, float);

Function Definition: A function is a fundamental building block of


the C language. Every program should contain at least one function
i.e., main () function. Function is a subprogram of one or more
statements that performs a specific task when called. To reduce the
complexity of a program while coding, debugging and testing a
lengthy program is divided into sub-programs or modules. Each such
module or a subprogram is a function.
The General Form of a Function: A function definition consists of two
parts. They are
1. Function header(first line of the function)
2. Function body
The general form of a function is
ret-type function-name(parameter list)
{
body of the function
}
1. The ret-type specifies the type of data that the function returns. A
function may return any type of data except an array.
2. The function-name specifies the name of the user defined
function.
3. The parameter list is a comma-separated list of variable names
and their associated types.
4. The body of the function contains the actual code to perform a
specific task. The body of the function is enclosed within Opening
brace ”{ “ and closing brace “}”. Along with the actual code the
function body also contains a return Statement. A return
statement is optional.
5. Return statement uses the keyword return which causes
termination of function and returns values to calling function.
When return statement is not present the closing brace causes
termination of function.

Function call: When executing main() a function call is


encountered then the control of execution instead of executing next
statement in main function the control of execution jumps to the
called function and executes it and return back to main(). Now the
execution of main continues.
The general form of a function call is
function-name(parameter list);
Ex:
Krishnaveni Degree College :: Narasaraopet Page No. : 2
Problem Solving in C
UNIT IV
sum( a, b);

return statement: The return statement is used to terminate the


execution of a function and returns control of execution to the
calling function.
The general form of a function call is
return <expression>;
Ex:
return c;

Passing Parameters: When the function is called the calling


function passes parameters to the called function. The parameters
used in the function call are called actual parameters and the
parameters used in the function definition are called formal
parameters. Depending on how data is exchanged between actual
and formal parameters there are two types of parameter passing in
C language . They are
1. Call by Value
2. Call by Reference
Call by Value: In Call by value mechanism the values of actual
parameters are assigned to formal parameters. Changes made to
the formal parameters are not effect the actual parameters.
/* Program to find the sum of the digits of a given number */
#include<stdio.h>
#include<conio.h>
int sum_dig(int);
void main()
{
int num,sum;
printf("Enter any number to find sum of digits:");
scanf("%d",&num);
sum=sum_dig(num);
printf("The sum of digits of %d number is %d\n",num,sum);
getch();
}
int sum_dig(int n)
{
int rem,sum=0;
while(n>0)
{
rem=n%10;
sum=sum+rem;
n=n/10;

Krishnaveni Degree College :: Narasaraopet Page No. : 3


Problem Solving in C
UNIT IV
}
return sum;
}
Call by Reference: In Call by reference mechanism the address of
actual parameters are assigned to formal parameters. Changes
made to the formal parameters will effect the actual parameters.

/* Program to swap two number */


#include<stdio.h>
#include<conio.h>
void swap_dig(float *, float *);
void main()
{
float num1,num2;
printf("Enter any two number to find sum of digits:");
scanf("%f%f",&num1, &num2);
swap_dig(&num1, &num2);
printf("The numbers after swaping are %5.2f and %5.2f \
n",num1,num2);
getch();
}
void swap_dig(float *n1, float *n2)
{
float temp;
temp=*n1;
*n1=*n2;
*n2=temp;
return ;
}

Scope of variables: The scope of an variable specifies the region


of the source program where a variable can be accessed. There are
four types of scope used in C. They are
1. Block Scope
2. Function Scope
3. Program Scope
4. File Scope
Block Scope: A Block is a set of statements enclosed within left and
right braces { and } . Blocks may be nested in C i.e a block may
contain other blocks inside it. A variable declared in a block is
accessible in the block and all inner blocks of that block, but not
accessible outside the block. If an inner block declares a variable
with the same name as the variable declared by the outer block,

Krishnaveni Degree College :: Narasaraopet Page No. : 4


Problem Solving in C
UNIT IV
then the visibility of the outer block variable ends at the point of
declaration by inner block.
Function Scope: Function Scope is also called as Local Scope.
Variables that are declared inside a function are called local
variables and are said to have local scope. These local variables can
only be used within the function in which these are declared. Local
variables are created when the function is called and then they get
destroyed when the function is terminated.
Program Scope: Program Scope is also called as Global Scope.
Variables that are defined outside of all the functions and are
accessible throughout the program are called global variables and
are said to have global scope. Once declared, these can be accessed
and modified by any function in the program. We can have the same
name for a local and a global variable but the local variable gets
priority inside a function.
File Scope: A variable with file scope can be accessed by any
function within a single file. To declare a file scoped variable, simply
declare a variable outside of a function but use the static keyword.

Storage Classes: Every variable in C is associated with a data type.


In addition to data type, C associates a storage class also. A storage
class associated with a variable specifies some properties such as
scope and lifetime. The scope of an variable specifies the region of
the source program where a variable cab be accessed. The lifetime
of the variable specifies the time period during which the memory
is allocated to that variable.The storage class of a variable dictates
how, when and where storage will be allocated for the variable. C
supports four storage classes. They are
1. auto
2. register
3. extern
4. static
These specifiers tell the compiler how to store the subsequent
variable.
 Syntax: storage class type var_name;
 Example: auto int i;
auto : All the variables with in a function by default belong to the
automatic storage class. The keyword auto identifies a variable as
automatic. The scope of the automatic variable is limited to the
function or block in which they appear. They are created when the
function is called and destroyed when the function is exited. The
memory location is allocated to a auto variable when the function is
called and gets de-allocated when the function is exited. They are

Krishnaveni Degree College :: Narasaraopet Page No. : 5


Problem Solving in C
UNIT IV
recreated when the function is called again. Automatic variables are
not initialized to any value when they are created. They usually start
with garbage value. Automatic variables have two pleasant aspects
1. Memory space used economically.
2. Local scope protect us from affection them in
advertently in other function.
static: The static variables are defined within a function and they
have the same scope of the rules of automatic variables but the
lifetime is entire program i.e contents of static variables will be
retained throughout the program. Static keyword is used to define
the storage class . static variables are initialized to zero.
/* Program to demonstrate static variable*/
#include<stdio.h>
#include<conio.h>
long int fact(int );
void main()
{
int n;
clrscr();
printf("Enter any number to find factorial");
scanf("%d",&n);
printf("The factorial of %d is %d\n",n,fact(n));
getch();
}
long int fact(int n1)
{
static int cnt;
cnt++;
printf("The fact function is called %d time\n",cnt);
if ((n1==0) ||(n1==1))
return 1;
else
return n1*fact(n1-1);
}
extern : The variables that are declared before the function main()
are existing for all the functions inside the program. So these
variables are called global variables. The extern declaration of the
variables makes the variables to be available even for the external
functions that are called from the program. External variables are
created when they are defined and are permanently available
thereafter. Thus their scope is the entire program and their extent
from the time of creation till the termination of the program.

Krishnaveni Degree College :: Narasaraopet Page No. : 6


Problem Solving in C
UNIT IV
register: All the computers have few memory locations on the
microprocessor chip itself. These memory locations are known as
registers. Storage and retrieved of data from a register can be done
by a program much faster than from a location in the main memory
of the computer. Register storage can be specified only to local
variables not to global variables, register variables are ideal for use
where there is a repeated use of that variable such as in loops. The
scope and life of a register variable is similar to that of automatic
variables. Suppose some of the variables have been declared as
register and if these variables are not the correct data type such as
char or int and if there are not enough registers available, then the C
compiler will automatically ignore the register data type and keeps
them in the memory. It will be treated as automatic variables.

Recursive Functions: Recursive functions are effective tools for


programming complex problems. If a function calls itself then such a
function is called recursive function.
/* Program to find the g.c.d of two numbers using recursion */
#include<stdio.h>
#include<conio.h>
int gcd(int m,int n);
void main()
{
int temp, m,n;
clrscr();
printf("Enter any two values to find gcd :");
scanf("%d%d",&m,&n);
if(m<n)
{
temp=m;
m=n;
n=temp;
}
printf("GCD of %d and %d is %d\n",m, n, gcd(m,n));
getch();
}
int gcd(int m1,int n1)
{ int rem;
if(m1==n1)
return m1;
else
if((m1%n1)==0)
return n1;

Krishnaveni Degree College :: Narasaraopet Page No. : 7


Problem Solving in C
UNIT IV
else
return gcd(n1,m1%n1);
}
/*Program to print n fibonancci number using recursion */
#include<stdio.h>
#include<conio.h>
int fib(int);
void main()
{
int n,i ;
clrscr();
printf("Enter how many fibonancci numbers: ");
scanf("%d",&n);
printf("%d Fibonacci numbers are as follows..\n", n);
for ( i = 0 ; i < n ; i++ )
printf("%d\t", fib(i));
getch();
}
int fib(int i1)
{
if ( i1 == 0 )
return 0;
else if ( i1 == 1 )
return 1;
else
return ( fib(i1-1) + fib(i1-2) );
}
Types of recursion: The process of calling a function by itself is
called recursion and the function which calls itself is called recursive
function. Recursive functions can be classified as
1. Direct Recursive and Indirect Recursive
2. Non-tail Recursive and Tail Recursive
3. Linear Recursive and Tree Recursive
Direct Recursive: A function is said to be direct recursive if it calls
itself directly.
Non-tail Recursive: A recursive function is non-tail recursive when
recursive call is not the last thing executed by the function.
Tail Recursive: A recursive function is tail recursive when recursive
call is the last thing executed by the function.
Linear recursive: A linear recursive function is a recursive function
that only makes a single call to itself each time the function runs.
The factorial function is a good example of linear recursion.

Krishnaveni Degree College :: Narasaraopet Page No. : 8


Problem Solving in C
UNIT IV
Tree Recursive: A recursive function is said to be tree recursive or
non-linear recursive if the pending operation makes another
recursive call to the function. The Fibonacci function is a good
example of tree recursion.

Basis for comparison Recursion Iteration


Basic The statement in a Allows the set of
body of function, calls instructions to be
the function itself. repeatedly executed.
Condition If the terminating If the control
condition is never condition in the
reached it leads to iteration statement
infinite recursion. never become false,
it leads to infinite
iteration.
Infinite Repetition Infinite recursion can Infinite loop uses CPU
crash the system. cycles repeatedly.
Stack The stack is used to Does not uses stack.
store the set of new
local variables and
parameters each
time the function is
called.
Overhead Recursion possesses No overhead of
the overhead of repeated function
repeated function call.
calls.
Speed Slow in execution. Fast in execution.
Size of Code Recursion reduces Iteration makes the
the size of the code. code longer.

One dimensional array for inter-function communication: In C,


passing an entire array as an argument to a function is not possible.
However, pass a pointer to an array by specifying the array's name
without an index.
/* Program to sort an array using bubble sort */
/* Program demonstrates passing one-dimensional array to function
*/
#include<stdio.h>
#include<conio.h>
void bsort(float[], int);
void main()
{

Krishnaveni Degree College :: Narasaraopet Page No. : 9


Problem Solving in C
UNIT IV
float array[20];
int i,size;
clrscr();
printf("Enter array size\n");
scanf("%d",&size);
printf("Enter any %d elements\n",size);
for(i=0;i<size;i++)
scanf("%f",&array[i]);
bsort(array, size);
printf("After sorting, the elements are\n");
for(i=0;i<size;i++)
printf("%.2 f\t ",array[i]);
getch();
}
void bsort(float a[], int s)
{
int temp, i, j;
for(i=1;i<=s-1;i++)
for(j=0;j<s-i;j++)
if(a[j]>a[j+1])
{
temp = a[j];
a[j] = a[j+1];
a[j+1] = temp;
}
return ;
}
Two Dimensional Arrays for inter-function communication:
When a two-dimensional array is used as an argument to a function,
only a pointer to the first element is actually passed. However, the
parameter receiving a two-dimensional array must define at least
the size of the rightmost dimension. (You can specify the left
dimension if you like, but it is not necessary.) The rightmost
dimension is needed because the compiler needs to know the length
of each row if it is to index the array correctly.
/* Program to add and multiply two matrices */
/* Program demonstrates passing two-dimensional array to function
*/
#include<stdio.h>
#include<conio.h>
void add_mat(float a[][3],float b[][3], int, int);
void mul_mat(float a[][3],float b[][3], int, int, int);
void main()

Krishnaveni Degree College :: Narasaraopet Page No. : 10


Problem Solving in C
UNIT IV
{
int i,j,m,n,p,q;
float a[3][3],b[3][3];
clrscr();
printf("\nenter order of first matrix");
scanf("%d%d",&m,&n);
printf("\nenter order of second matrix");
scanf("%d%d",&p,&q);
printf("\nenter the elements of first matrix");
for(i=0;i<m;i++)
for(j=0;j<n;j++)
scanf("%f",&a[i][j]);
printf("\nenter the elements of second matrix");
for(i=0;i<m;i++)
for(j=0;j<n;j++)
scanf("%f",&b[i][j]);
if((m==p)&&(n==q))
add_mat(a, b, m, n);
else
printf("\naddition is not possible");
if(n==q)
mul_mat(a,b,m,n,q);
else
printf("\nmultiplication is not possible");
getch();
}
void add_mat(float a[][3], float b[][3], int m, int n)
{
int i, j;
float c[3][3];
for(i=0;i<m;i++)
for(j=0;j<n;j++)
c[i][j]=a[i][j]+b[i][j];
printf("the resultant matrix after addition is \n");
for(i=0;i<m;i++)
{
for(j=0;j<n;j++)
printf("%5.2f\t",c[i][j]);
printf("\n");
}
return;
}
void mul_mat(float a[][3], float b[][3], int m, int n, int q)

Krishnaveni Degree College :: Narasaraopet Page No. : 11


Problem Solving in C
UNIT IV
{
int i, j,k;
float c[3][3];
for(i=0;i<m;i++)
for(j=0;j<q;j++)
{
c[i][j]=0;
for(k=0;k<n;k++)
c[i][j]+= a[i][k]*b[k][j];
}
printf("the resultant matrix after multiplication is \n");
for(i=0;i<m;i++)
{
for(j=0;j<q;j++)
printf("%5.2f\t",c[i][j]);
printf("\n");
}
return;
}

Strings for inter-function communication: When a string is used


as an argument to a function, the name of a string is passed as an
arguments which gives the address of the first element in the string.
/* C program to count number of characters, words and lines using
functions*/
#include<stdio.h>
#include<conio.h>
void cwlch(char[]);
void main()
{
char para[100];
printf("Enter any parahgraph\n");
scanf("%[^'$']s",para);
cwlch(para);
getch();
}
void cwlch(char para[])
{
char ch;
int i,cntch, words, lines;
cntch = words = lines = 0;
i=0;
while ((ch = para[i++]) != '\0')

Krishnaveni Degree College :: Narasaraopet Page No. : 12


Problem Solving in C
UNIT IV
{
if (ch == ' ')
words++;
else
if (ch == '\n' )
{
words++;
lines++;
}
else
cntch++;
}
printf("Total characters = %d\n", cntch);
printf("Total words = %d\n", words);
printf("Total lines = %d\n", lines);
}

Structure Definition: A structure is a collection of one or more


variables of different data types, grouped under a single name. The
elements that make up the structure are called members and they
are also referred as fields. The keyword struct tells the compiler that
a structure is being declared.
Syntax:
struct struct_name
{
data_type member1;
data_type member2;
data_type member3;
};
The declaration of a structure must be terminated by a semicolon.
After structure is defined, struct_name can be used to declare
structure variables. When structure is defined no space is allocated
to it. It is just a user defined data type.
Example:
struct student
{
int rollno;
char name[40];
float marks;
};
In the above example student is the structure name and rollno,
name, and marks are members of the structure.

Krishnaveni Degree College :: Narasaraopet Page No. : 13


Problem Solving in C
UNIT IV
Declaring Structure variables: After structure is defined,
structure variables can be declared by using the keyword struct,
structure name and variable name followed by a semicolon.
Syntax: struct struct_name var_name;
Example: struct student s;
When a structure variable is declared, the compiler automatically
allocates sufficient memory to accommodate all of its members.
Declaring structure variables can be combined with structure
definition as follows
Example:
struct student
{
int rollno;
int marks;
} s;

Accessing Structure Members: Individual members of a structure


are accessed through the use of the dot(.) operator.
Syntax: structure variable-name.member-name
Example : s1.rollno

Structure Intialization: Structure variable can be initialized during


compile time.
Syntax: structure_var_name = { value of member 1, value of
member 2,…}
Example: s = {101, 95};
/* Program that demonstrates the use of structures */
#include <stdio.h>
#include<conio.h>
void main()
{
struct student
{
int rollno;
int marks;
} s1, s2={102, 95};
clrscr();
printf("Enter rollno and marks of student: ");
scanf("%d%d", &s1.rollno, &s1.marks);
printf("Details of student 1 are as follows\n");
printf(" RollNo: %d\n", s1.rollno);
printf(" Marks: %d\n", s1.marks);
printf("Details of student 2 are as follows\n");

Krishnaveni Degree College :: Narasaraopet Page No. : 14


Problem Solving in C
UNIT IV
printf(" RollNo: %d\n", s2.rollno);
printf(" Marks: %d\n", s2.marks);
getch();
}
Structure Assignments: The information contained in one
structure can be assigned to another structure of the same type
using a single assignment statement. No need to assign the value of
each member separately.
Syntax: struct_var1 = struct_var2
Example:
struct student s1, s2;
s1 = {101, “Sai”, 95};
s2=s1;

Arrays of Structures: Structures are often arrayed. To declare an


array of structures, first define a structure and then declare an array
variable of that type. For example, to declare a 100-element array of
type student defined earlier, write
struct student s[100];
To access a specific structure, index the array name. For example, to
print the rollno of structure 3, write
printf("%d", s[2].rollno);
/* Program that demonstrates the use of array of structures */
#include <stdio.h>
#include<conio.h>
void main()
{
struct student
{
int rollno;
int marks;
} s[2];
int i,n;
clrscr();
printf("Enter how many students: ");
scanf("%d ", &n);
printf("Enter %d students rollno and marks one by one\n", n);
for(i=0;i<n;i++)
scanf("%d%d", &s[i].rollno, &s[i].marks);
printf("Details of %d students are as follows\n", n);
printf("--------------------------------------------\n");
printf("Roll Number \t Marks\n");
printf("--------------------------------------------\n");

Krishnaveni Degree College :: Narasaraopet Page No. : 15


Problem Solving in C
UNIT IV
for(i=0;i<n;i++)
printf(" %d\t\t%d\n", s[i].rollno, s[i].marks);
printf("------------------------\n");
printf("Size of s is %d bytes\n", sizeof(s));
getch();
}
Arrays within structures: Arrays can be used as structure
members. Assume we have to store marks in three subjects for the
same student then declare marks as an array.
Example:
struct student
{
int rollno;
int marks[3];
} s;
/* Program that demonstrates the use of structures */
#include <stdio.h>
#include<conio.h>
void main()
{
struct student
{
int rollno;
int marks[3];
} s;
int i, total=0;
clrscr();
printf("Enter rollno of student: ");
scanf("%d", &s.rollno);
for(i=0;i<3;i++)
{
printf("Enter the Subject %d marks : ", i);
scanf("%d", &s.marks[i]);
}
printf("Details of student are as follows\n");
printf(" RollNo: %d\n", s.rollno);
for(i=0;i<3;i++)
{
printf(" Marks[%d]: %d\n", i,s.marks[i]);
total+=s.marks[i];
}
printf("Total: %d\n",total);
getch();

Krishnaveni Degree College :: Narasaraopet Page No. : 16


Problem Solving in C
UNIT IV
}
Nested Structures: Structure within another structure is known as
nesting of structures.
Example:
struct student
{
int rollno;
char name[40];
struct
{ int day;
int month;
int year;
} doj;
} s;
/* Program that demonstrates the use of structure within structures
*/
#include <stdio.h>
#include<conio.h>
void main()
{
struct student
{
int rollno;
struct date
{
int day,month, year;
}doj;
} s;
clrscr();
printf("Enter rollno of student: ");
scanf("%d", &s.rollno);
printf("Enter Date of Joining in dd-mm-yyyy format: ");
scanf("%d-%d-%d",&s.doj.day, &s.doj.month, &s.doj.year);
printf("Details of student are as follows\n");
printf(" RollNo: %d\n”, s,rollno);
printf(“ Date of Joining: %d/%d/%d\n", s.doj.day, s.doj.month,
s.doj.year);
getch();
}
Passing Structures to Functions: Passing structures to functions
can be done in three ways. They are
1. Passing Structure Members to Functions
2. Passing Entire Structures to Functions

Krishnaveni Degree College :: Narasaraopet Page No. : 17


Problem Solving in C
UNIT IV
3. Passing address of structure to a function
Passing Structure Members to Functions: Passing a member of a
structure to a function means passing the value of that member to
the function. It is similar to the technique call by value. This
technique will be useful when only some members of the structure
are to be passed to the function.
Passing Entire Structures to Functions: Passing entire structure to a
function means passing the value of the structure members to the
function. It is similar to the technique call by value. This technique
will be useful when all members of the structure are to be passed to
the function.
/* C Program to pass structure to a function and calculate sum of two
numbers */
#include<stdio.h>
#include<conio.h>
struct complexnum
{
float real;
float imag;
};
typedef struct complexnum complex;
complex add(complex n1,complex n2);
void main()
{
complex n1, n2, temp;
clrscr();
printf("Enter real and imaginary part of first complex number:");
scanf("%f%f", &n1.real, &n1.imag);
printf("Enter real and imaginary part of second complex
number:");
scanf("%f%f", &n2.real, &n2.imag);
temp = add(n1, n2);
printf("Sum = %.1f + j%.1f", temp.real, temp.imag);
getch();
}
complex add(complex n1, complex n2)
{
complex temp;
temp.real = n1.real + n2.real;
temp.imag = n1.imag + n2.imag;
return(temp);
}

Krishnaveni Degree College :: Narasaraopet Page No. : 18


Problem Solving in C
UNIT IV
Passing address of structure to a function: Address of structure can
be passed as arguments to functions. This is similar to call by
reference technique. When a pointer of structure is passed as
function argument i.e address of the structure is passed to the
function. Thus modification done to the structure in the function will
also affect the calling function.

Unions: Syntax of union is similar to syntax of structure. The


difference lies in terms of storage. In structure each member has its
own storage location whereas all the members of the union use the
same location. That means even though union may contain different
members , it can handle only one member at a time .
Syntax:
union union_name
{
data_type member-name;
data_type member-name;
data_type member-name;
} union-variables;
Example:
union stud
{
int rollno;
char name[10];
float marks;
} s;
For the above example the compiler allocates a piece of storage
that is large enough to hold largest variable in the union. In the
above example rollno requires 2 bytes, marks requires 4 bytes and
name requires 10 bytes. Thus compiler allocates 10 bytes for the
union stud.
/* Program to demonstrate union */
#include<stdio.h>
#include<conio.h>
void main()
{
union student
{
int rollno;
int marks;
}s;
clrscr();
printf("Enter student rollno: ");

Krishnaveni Degree College :: Narasaraopet Page No. : 19


Problem Solving in C
UNIT IV
scanf("%d",&s.rollno);
printf("The student rollno is %d\n", s.rollno);
printf("Enter student marks: ");
scanf("%d",&s.marks);
printf("The student marks is %d\n", s.marks);
printf("Size of s is %d bytes\n", sizeof(s));
getch();
}

typedef: The keyword typedef is used for defining a new name for
an existing type.
Syntax: typedef existing_name new_name;
Example typedef float real;
where existing_name is any valid data type, and new_name is the
new name for this datatype. The new_name is in addition to, not a
replacement for, the existing type name. That is you can use either
the existing_name or new_name.

Enumerated data type: Enumeration (or enum) is a user defined


data type in C. It is mainly used to assign names to integral
constants, the names make a program easy to read and maintain.
Keyword enum is used to defined enumerated data type.
enum type_name{ value1, value2,...,valueN };
Here, type_name is the name of enumerated data type or tag. And
value1,value2,.,valueN are values of type type_name. By default,
value1 will be equal to 0, value2 will be 1 and so on but, the
programmer can change the default value.
Changing the default value of enum elements:
enum suit { club=0; diamonds=10; hearts=20; spades=3; };
Declaration of enumerated variable: Above code defines the type of
the data but, no any variable is created. Variable of type enum can
be created as:
enum boolean{ false; true; };
enum boolean check;
Here, a variable check is declared which is of type enum boolean.
/* Example of enumerated type*/
#include <stdio.h>
enum week{ sunday, monday, tuesday, wednesday, thursday,
friday, saturday}; void main()
{
enum week today;
today=wednesday;
printf("%d day",today+1);

Krishnaveni Degree College :: Narasaraopet Page No. : 20


Problem Solving in C
UNIT IV
getch();
}

Krishnaveni Degree College :: Narasaraopet Page No. : 21

You might also like