Unit-2
ARRAYS USING FUNCTIONS
By
[Link]
1-d arrays using functions
Passing individual array elements to a function
• We can pass individual array elements as arguments to a
function like other simple variables.
Example:
#include<stdio.h>
void check(int);
void main()
{
int a[10],i;
clrscr();
printf(“\n enter the array elements:”);
for(i=0;i<10;i++)
{
scanf(“%d”,&a[i]);
check(a[i]);
Example:
}
void check(int num)
{
if(num%2==0)
printf(“%d is even\n”,num);
else
printf(“%d is odd\n”,num);
}
Output:
enter the array elements:
1 2 3 4 5 6 7 8 9 10
1 is odd
2 is even
3 is odd
4 is even
5 is odd
6 is even
7 is odd
8 is even
9 is odd
Example:C program to pass a single element of an array to function
#include <stdio.h>
void display(int a)
{
printf("%d",a);
}
int main()
{
int c[]={2,3,4};
display(c[2]); //Passing array element c[2] only.
return 0;
Output
234
STRUCTURE AND UNION
• A Structure is a user defined data type that can store related information
together.
• The variable within a structure are of different data types and each has a name that is
used to select it from the structure.
• C arrays allow you to define type of variables that can hold several data items of the
same kind but structure is another user defined data type available in C
programming, which allows you to combine data items of different kinds.
• Structures are used to represent a record, Suppose you want to keep track of your
books in a library. You might want to track the following attributes about each book:
• Title
• Author
• Subject
• Book ID
Structure Declaration
• It is declared using a keyword struct followed by the name of the
structure. The variables of the structure are declared within the
structure.
Example:
Struct struct-name
{
data_type var-name;
data_type var-name;
Structure Initialization
Assigning constants to the members of the structure is called initializing
of structure.
Syntax:
struct struct_name
data _type member_name1;
data _type member_name2;
} struct_var={constant1,constant2};
Accessing the Members of a structure
• A structure member variable is generally accessed using a ‘.’ operator.
Syntax:
strcut_var.member_name;
• The dot operator is used to select a particular member of the structure.
• To assign value to the individual Data members of the structure variable stud, we write,
[Link]=01;
[Link]=”Rahul”;
To input values for data members of the structure variable stud,
can be written as,
scanf(“%d”,&[Link]);
scanf(‘’%s”,&[Link]);
• To print the values of structure variable stud, can be written
as:
printf(“%s”,[Link]);
printf(“%f”,[Link]);
QUESTIONS
1. Write a program using structures to read and display the
information about an employee.
2. Write a program to read, display, add and subtract two complex
numbers.
3. Write a program to enter two points and then calculate the
distance between them
NESTED STRUCTURES
• The structure that contains another structure as its members
is called a nested structure or a structure within a structure
is called nested structure.
• The structure should be declared separately and then be
grouped into high level structure.
Passing Structures through pointers
• Pointer to a structure is a variable that holds the address of a structure.
• The syntax to declare pointer to a structure can be given as:
strcut struct_name *ptr;
• To assign address of stud to the pointer using address operator(&) we would write
ptr_stud=&stud;
• To access the members of the structure (->) operator is used.
For example
Ptr_stud->name=Raj;
SELF REFERENTIAL STRUCTURE
• Self –referential structures are those structures that contain a reference to
data of its same type as that of structure.
Example
struct node
{
int val;
struct node*next;
};
Pointers to Structures
• You can define pointers to structures in very similar way as you define pointer to
any other variable as follows:
struct books *struct_pointer;
• Now, you can store the address of a structure variable in the above defined pointer
variable.
• To find the address of a structure variable, place the & operator before the structure's
name as follows:
struct_pointer = &book1;
• To access the members of a structure using a pointer to that structure, you must use
the ->operator as follows: struct_pointer->title;
UNION
• Union is a collection of variables of different data types, in case of
union information can only be stored In one field at any one time.
• A union is a special data type available in C that enables you to
store different data types in the same memory location.
• You can define a union with many members, but only one member
can contain a value at any given time.
• Unions provide an efficient way of using the same memory
location for multi-purpose.
Declaring Union
union union-name
data_type var-name;
data_type var-name;
};
Accessing a Member of a Union
#include <stdio.h>
#include <string.h>
union Data
{
int i;
float f;
char str[20];
};
int main( )
{
union Data data;
Accessing a Member of a Union
data.i = 10;
data.f = 220.5;
strcpy( [Link], "C Programming");
printf( "data.i : %d\n", data.i);
printf( "data.f : %f\n", data.f);
printf( "[Link] : %s\n", [Link]);
return 0;
}
POINTERS
• A pointer is a variable that contains the address of a variable.
Example
int a=50;
int *ptr;
ptr=&a;
• Here ‘a’ is a variable holds a value 50 and stored in a memory location
1001. ‘*ptr’ is pointer variable holds a address of a variable ‘a’.
Array of Pointers
• We can declare an array that contains pointers as its elements.
Syntax to declare array of pointer:
datatype *arrayname[size];
• For example to declare an array of size 20 that contains integer
pointers we can write
int *a[10];
• where we can initialize each element of a[] with addresses of
variables.
Functions returning Pointer
• We can have a function that returns a pointer.
Syntax to declare such type of function is
type *function_name(type1,type2,……);
For Example:
void main()
{
int *p;
p=fun();
}
int *fun()
{
int a=5; int *q=&a;
return q;}
Pointers to Functions
• How to declare a pointer to a function?
Syntax:
returntype_of_function (*pointer variable)(List of arguments);
For example:
int (*p)(int,int);
• can be interpreted as p is a pointer to function which takes two integers as
argument and returntype is integer.
How to make a pointer to a function?
Syntax: pointer_variable=function_name_without_parantheses;
For Example:
p=test;
• can be read as p is a pointer to function test.
How to call a function using pointer?
Syntax:
pointer_variable(list of arguments);
How to call a function using pointer?
OR
(*pointer_variable)(List of arguments);
The following program illustrates pointer to function
int getc()
{
return 10;
}
void put(int a)
{
printf(“%d”,a);
}
How to call a function using pointer?
void main()
{
int k;
int (*p)();/*You can write void *p();*/
void (*q)(int);/*You can write void *q(int);*/
p=get;
q=put;
k=p();
q(k);
}
ENUMERATED DATA TYPES
• Enumeration or Enum in C is a special kind of data type defined by the
user.
• It consists of constant integrals or integers that are given names by a
user.
• The use of enum in C to name the integer values makes the entire program
easy to learn, understand, and maintain by the same or even different
programmer.
Syntax to Define Enum in C
• An enum is defined by using the ‘enum’ keyword in C, and the use of a
comma separates the constants within.
The basic syntax of defining an enum is:
enum enum_name{int_const1, int_const2, int_const3, …. int_constN};
• In the above syntax, the default value of int_const1 is 0, int_const2 is 1,
int_const3 is 2, and so on.
• However, you can also change these default values while declaring the
enum.
Example
• Below is an example of an enum named cars and how you can change
the default values.
enum cars{BMW, Ferrari, Jeep, Mercedes-Benz};
Here, the default values for the constants are:
BMW=0, Ferrari=1, Jeep=2, and Mercedes-Benz=3.
• However, to change the default values, you can define the enum as
follows:
enum cars{ BMW=3,
Ferrari=5, Jeep=0,
Mercedes-Benz=1
};
Enumerated Type Declaration to Create a Variable
• Similar to pre-defined data types like int and char, you can also declare a variable for
enum and other user-defined data types. Here’s how to create a variable for enum.
enum condition (true, false); //declaring the enum
enum condition e; //creating a variable of type condition
• Suppose we have declared an enum type named condition; we can create a variable for
that data type as mentioned above. We can also converge both the statements and write
them as:
enum condition (true, false) e;
• For the above statement, the default value for true will be 1, and that for false will be 0.
Implementing enum using C Program
Example program : Printing the Values of Weekdays
#include <stdio.h>
enum days{Sunday=1, Monday, Tuesday, Wednesday, Thursday, Friday,
Saturday};
int main()
{
// printing the values of weekdays
for(int i=Sunday;i<=Saturday;i++)
{
printf("%d, ",i);
}
return 0;
}
Output
PREPROCESSOR DIRECTIVES
• The C preprocessor is a microprocessor that is used by compiler to
transform your code before compilation.
• It is called micro preprocessor because it allows us to add macros.
Note: A macro is a segment of code which is replaced by the value of macro.
Macro is defined by #define directive.
Example
#define PI 3.14
• Here, PI is the macro name which will be replaced by the value 3.14.
PREPROCESSOR DIRECTIVES
• All preprocessor directives starts with hash # symbol. Let's see a list of preprocessor
directives.
• #define: It substitutes a preprocessor using macro.
• #include: It helps to insert a certain header from another file.
• #undef: It undefines a certain preprocessor macro.
• #ifdef: It returns true if a certain macro is defined.
• #ifndef: It returns true if a certain macro is not defined.
• #if, #elif, #else, and #endif: It tests the program using a certain condition; these directives
can be nested too.
• #line: It handles the line numbers on the errors and warnings. It can be used to change the
line number and source files while generating output during compile time.
• #error and #warning: It can be used for generating errors and warnings.
PREPROCESSOR DIRECTIVES
• #error can be performed to stop compilation.
• #warning is performed to continue compilation with messages in the
console window.
• #region and #endregion: To define the sections of the code to make
them more understandable and readable, we can use the region using
expansion and collapse features.
Enumeration Data Type
• A set of named constants or enumerators that represent a collection of
connected values can be defined in C using the enumeration data type
(enum).
• The enum in C is also known as the enumerated type.
• It is a user-defined data type that consists of integer values, and it
provides meaningful names to these values.
• The use of enum in C makes the program easy to understand and maintain.
• The enum is defined by using the enum keyword.
The following is the way to define the enum in C:
enum flag{integer_const1, integer_const2,.....integter_constN};
• In the above declaration, we define the enum named as flag containing 'N'
integer constants.
• The default value of integer_const1 is 0, integer_const2 is 1, and so on.
• We can also change the default value of the integer constants at the time
of the declaration.
For example:
enum fruits{mango, apple, strawberry, papaya};
• The default value of mango is 0, apple is 1, strawberry is 2,
and papaya is 3. If we want to change these default values, then
we can do as given below:
enum fruits{ mango=2, apple=1, strawberry=5, papaya=7,
};
Enumerated type declaration
• As we know that in C language, we need to declare the variable of a pre-
defined type such as int, float, char, etc.
• Similarly, we can declare the variable of a user-defined data type, such as
enum.
• Let's see how we can declare the variable of an enum type.
• Suppose we create the enum of type status as shown below:
enum status{false,true};
Enumerated type declaration
• Now, we create the variable of status type:
enum status s; // creating a variable of the status type.
• In the above statement, we have declared the 's' variable of type status.
• To create a variable, the above two statements can be written as:
enum status{false,true} s;
Let's create a simple program of enum.
#include <stdio.h>
enum weekdays{Sunday=1, Monday, Tuesday, Wednesday, Thursday,
Friday, Saturday};
int main()
{
enum weekdays w; // variable declaration of weekdays type
w=Monday; // assigning value of Monday to w.
printf("The value of w is %d",w);
return 0;
}
Output
Let's demonstrate another example to understand the enum more
clearly.
#include <stdio.h>
enum months{jan=1, feb, march, april, may, june, july, august, september,
october, november, december};
int main()
{
// printing the values of months
for(int i=jan;i<=december;i++)
{
printf("%d, ",i);
}
return 0; }
Output