SlideShare a Scribd company logo
Arrays:
 An array is a collection of similar data items, which are stored under a common name.
 Each element of an array is stored in successive locations of the memory.
 Data items can be int, float, char values of data types.
 The elements of the array are known as members of the array.
 Arrays are declared using the symbol square bracket”[ ]” (or) subscript.
Need for Array:
 A single variable store only one value.
 If we want to store more values means we need to declare more variables.
 This problem solved using array.
Types of array:
Arrays can be classified into
1. One Dimensional Array
2. Two Dimensional Array
3. Multi Dimensional Array
1. One Dimensional Array:
 An array is a collection of similar data items, which are stored under a common name using
single subscript.
 One Dimensional Array also called linear array or Single Dimensional Array.
 The array elements must be accessed on an element by element.
 Array accessed by using looping structure(for, while).
 Array elements are always starting at Zero and end with Maximum element-1.
Syntax:
Datatype array_name[size];
Datatype—Type of data items like as int,char,float
Array_name---specifies name of the array
Size---element count.
Example: int a[3];
Array index Element values
a[0] 4
a[1] 12
a[2] 10
Array initialization:
 The array initialized in two ways:
1. At compile time
2. At run time
1. At compile time:
o The array elements are initialized at the time of declaration.
Syntax: Datatype array_name[]={list of values};
Example: int marks[3]={45,67,89};
Array index Element values
marks[0] 45
marks [1] 67
marks [2] 89
2. At run time:
o The array elements are initialized at the time of program running.
o The “for” loop is used to initialize values for array element.
Example:
i) Using for loop to initialize value “0” to all the elements.
int a[10],i;
for(i=0;i<10;i++)
a[i]=0;
UNIT-3
ARRAYS AND
FUNCTIONS
ii) Using scanf() function to initialize different values.
int a[5],i;
for(i=0;i<5;i++)
scanf(“%d”,&a[i]);
//One Dimensional array Sum and average Numbers
#include<stdio.h>
#include<conio.h>
void main()
{
int a[10],n,i,sum=0;
float avg=0.0;
clrscr();
printf("Sum and average of given Numbers");
printf("nEnter the Limit Value:");
scanf("%d",&n);
printf("nEnter the Values:");
for(i=0;i<n;i++)
{
scanf("%d",&a[i]);
sum=sum+a[i];
}
avg=(float)sum/n;
printf("nSum = %d",sum);
printf("nAverage = %.2f",avg);
getch();
}
OUTPUT:
Sum and average of given Numbers
Enter the Limit Value:5
Enter the Values:45
2
3
10
5
Sum = 65
Average = 13.00
2. Two Dimensional array:
o Two dimensional arrays have two subscripts.
o We need to store table of values use the 2D array.
o Two pairs of square brackets denoted by rows and columns.
Example: A[3][3];
Column-0 Column-1 Column-2
Row-0
Row-1
Row-2
That is represented as
Columns
Column-0 Column-1 Column-2
Row-0 A[0][0] A[0][1] A[0][2]
Row-1 A[1][0] A[1][1] A[1][2]
Row-2 A[2][0] A[2][1] A[2][2]
Syntax:
Datatype array_name[row_size][column_size];
Initialization:
Rows
1. At compile time:
 The values can be initialized at the time of declaration.
Syntax:
Datatype array_name[row_size][column_size]={List of Values};
Example:
A[2][2]={{1,2}{3,4}};
Or
A[2][2]={1,2,3,4};
2. At run time:
 The values can be initialized at the time of running.
 Run time initialization can be do with the scanf() function.
Example:
int a[5][5],I,j;
for(i=0;i<5;i++)
for(j=0;j<5;j++)
scanf("%d",&a[i][j]);
Example:
//Two Dimensional array or Matrix Multiplication
#include<stdio.h>
#include<conio.h>
void main()
{
int a[2][2],b[2][2],c[2][2],j,i,k;
clrscr();
printf("Matrix Multiplication");
printf("nEnter the A matrix 4 values:");
for(i=0;i<2;i++)
for(j=0;j<2;j++)
scanf("%d",&a[i][j]);
printf("nEnter the B matrix 4 values:");
for(i=0;i<2;i++)
for(j=0;j<2;j++)
scanf("%d",&b[i][j]);
printf("nResult Matrix:n");
for(i=0;i<2;i++)
{
for(j=0;j<2;j++)
{
c[i][j]=0;
for(k=0;k<2;k++)
c[i][j]= c[i][j]+a[i][k]*b[k][j];
}
}
for(i=0;i<2;i++)
{
for(j=0;j<2;j++)
printf("%dt",c[i][j]);
printf("n");
}
getch();
}
OUTPUT:
Matrix Multiplication
Enter the A matrix 4 values:1
2
3
4
Enter the B matrix 4 values:5
6
7
8
Result Matrix:
19 22
43 50
//Two Dimensional array or Matrix Addition
#include<stdio.h>
#include<conio.h>
void main()
{
int a[2][2],b[2][2],c[2][2],j,i;
clrscr();
printf("Matrix Addition");
printf("nEnter the A matrix 4 values:");
for(i=0;i<2;i++)
for(j=0;j<2;j++)
scanf("%d",&a[i][j]);
printf("nEnter the B matrix 4 values:");
for(i=0;i<2;i++)
for(j=0;j<2;j++)
scanf("%d",&b[i][j]);
printf("nResult Matrix:n");
for(i=0;i<2;i++)
{
for(j=0;j<2;j++)
{
c[i][j]=a[i][j]+b[i][j];
printf("%dt",c[i][j]);
}
printf("n");
}
getch();
}
OUTPUT:
Matrix Addition
Enter the A matrix 4 values:3
2
1
5
Enter the B matrix 4 values:4
6
8
2
Result Matrix:
7 8
9 7
Strings:
 Group of (or) Collection of (or) Array of characters are called strings.
 The strings are specified with pair of double quotes (“ “).
 Where declaring a string it will take null character “0” at the end of string.
 This null character cannot visible.
Syntax: char array_name[];
Initialization:
 The values of string can be initialized at run time or compile time.
 The string values are initialized at compile time:
Syntax: char array_name[]=”values”;
Example: char name[]=”Senthil”;
 The string values are initialized at run time using scanf():
Syntax:
char array_name[];
scanf(“%s”,array_name);
Example:
char name[];
scanf(“%s”,name);
Reading and Writing:
 Reading & writing the string using scanf() & printf() function through the “%s” control string.
 Also use the gets() and puts() functions.
Syntax:
Read Write
scanf(“%s”,array_name); printf(“%s”,array_name);
gets(array_name); puts(array_name);
Example:
char name[15];
printf(“Enter the name:”);
scanf(“%s”,name);
printf(“nName:%s”,name);
OUTPUT:
Enter the name:Senthil
Name:Senthil
String Handling (or) Standard Functions:
 The ‘C’ compiler provides the following string handling functions:
S.No. Function Purpose
1. strlen() Find length of the string
2. strcpy() Copy one string to another
3. strcat() Combine two strings
4. strcmp() Comparing two strings
5. strrev() Reverse a string
6. strlwr() Convert in to lower case
7. strupr() Convert into upper case
1. strlen():
 This function is used to count & return the number of characters present in a string.
Syntax: int var=strlen(string1);
Example:
char name[]=”Senthil”;
int len1,len2;
len1=strlen(name);
len2=strlen(“Kumar”);
printf(“%s length is %d”,name,len1);
printf(“n%s length is %d”,”Kumar”,len1);
OUTPUT:
Senthil length is 7
Kumar length is 5
2. strcpy():
 This function is used to copy the contents of one string to another .
Syntax: strcpy(string1,string2);
 The contents of string2 copy to string1.
Example:
char str1[]=”Senthil”,str2[]=”Kumar”;
strcpy(str1,str2);
printf(“String1=%snString2=%s”,str1,str2);
OUTPUT:
String1=Kumar
String2=Kumar
3. strcat():
 This function is used to concatenate (or) combine the two strings.
Syntax: strcat(string1,string2);
String2 is combined with string1
Example:
char str1[]=”Senthil”,str2[]=”Kumar”;
strcat(str1,str2);
printf(“The combined string:%s”,str1);
OUTPUT:
The combined string:SenthilKumar
4. strcmp():
 This function is used to compares two strings and find out whether they are same or different.
 The two strings are compared character by character until end of one string is reached.
 When two strings are equal it will give value “Zero” otherwise give any other value.
Syntax: int var=strcmp(string1,string2);
Example:
char name1[]=”Kalai”,name2[]=”Malai”,name3[]=”Kalai”;
int I,j;
i=strcmp(name1,name2);
j=strcmp(name1,name3);
printf(“Comparison of %s & %s is %d”,name1,name2,i);
printf(“nComparison of %s & %s is %d”,name1,name3,j);
OUTPUT:
Comparison of Kalai & Malai is 1
Comparison of Kalai & Kalai is 0
5. strrev():
 This function is used to reverse a string.
Syntax: strrev(string1);
Example:
char str1[]=”Senthil”;
strrev(str1);
printf(“Reversed String=%s”,str1);
OUTPUT:
lihtneS
6. strlwr():
 This function is used to converts the characters of string into lower case characters.
Syntax: strlwr(string1);
Example:
char str1[]=”SenThiL”;
strlwr(str1);
printf(“Converted lower case:%s”,str1);
OUTPUT:
Converted lower case:senthil
7. strupr():
 This function is used to converts the characters of string into upper case characters.
Syntax: strupr(string1);
Example:
char str1[]=”SenThiL”;
strupr(str1);
printf(“Converted upper case:%s”,str1);
OUTPUT:
Converted upper case:SENTHIL
 A function is a set of instructions that are used to perform specified task.
Types of Functions:
i) User defined functions
ii) Built in functions
User Defined Functions:
 The user defined functions has to be written by the programmer.
Built in functions:
 These functions are not required to be written by the programmer.
 Built in functions also called as pre defined (or) library functions.
Need for user defined function:
 The program becomes too large & complex.
 The users cannot go through at glance.
 The task of debugging, testing & maintenance becomes difficult.
Elements of functions:
 The functions contain following three elements:
FUNCTIONS:
1) Function declaration
2) Function Definition
3) Function calling
Example:
1) Function Declaration:
 The function can be declared before they are defined.
 The parameters must match.
Syntax:
Return_type function_name(Parameter list);
Return_type  Datatype of the return value
Function_name  Name of the function
Parameter list  List of parameters
Example:
Int add(int x, int y); or void add();
2) Function Definition:
 The function definition is the actual body of the function.
 It is the process of specifying and establishing the operation.
Syntax:
Return_type function_name(parameter list)
{
Body of the function;
Return data;
}
3) Function call:
 A function can be called by specifying its name, followed by a list of parameters.
 The function definition may return a value to function call.
 A semicolon (;) is used at the end of the statement.
Syntax:
Function_name(); (or) function_name(parameter);
Value=function_name(parameter);
Example:
Fun(); or fun(a,b);
C=fun(a,b);
Parameters:
 Parameters provide the data communication between the function call & function definition.
 Parameters are also called as arguments.
There are 2 types:
i) Actual parameters
ii) Formal parameters.
Actual and formal parameters must match.
i) Actual parameters: These parameters are present in the function call.
ii) Formal parameters: These are present in the function definition.
Example:
Void main()
{ void sum(int x, int y)
……. {
Body of the function;
…… }
Sum(a,b);
…..
……
}
Return Statement:
 Value (or) information is returned from the function definition to the function call.
 A function may contain more than one return statement.
 Return type must be present in definition.
Syntax:
Return; (or) return(value (or) expression);
Example:
int first() int second()
{ {
….. ……
…. …
Return x*x; return a;
} }
Function prototypes:
 The functions are classified into the following types depending on arguments present or not
and the value is returned or not.
 These are called as function prototypes.
a) Function without arguments & no return values
b) Function with arguments & no return vales
c) Function with arguments & with return vales
d) Function without arguments & with return vales
a) Function without arguments & no return values:
 Here, there is no data transfer between function call & function definition. i.e.,no
arguments
are passed
from main
function & no
value is
returned from
the sub
function.
Syntax:
Example:
void sum();
void main()
{
sum();
}
void sum()
{
int a,b,c;
printf("enter the two values:");
scanf("%d%d",&a,&b);
c=a+b;
printf("sum =%d",c);
}
Output:
enter the two values:10
20
sum =30
b) Function with arguments & no return values:
 In this prototype, data is transferred from function call to the function definition.
 The value does not return the function call so it is called one-way communication.
Syntax:
Example:
void sum(int,int);
void main()
{
int a,b;
printf("enter the two values:");
scanf("%d%d",&a,&b);
sum(a,b);
}
void sum(int x, int y)
{
int z;
z=x+y;
printf("sum=%d",z);
}
OUTPUT:
enter the two values:10
20
sum =30
c) Function with arguments & with return vales:
 Here, the data is transferred between function call & function definition.
 The value is returned to the function call. So it is called as two way communication.
Syntax:
Example:
void main()
{
int a,b,c;
clrscr();
printf(“enter the two values:”);
scanf(“%d%d”,&a,&b);
c=sum(a,b);
printf(“sum=%d”,c);
getch();
}
void sum(int x, int y)
{
int z;
z=x+y;
return z;
}
Output:
Enter the values: 5 10
Sum=15
d) Function without arguments & with return values:
 Here, no data is transferred between function call & function definition.
 But the value is returned from the function definition to the function cal.
 So it is called as one way communication.
Syntax:
Example:
void main()
{
int a,b,c;
clrscr();
c=sum();
printf(“sum=%d”,c);
getch();
}
void sum(int x, int y)
{
int x,y,z;
printf(“enter the two values:”);
scanf(“%d%d”,&x,&y);
z=x+y;
return z;
}
OUTPUT:
Enter the values: 5 10
Sum=15
Parameter Passing Methods
There are 2 ways to pass a parameter inside the function. They are:
i) Call by Value
ii) Call by reference
i) Call by Value:
 This method copies the values of actual parameters into the formal parameters of the
function.
 The changes of the formal parameters cannot affect the actual parameters.
 Because formal parameters are photocopy of the actual parameters.
Syntax:
void main()
{
…………
swap(a,b);
……….
}
swap(int a,int b)
{
int temp;
………….
}
Example:
void swap1(int,int);
void main()
{
int a=10,b=20;
clrscr();
printf("before swap: a=%dt b=%d",a,b);
swap1(a,b);
printf("nafter swap: a=%dt b=%d",a,b);
}
void swap1(int x, int y)
{
int t;
t=x;
x=y;
y=t;
printf("nIn function a=%dt b=%d",x,y);
}
OUTPUT:
before swap: a=10 b=20
In function a=20 b=10
after swap: a=10 b=20
ii) Call by reference:
 Call by reference is the addresses of actual parameters are copied into the formal parameters
inside the function.
 The address is used to access the actual parameters inside the function also.
 So, Changes made in parameters are permanent.
 Here pointers are used to store the address.
Syntax:
void main()
{
…………..
swap(address of variable);
…………
}
void swap(pointer variable)
{
………..
}
Example:
void swap(int*,int*);
void main()
{
int a=10,b=20;
clrscr();
printf("before swap: a=%dt b=%d",a,b);
swap(&a,&b);
printf("nafter swap: a=%dt b=%d",a,b);
}
void swap(int *x, int *y)
{
int t;
t=*x;
*x=*y;
*y=t;
}
OUTPUT:
before swap: a=10 b=20
after swap: a=20 b=10
Recursion:
 Recursion takes the form of function that calls itself.
 A process being performed where one of the instructions is to repeat the process.
 It is similar to looping.
 Recursion is the process of calling the same function itself again and again until some
condition is satisfied.
Syntax:
void function1();
{
---
---
function1();
}
 The above function function1() is called themselves continuously.
Example:
void main()
{
int n,f;
printf("Enter the Number:");
scanf("%d",&n);
printf("nThe factorial of %d = %d",n,fact(n));
}
int fact(int x)
{
int f;
if(x==1)
return 1;
else
f=x*fact(x-1);
return f;
}
OUTPUT:
Enter the Number:5
The factorial of 5 = 120
Tower of Hanoi:
 The Tower of Hanoi is a mathematical game or puzzle.
 It consists of three rods, and a number of disks of different
sizes which can slide onto any rod.
 The puzzle starts with the disks in a neat stack in ascending
order of size on one rod, the smallest at the top, thus making a
conical shape.
The objective of the puzzle is to move the entire stack to another rod,
obeying the following simple rules:
1. Only one disk can be moved at a time.
2. Each move consists of taking the upper disk from one of the
stacks and placing it on top of another stack i.e. a disk can only
be moved if it is the uppermost disk on a stack.
3. No disk may be placed on top of a smaller disk.
With three disks, the puzzle can be solved in seven moves. The minimum number of moves
required to solve a Tower of Hanoi puzzle is 2n
- 1, where n is the number of disks.
 A pointer is a variable that is used to store the address of another variable.
 It is declared like other variables and also it is always denoted by asterisk “*” operator.
 Each variable has two attributes:
o Address
o Value
 It can be used to access and manipulate data stored in the
memory.
 Ordinary Variable:
int a=5;
aaccess the value
&a access the address of variable.
a variable
5 value
4002 address
Syntax: Data_type *pointer_variable;
Example: int *p;
Advantages:
1. It is increase the speed of execution.
2. It is saving memory space.
3. It enables us to access the memory directly.
4. It is also provide an alternate way to access an array.
5. Multiple data items can receive in the function.
Initializing pointer:
 The process of assigning the address of a variable to a pointer variable is called initialization.
 The location of the variable in system memory.
 This can be achieved through the ampersand(&) symbol.
 The ampersand(&) symbol is an address operator.
Unit-4
Pointers and
Structures
POINTERS
 It takes the address of the variable.
 Pointers must be initializing with assigning address of the variable.
Example:
void main()
{
int a=10,*p;
p=&a;
printf("n*p=%dtp=%dt&p=%dt&a=%d",*p,p,&p,&a);
}
OUTPUT:
*p=10 p=-12 &p=-14 &a=-12
 *pvalue of the address stored in pointer variable.
 Paddress of the variable.
 &paddress of the pointer variable.
 &aaddress of the variable.
a variable *p
10 value -12
-12 address -14
Pointer Arithmetic:
 C pointer is an address, which is a numeric value.
 Therefore, you can perform arithmetic operations on a pointer just as you can a numeric value.
 There are four arithmetic operators that can be used on pointers: ++, --, +, and -
Data type Initial Address operation address after operation bytes of data type
char 4000 ++ 4001 1
char 4000 -- 3999 1
int 4000 ++ 4002 2
int 4000 -- 3998 2
float 4000 ++ 4004 4
float 4000 -- 3996 4
Incrementing a Pointer
 Incrementing pointer is generally used in array.
 The variable pointer to access each succeeding element of the array.
 Incrementing pointer variable depends upon datatype of the pointer variable.
Example:
void main ()
{
int var[] = {10, 100, 200};
int i, *ptr;
ptr = var;
for ( i = 0; i < 3; i++)
{
printf("nAddress of var[%d] = %u", i, ptr );
printf("nValue of var[%d] = %d", i, *ptr );
ptr++;
}
}
OUTPUT:
Address of var[0] = 65520
Value of var[0] = 10
Address of var[1] = 65522
Value of var[1] = 100
Address of var[2] = 65524
Value of var[2] = 200
Decrementing a Pointer
 The same considerations apply to decrementing a pointer, which decreases its value by the
number of bytes of its data type as shown below:
Example:
void main ()
{
int var[] = {10, 100, 200};
int i, *ptr;
ptr = &var[3-1];
for ( i = 3; i > 0; i--)
{
printf("Address of var[%d] = %un", i, ptr );
printf("Value of var[%d] = %dn", i, *ptr );
ptr--;
}
}
OUTPUT:
Address of var[3] = 65524
Value of var[3] = 200
Address of var[2] = 65522
Value of var[2] = 100
Address of var[1] = 65520
Value of var[1] = 10
Pointers and Arrays or Pointers and Functions:
• The elements of the array can also be accessed through a pointer.
• Pointers also send the array to functions.
Syntax:
Pointer_variable=array_name;
Example:
void fun(int[]);
void main()
{
int a[3]={10,20,30},*p;
p=a;
fun(p);
}
void fun(int b[])
{
int i,total=0;
for(i=0;i<3;i++)
total=total+b[i];
printf("nTotal=%d",total);
}
OUTPUT:
Total=60
Structures:
 Structure is a compound datatype.
 It stores different type of data items.
 It is used to store dissimilar data items.
 Structure is creating with the “struct” keyword.
 It is the one of the storage unit.
 Different type of data items can be store in different memory space.
 The elements of structure are called members.
 It must be declare and defined.
Structure Declaration and Definition:
 It must be declare and defined.
 Structure is creating with the “struct” keyword.
 Structure finished declaration with semicolon(;).
 Accessing members with dot(.) operator.
Syntax:
struct structure_name
{
Datatype variables;
----
};
Creating structure Variable:
struct structure_name structure_variable;
Structures
FLOAT
INT
CHAR DOUBLE
Structures and Union
Accessing structure Member:
structure_variable.member;
Difference between structure and array:
S.No. Array Structure
1. It is a collection of similar data items. it is collection of dissimilar data items
2. It is derived data type. It is a user defined data type.
3. It behaves like a built-in data types. It must be declared and defined.
4. An array can be increase or decrease. Its members can be added.
Example:
//Student Details using Structure
struct stud
{
int regno,m1,m2,m3,total;
char name[20],result[5];
};
void main()
{
struct stud s1,s2;
printf("nStructures");
printf("nEnter the Regno, Name:");
scanf("%d%s",&s1.regno,s1.name);
printf("nEnter the Mark1, Mark2, Mark3:");
scanf("%d%d%d",&s1.m1,&s1.m2,&s1.m3);
s1.total=s1.m1+s1.m2+s1.m3;
if(s1.m1<50||s1.m2<50||s1.m3<50)
strcpy(s1.result,"Fail");
else
strcpy(s1.result,"Pass");
s2=s1; //Assigning structure
printf("RegnotNametMark1tMark2tMark3tTotaltResultn");
printf("%dt%st%dt%dt%dt%dt%s",s1.regno,s1.name,s1.m1,s1.m2,s1.m3,s1.total,s1.result);
printf("nStructure--2");
printf("nRegnotNametMark1tMark2tMark3tTotaltResultn");
printf("%dt%st%dt%dt%dt%dt%s",s2.regno,s2.name,s2.m1,s2.m2,s2.m3,s2.total,s2.result);
getch();
}
OUTPUT:
Enter the Regno, Name:345
kumar
Enter the Mark1, Mark2, Mark3:67
78
61
Regno Name Mark1 Mark2 Mark3 Total Result
345 kumar 67 78 61 206 Pass
Structure--2
Regno Name Mark1 Mark2 Mark3 Total Result
345 kumar 67 78 61 206 Pass
Structure within structure:
 A structure can be declared within another structure.
 It is also called nesting of structure.
 The structure variables can be normal variable or pointer variable.
 Nesting of more than one type of structure is allowed.
 Structure cannot be nested within itself.
Syntax:
struct struct_1
{
----
----
};
struct struct_2
{
----
----
struct struct_1 s1;
};
Example:
// Structure within structure
struct college_detail
{
int college_id;
char college_name[20];
};
struct student_detail
{
int regno;
char name[20];
float percent;
struct college_detail c1;
};
void main()
{
struct student_detail s1={703,"kumar",87.3,1300,"XYZ college"};
printf("nStructures within Structuren");
printf("RegnotNametpercentagetCollege IDtCollege Namen");
printf("%dt%st%ft%dt%s",s1.regno,s1.name,s1.percent,s1.c1.college_id,s1.c1.college_name);
getch();
}
OUTPUT:
Structures within Structure
Regno Name percentage College ID College Name
703 kumar 87.300003 1300 XYZ college
Example:
//Employee Details using Structure
void dummy(float *a)
{
float b=*a; //perform some floating access
dummy (&b); //calling a floating point function
}
struct employee1
{
int empno;
char name[10];
float salary;
};
void main()
{
struct employee1 e[10];
int i,n;
printf("nEnter the no.of Employees:");
scanf("%d",&n);
for(i=0;i<n;i++)
{
printf("nEnter the employee empno,name,salary:");
scanf("%d%s%f",&e[i].empno,e[i].name,&e[i].salary);
}
printf("nEmployee Detailsn");
printf("nEMPNOtNAMEtSALARY");
for(i=0;i<n;i++)
printf("n%dt%st%.2f",e[i].empno,e[i].name,e[i].salary);
getch();
}
OUTPUT:
Enter the no.of Employees:2
Enter the employee empno,name,salary:23
Raj
5000
Enter the employee empno,name,salary:24
Kumar
3500
Employee Details
EMPNO NAME SALARY
23 Raj 5000.00
24 Kumar 3500.00
Union
• A Union is a collection of different data items, which are stored under a common name.
• Here same memory is shared by its members.
• The keyword union is used to define a union.
• Size of union is equal to the size of largest member.
• Memory allocated is shared by individual members of union.
• The address is same for all the members of a union.
• Altering the value of any of the member will alter other member values.
• Only one member can be accessed at a time.
• Only the first member of a union can be initialized.
Syntax:
union union_name
{
union element1;
union element2;
…………………
};
Example:
union result
{
int mark;
float avg;
char grade;
};
union result s;
Structure Union
1.The keyword struct is used to define a structure 1. The keyword union is used to define a union.
2. The size of structure is greater than or equal to the
sum of sizes of its members.
2. Size of union is equal to the size of largest
member.
3. Each member within a structure is assigned
unique storage area of location.
3. Memory allocated is shared by individual
members of union.
4. The address of each member will be in ascending
order.
4. The address is same for all the members of a
union.
5 Altering the value of a member will not affect
other members of the structure.
5. Altering the value of any of the member will
alter other member values.
6. Individual member can be accessed at a time 6. Only one member can be accessed at a time.
7. Several members of a structure can initialize at
once.
7. Only the first member of a union can be
initialized.
Example:
void dummy(float *a)
{
float b=*a; //perform some floating access
dummy (&b); //calling a floating point function
}
union employee1
{
int empno;
char name[10];
float salary;
};
void main()
{
union employee1 e[10];
int i,n;
printf("nEnter the no.of Employees:");
scanf("%d",&n);
for(i=0;i<n;i++)
{
printf("nEnter the employee empno,name,salary:");
scanf("%d%s%f",&e[i].empno,e[i].name,&e[i].salary);
}
printf("nEmployee Detailsn");
printf("nEMPNOtNAMEtSALARY");
for(i=0;i<n;i++)
printf("n%dt%st%.2f",e[i].empno,e[i].name,e[i].salary);
getch();
}
OUTPUT:
Enter the no.of Employees:2
Enter the employee empno,name,salary:23
Raj
5000
Enter the employee empno,name,salary:24
Kumar
3500
Employee Details
EMPNO NAME SALARY
16384 5000.00
-16384 3500.00
Preprocessor:
 It is a program that processes the source program before compilation.
 The C preprocessor executes before a program is compiled.
 Preprocessor directives begin with # and only white-space characters and comments may
appear before a preprocessor directive on a line.
 It operates under the following directives
1. File Inclusion
2. Macro substitution
3. Conditional inclusion
File Inclusion:
• It is used to include some file that contains functions or some definitions.
• Copy of a specified file included in place of the directive
Syntax:
#include<filename> Searches standard library for file
(or) #include“filename” Searches for user-defined files
Example:
#include<stdio.h>
#include<conio.h>
#include "addition.txt"
void main()
{
int a,b;
printf("nEnter the numbers:");
scanf("%d%d",&a,&b);
printf("The Value is %d",add(a,b));
getch();
}
addition.txt
int add(int a,int b)
{
return(a+b);
}
OUTPUT:
Enter the numbers:7
4
The Value is 11
Macro Substitution:
• It is used to define and use integer, string, or identifier in the source program
• The three forms of macros are
– Simple Macro
– Argumented Macro
– Nested Macro
1) Simple Macro:
 It is used to define some constants.
Syntax
#define identifier string/integer
Example:
#include<stdio.h>
#include<conio.h>
#define pi 3.14
#define CITY "chennai"
void main()
{
printf("The Value is %f",2*pi);
printf("nThe Value CITY is %s",CITY);
getch();
}
OUTPUT:
The Value is 6.280000
The Value CITY is chennai
2) Argumented Macro
• It is used to define some complex forms in the source program.
Syntax:
#define identifier (v1,v2,….) string/integer
Example:
#include<stdio.h>
#include<conio.h>
#define cube(n) (n*n*n)
void main()
{
printf("The Value of 3 cube is %d",cube(3));
getch();
}
OUTPUT:
The Value of 3 cube is 27
3) Nested Macro
 Here one macro is used by another macro.
Example:
#include<stdio.h>
#include<conio.h>
#define a 3
#define sq a*a
void main()
{
printf("The Value is %d",sq);
getch();
}
Output:
The Value is 9
Conditional Inclusion:
 It is used to include some conditional statements.
Example:
#include<stdio.h>
#include<conio.h>
#define a 3
#ifdef a
#define c a+5
#endif
void main()
{
printf("nThe value C is %d",c);
getch();
}
Output:
The value C is 8

More Related Content

What's hot (20)

PDF
Introduction to c++ ppt
Prof. Dr. K. Adisesha
 
PPT
Structure of a C program
David Livingston J
 
PPTX
Tokens in C++
Mahender Boda
 
PPT
Control statements
raksharao
 
PPTX
Data types in c++
Venkata.Manish Reddy
 
PPTX
Functions in C
Kamal Acharya
 
PPTX
Union in C programming
Kamal Acharya
 
PPTX
C pointer
University of Potsdam
 
PDF
Introduction to c++ ppt 1
Prof. Dr. K. Adisesha
 
PDF
Datatypes in python
eShikshak
 
PPTX
Storage classes in C
Nitesh Bichwani
 
PPT
Array in c
Ravi Gelani
 
PPTX
C++ language basic
Waqar Younis
 
PDF
Differences between c and c++
starlit electronics
 
PPTX
concept of Array, 1D & 2D array
Sangani Ankur
 
PPTX
Characteristics of OOPS
abhishek kumar
 
PPTX
Structure of C program
Pavan prasad
 
PPTX
Unit 3. Input and Output
Ashim Lamichhane
 
PPTX
Parameter passing to_functions_in_c
ForwardBlog Enewzletter
 
PPTX
C Programming: Structure and Union
Selvaraj Seerangan
 
Introduction to c++ ppt
Prof. Dr. K. Adisesha
 
Structure of a C program
David Livingston J
 
Tokens in C++
Mahender Boda
 
Control statements
raksharao
 
Data types in c++
Venkata.Manish Reddy
 
Functions in C
Kamal Acharya
 
Union in C programming
Kamal Acharya
 
Introduction to c++ ppt 1
Prof. Dr. K. Adisesha
 
Datatypes in python
eShikshak
 
Storage classes in C
Nitesh Bichwani
 
Array in c
Ravi Gelani
 
C++ language basic
Waqar Younis
 
Differences between c and c++
starlit electronics
 
concept of Array, 1D & 2D array
Sangani Ankur
 
Characteristics of OOPS
abhishek kumar
 
Structure of C program
Pavan prasad
 
Unit 3. Input and Output
Ashim Lamichhane
 
Parameter passing to_functions_in_c
ForwardBlog Enewzletter
 
C Programming: Structure and Union
Selvaraj Seerangan
 

Similar to Arrays and function basic c programming notes (20)

PPT
Session 4
Shailendra Mathur
 
PPT
Arrays in c programing. practicals and .ppt
Carlos701746
 
PPTX
arrays in c programming - example programs
stalin721831
 
PPTX
Arrays
RaziyasultanaShaik
 
PDF
VIT351 Software Development VI Unit2
YOGESH SINGH
 
PPTX
Programming in C (part 2)
Dr. SURBHI SAROHA
 
DOCX
Array Cont
Ashutosh Srivasatava
 
PPTX
Intro to C# - part 2.pptx emerging technology
worldchannel
 
PPTX
Unit 3
GOWSIKRAJAP
 
PPTX
Arrays in C++
Kashif Nawab
 
PPTX
Unit 3
GOWSIKRAJAP
 
PPTX
Lecture_3 the functions parameters andrecursion .pptx
Dr. Amna Mohamed
 
DOC
Functions struct&union
UMA PARAMESWARI
 
DOCX
Array assignment
Ahmad Kamal
 
PPTX
C-Arrays & Strings (computer programming).pptx
yusuph2410
 
PPT
Functional Programming
Olexandra Dmytrenko
 
PPTX
Array BPK 2
Riki Afriansyah
 
PDF
Programming Fundamentals Arrays and Strings
imtiazalijoono
 
PPTX
Java fundamentals
HCMUTE
 
Arrays in c programing. practicals and .ppt
Carlos701746
 
arrays in c programming - example programs
stalin721831
 
VIT351 Software Development VI Unit2
YOGESH SINGH
 
Programming in C (part 2)
Dr. SURBHI SAROHA
 
Intro to C# - part 2.pptx emerging technology
worldchannel
 
Unit 3
GOWSIKRAJAP
 
Arrays in C++
Kashif Nawab
 
Unit 3
GOWSIKRAJAP
 
Lecture_3 the functions parameters andrecursion .pptx
Dr. Amna Mohamed
 
Functions struct&union
UMA PARAMESWARI
 
Array assignment
Ahmad Kamal
 
C-Arrays & Strings (computer programming).pptx
yusuph2410
 
Functional Programming
Olexandra Dmytrenko
 
Array BPK 2
Riki Afriansyah
 
Programming Fundamentals Arrays and Strings
imtiazalijoono
 
Java fundamentals
HCMUTE
 
Ad

More from GOKULKANNANMMECLECTC (6)

PDF
GAME THEORY AND MONTE CARLO SEARCH SPACE TREE
GOKULKANNANMMECLECTC
 
PPT
INTRODUCTION TO ARTIFICIAL INTELLIGENCE BASIC
GOKULKANNANMMECLECTC
 
PPTX
tcpflowcontrolanurag-150513130509-lva1-app6892 (1).pptx
GOKULKANNANMMECLECTC
 
PPT
Tcp congestion control topic in high speed network
GOKULKANNANMMECLECTC
 
PPT
KandR_TCP (1).ppt notes for congestion control
GOKULKANNANMMECLECTC
 
PDF
INTRODUCTION TO C PROGRAMMING in basic c language
GOKULKANNANMMECLECTC
 
GAME THEORY AND MONTE CARLO SEARCH SPACE TREE
GOKULKANNANMMECLECTC
 
INTRODUCTION TO ARTIFICIAL INTELLIGENCE BASIC
GOKULKANNANMMECLECTC
 
tcpflowcontrolanurag-150513130509-lva1-app6892 (1).pptx
GOKULKANNANMMECLECTC
 
Tcp congestion control topic in high speed network
GOKULKANNANMMECLECTC
 
KandR_TCP (1).ppt notes for congestion control
GOKULKANNANMMECLECTC
 
INTRODUCTION TO C PROGRAMMING in basic c language
GOKULKANNANMMECLECTC
 
Ad

Recently uploaded (20)

PDF
Rapid Prototyping for XR: Lecture 1 Introduction to Prototyping
Mark Billinghurst
 
PPTX
Work at Height training for workers .pptx
cecos12
 
PDF
FSE-Journal-First-Automated code editing with search-generate-modify.pdf
cl144
 
PPTX
Introduction to File Transfer Protocol with commands in FTP
BeulahS2
 
PDF
Rapid Prototyping for XR: Lecture 6 - AI for Prototyping and Research Directi...
Mark Billinghurst
 
PPTX
Mobile database systems 20254545645.pptx
herosh1968
 
PDF
輪読会資料_Miipher and Miipher2 .
NABLAS株式会社
 
PDF
Decision support system in machine learning models for a face recognition-bas...
TELKOMNIKA JOURNAL
 
PPTX
LECTURE 7 COMPUTATIONS OF LEVELING DATA APRIL 2025.pptx
rr22001247
 
PPTX
WHO And BIS std- for water quality .pptx
dhanashree78
 
PDF
Rapid Prototyping for XR: Lecture 3 - Video and Paper Prototyping
Mark Billinghurst
 
PPT
FINAL plumbing code for board exam passer
MattKristopherDiaz
 
PDF
13th International Conference of Security, Privacy and Trust Management (SPTM...
ijcisjournal
 
PDF
Python Mini Project: Command-Line Quiz Game for School/College Students
MPREETHI7
 
PDF
CLIP_Internals_and_Architecture.pdf sdvsdv sdv
JoseLuisCahuanaRamos3
 
PPTX
Computer network Computer network Computer network Computer network
Shrikant317689
 
PPTX
CST413 KTU S7 CSE Machine Learning Clustering K Means Hierarchical Agglomerat...
resming1
 
PDF
Generative AI & Scientific Research : Catalyst for Innovation, Ethics & Impact
AlqualsaDIResearchGr
 
PPSX
OOPS Concepts in Python and Exception Handling
Dr. A. B. Shinde
 
PDF
Designing for Tomorrow – Architecture’s Role in the Sustainability Movement
BIM Services
 
Rapid Prototyping for XR: Lecture 1 Introduction to Prototyping
Mark Billinghurst
 
Work at Height training for workers .pptx
cecos12
 
FSE-Journal-First-Automated code editing with search-generate-modify.pdf
cl144
 
Introduction to File Transfer Protocol with commands in FTP
BeulahS2
 
Rapid Prototyping for XR: Lecture 6 - AI for Prototyping and Research Directi...
Mark Billinghurst
 
Mobile database systems 20254545645.pptx
herosh1968
 
輪読会資料_Miipher and Miipher2 .
NABLAS株式会社
 
Decision support system in machine learning models for a face recognition-bas...
TELKOMNIKA JOURNAL
 
LECTURE 7 COMPUTATIONS OF LEVELING DATA APRIL 2025.pptx
rr22001247
 
WHO And BIS std- for water quality .pptx
dhanashree78
 
Rapid Prototyping for XR: Lecture 3 - Video and Paper Prototyping
Mark Billinghurst
 
FINAL plumbing code for board exam passer
MattKristopherDiaz
 
13th International Conference of Security, Privacy and Trust Management (SPTM...
ijcisjournal
 
Python Mini Project: Command-Line Quiz Game for School/College Students
MPREETHI7
 
CLIP_Internals_and_Architecture.pdf sdvsdv sdv
JoseLuisCahuanaRamos3
 
Computer network Computer network Computer network Computer network
Shrikant317689
 
CST413 KTU S7 CSE Machine Learning Clustering K Means Hierarchical Agglomerat...
resming1
 
Generative AI & Scientific Research : Catalyst for Innovation, Ethics & Impact
AlqualsaDIResearchGr
 
OOPS Concepts in Python and Exception Handling
Dr. A. B. Shinde
 
Designing for Tomorrow – Architecture’s Role in the Sustainability Movement
BIM Services
 

Arrays and function basic c programming notes

  • 1. Arrays:  An array is a collection of similar data items, which are stored under a common name.  Each element of an array is stored in successive locations of the memory.  Data items can be int, float, char values of data types.  The elements of the array are known as members of the array.  Arrays are declared using the symbol square bracket”[ ]” (or) subscript. Need for Array:  A single variable store only one value.  If we want to store more values means we need to declare more variables.  This problem solved using array. Types of array: Arrays can be classified into 1. One Dimensional Array 2. Two Dimensional Array 3. Multi Dimensional Array 1. One Dimensional Array:  An array is a collection of similar data items, which are stored under a common name using single subscript.  One Dimensional Array also called linear array or Single Dimensional Array.  The array elements must be accessed on an element by element.  Array accessed by using looping structure(for, while).  Array elements are always starting at Zero and end with Maximum element-1. Syntax: Datatype array_name[size]; Datatype—Type of data items like as int,char,float Array_name---specifies name of the array Size---element count. Example: int a[3]; Array index Element values a[0] 4 a[1] 12 a[2] 10 Array initialization:  The array initialized in two ways: 1. At compile time 2. At run time 1. At compile time: o The array elements are initialized at the time of declaration. Syntax: Datatype array_name[]={list of values}; Example: int marks[3]={45,67,89}; Array index Element values marks[0] 45 marks [1] 67 marks [2] 89 2. At run time: o The array elements are initialized at the time of program running. o The “for” loop is used to initialize values for array element. Example: i) Using for loop to initialize value “0” to all the elements. int a[10],i; for(i=0;i<10;i++) a[i]=0; UNIT-3 ARRAYS AND FUNCTIONS
  • 2. ii) Using scanf() function to initialize different values. int a[5],i; for(i=0;i<5;i++) scanf(“%d”,&a[i]); //One Dimensional array Sum and average Numbers #include<stdio.h> #include<conio.h> void main() { int a[10],n,i,sum=0; float avg=0.0; clrscr(); printf("Sum and average of given Numbers"); printf("nEnter the Limit Value:"); scanf("%d",&n); printf("nEnter the Values:"); for(i=0;i<n;i++) { scanf("%d",&a[i]); sum=sum+a[i]; } avg=(float)sum/n; printf("nSum = %d",sum); printf("nAverage = %.2f",avg); getch(); } OUTPUT: Sum and average of given Numbers Enter the Limit Value:5 Enter the Values:45 2 3 10 5 Sum = 65 Average = 13.00 2. Two Dimensional array: o Two dimensional arrays have two subscripts. o We need to store table of values use the 2D array. o Two pairs of square brackets denoted by rows and columns. Example: A[3][3]; Column-0 Column-1 Column-2 Row-0 Row-1 Row-2 That is represented as Columns Column-0 Column-1 Column-2 Row-0 A[0][0] A[0][1] A[0][2] Row-1 A[1][0] A[1][1] A[1][2] Row-2 A[2][0] A[2][1] A[2][2] Syntax: Datatype array_name[row_size][column_size]; Initialization: Rows
  • 3. 1. At compile time:  The values can be initialized at the time of declaration. Syntax: Datatype array_name[row_size][column_size]={List of Values}; Example: A[2][2]={{1,2}{3,4}}; Or A[2][2]={1,2,3,4}; 2. At run time:  The values can be initialized at the time of running.  Run time initialization can be do with the scanf() function. Example: int a[5][5],I,j; for(i=0;i<5;i++) for(j=0;j<5;j++) scanf("%d",&a[i][j]); Example: //Two Dimensional array or Matrix Multiplication #include<stdio.h> #include<conio.h> void main() { int a[2][2],b[2][2],c[2][2],j,i,k; clrscr(); printf("Matrix Multiplication"); printf("nEnter the A matrix 4 values:"); for(i=0;i<2;i++) for(j=0;j<2;j++) scanf("%d",&a[i][j]); printf("nEnter the B matrix 4 values:"); for(i=0;i<2;i++) for(j=0;j<2;j++) scanf("%d",&b[i][j]); printf("nResult Matrix:n"); for(i=0;i<2;i++) { for(j=0;j<2;j++) { c[i][j]=0; for(k=0;k<2;k++) c[i][j]= c[i][j]+a[i][k]*b[k][j]; } } for(i=0;i<2;i++) { for(j=0;j<2;j++) printf("%dt",c[i][j]); printf("n"); } getch(); } OUTPUT: Matrix Multiplication Enter the A matrix 4 values:1 2 3 4 Enter the B matrix 4 values:5 6
  • 4. 7 8 Result Matrix: 19 22 43 50 //Two Dimensional array or Matrix Addition #include<stdio.h> #include<conio.h> void main() { int a[2][2],b[2][2],c[2][2],j,i; clrscr(); printf("Matrix Addition"); printf("nEnter the A matrix 4 values:"); for(i=0;i<2;i++) for(j=0;j<2;j++) scanf("%d",&a[i][j]); printf("nEnter the B matrix 4 values:"); for(i=0;i<2;i++) for(j=0;j<2;j++) scanf("%d",&b[i][j]); printf("nResult Matrix:n"); for(i=0;i<2;i++) { for(j=0;j<2;j++) { c[i][j]=a[i][j]+b[i][j]; printf("%dt",c[i][j]); } printf("n"); } getch(); } OUTPUT: Matrix Addition Enter the A matrix 4 values:3 2 1 5 Enter the B matrix 4 values:4 6 8 2 Result Matrix: 7 8 9 7 Strings:  Group of (or) Collection of (or) Array of characters are called strings.  The strings are specified with pair of double quotes (“ “).  Where declaring a string it will take null character “0” at the end of string.  This null character cannot visible. Syntax: char array_name[]; Initialization:  The values of string can be initialized at run time or compile time.  The string values are initialized at compile time: Syntax: char array_name[]=”values”;
  • 5. Example: char name[]=”Senthil”;  The string values are initialized at run time using scanf(): Syntax: char array_name[]; scanf(“%s”,array_name); Example: char name[]; scanf(“%s”,name); Reading and Writing:  Reading & writing the string using scanf() & printf() function through the “%s” control string.  Also use the gets() and puts() functions. Syntax: Read Write scanf(“%s”,array_name); printf(“%s”,array_name); gets(array_name); puts(array_name); Example: char name[15]; printf(“Enter the name:”); scanf(“%s”,name); printf(“nName:%s”,name); OUTPUT: Enter the name:Senthil Name:Senthil String Handling (or) Standard Functions:  The ‘C’ compiler provides the following string handling functions: S.No. Function Purpose 1. strlen() Find length of the string 2. strcpy() Copy one string to another 3. strcat() Combine two strings 4. strcmp() Comparing two strings 5. strrev() Reverse a string 6. strlwr() Convert in to lower case 7. strupr() Convert into upper case 1. strlen():  This function is used to count & return the number of characters present in a string. Syntax: int var=strlen(string1); Example: char name[]=”Senthil”; int len1,len2; len1=strlen(name); len2=strlen(“Kumar”); printf(“%s length is %d”,name,len1); printf(“n%s length is %d”,”Kumar”,len1); OUTPUT: Senthil length is 7 Kumar length is 5 2. strcpy():  This function is used to copy the contents of one string to another . Syntax: strcpy(string1,string2);  The contents of string2 copy to string1. Example: char str1[]=”Senthil”,str2[]=”Kumar”; strcpy(str1,str2); printf(“String1=%snString2=%s”,str1,str2); OUTPUT: String1=Kumar String2=Kumar
  • 6. 3. strcat():  This function is used to concatenate (or) combine the two strings. Syntax: strcat(string1,string2); String2 is combined with string1 Example: char str1[]=”Senthil”,str2[]=”Kumar”; strcat(str1,str2); printf(“The combined string:%s”,str1); OUTPUT: The combined string:SenthilKumar 4. strcmp():  This function is used to compares two strings and find out whether they are same or different.  The two strings are compared character by character until end of one string is reached.  When two strings are equal it will give value “Zero” otherwise give any other value. Syntax: int var=strcmp(string1,string2); Example: char name1[]=”Kalai”,name2[]=”Malai”,name3[]=”Kalai”; int I,j; i=strcmp(name1,name2); j=strcmp(name1,name3); printf(“Comparison of %s & %s is %d”,name1,name2,i); printf(“nComparison of %s & %s is %d”,name1,name3,j); OUTPUT: Comparison of Kalai & Malai is 1 Comparison of Kalai & Kalai is 0 5. strrev():  This function is used to reverse a string. Syntax: strrev(string1); Example: char str1[]=”Senthil”; strrev(str1); printf(“Reversed String=%s”,str1); OUTPUT: lihtneS 6. strlwr():  This function is used to converts the characters of string into lower case characters. Syntax: strlwr(string1); Example: char str1[]=”SenThiL”; strlwr(str1); printf(“Converted lower case:%s”,str1); OUTPUT: Converted lower case:senthil 7. strupr():  This function is used to converts the characters of string into upper case characters. Syntax: strupr(string1); Example: char str1[]=”SenThiL”; strupr(str1); printf(“Converted upper case:%s”,str1); OUTPUT: Converted upper case:SENTHIL
  • 7.  A function is a set of instructions that are used to perform specified task. Types of Functions: i) User defined functions ii) Built in functions User Defined Functions:  The user defined functions has to be written by the programmer. Built in functions:  These functions are not required to be written by the programmer.  Built in functions also called as pre defined (or) library functions. Need for user defined function:  The program becomes too large & complex.  The users cannot go through at glance.  The task of debugging, testing & maintenance becomes difficult. Elements of functions:  The functions contain following three elements: FUNCTIONS:
  • 8. 1) Function declaration 2) Function Definition 3) Function calling Example: 1) Function Declaration:  The function can be declared before they are defined.  The parameters must match. Syntax: Return_type function_name(Parameter list); Return_type  Datatype of the return value Function_name  Name of the function Parameter list  List of parameters Example:
  • 9. Int add(int x, int y); or void add(); 2) Function Definition:  The function definition is the actual body of the function.  It is the process of specifying and establishing the operation. Syntax: Return_type function_name(parameter list) { Body of the function; Return data; } 3) Function call:  A function can be called by specifying its name, followed by a list of parameters.  The function definition may return a value to function call.  A semicolon (;) is used at the end of the statement. Syntax: Function_name(); (or) function_name(parameter); Value=function_name(parameter); Example: Fun(); or fun(a,b); C=fun(a,b); Parameters:  Parameters provide the data communication between the function call & function definition.  Parameters are also called as arguments. There are 2 types: i) Actual parameters ii) Formal parameters. Actual and formal parameters must match. i) Actual parameters: These parameters are present in the function call. ii) Formal parameters: These are present in the function definition. Example: Void main() { void sum(int x, int y) ……. { Body of the function; …… } Sum(a,b); ….. …… } Return Statement:  Value (or) information is returned from the function definition to the function call.  A function may contain more than one return statement.  Return type must be present in definition. Syntax: Return; (or) return(value (or) expression); Example: int first() int second() { {
  • 10. ….. …… …. … Return x*x; return a; } } Function prototypes:  The functions are classified into the following types depending on arguments present or not and the value is returned or not.  These are called as function prototypes. a) Function without arguments & no return values b) Function with arguments & no return vales c) Function with arguments & with return vales d) Function without arguments & with return vales a) Function without arguments & no return values:  Here, there is no data transfer between function call & function definition. i.e.,no arguments are passed from main function & no value is returned from the sub function. Syntax: Example: void sum(); void main() { sum(); } void sum() {
  • 11. int a,b,c; printf("enter the two values:"); scanf("%d%d",&a,&b); c=a+b; printf("sum =%d",c); } Output: enter the two values:10 20 sum =30 b) Function with arguments & no return values:  In this prototype, data is transferred from function call to the function definition.  The value does not return the function call so it is called one-way communication. Syntax: Example: void sum(int,int); void main() { int a,b; printf("enter the two values:"); scanf("%d%d",&a,&b); sum(a,b); } void sum(int x, int y) { int z; z=x+y; printf("sum=%d",z); } OUTPUT: enter the two values:10 20
  • 12. sum =30 c) Function with arguments & with return vales:  Here, the data is transferred between function call & function definition.  The value is returned to the function call. So it is called as two way communication. Syntax: Example: void main() { int a,b,c; clrscr(); printf(“enter the two values:”); scanf(“%d%d”,&a,&b); c=sum(a,b); printf(“sum=%d”,c); getch(); } void sum(int x, int y) { int z; z=x+y; return z; } Output: Enter the values: 5 10 Sum=15 d) Function without arguments & with return values:  Here, no data is transferred between function call & function definition.  But the value is returned from the function definition to the function cal.  So it is called as one way communication.
  • 13. Syntax: Example: void main() { int a,b,c; clrscr(); c=sum(); printf(“sum=%d”,c); getch(); } void sum(int x, int y) { int x,y,z; printf(“enter the two values:”); scanf(“%d%d”,&x,&y); z=x+y; return z; } OUTPUT: Enter the values: 5 10 Sum=15 Parameter Passing Methods There are 2 ways to pass a parameter inside the function. They are: i) Call by Value ii) Call by reference i) Call by Value:  This method copies the values of actual parameters into the formal parameters of the function.  The changes of the formal parameters cannot affect the actual parameters.  Because formal parameters are photocopy of the actual parameters. Syntax:
  • 14. void main() { ………… swap(a,b); ………. } swap(int a,int b) { int temp; …………. } Example: void swap1(int,int); void main() { int a=10,b=20; clrscr(); printf("before swap: a=%dt b=%d",a,b); swap1(a,b); printf("nafter swap: a=%dt b=%d",a,b); } void swap1(int x, int y) { int t; t=x; x=y; y=t; printf("nIn function a=%dt b=%d",x,y); } OUTPUT: before swap: a=10 b=20 In function a=20 b=10 after swap: a=10 b=20 ii) Call by reference:  Call by reference is the addresses of actual parameters are copied into the formal parameters inside the function.  The address is used to access the actual parameters inside the function also.  So, Changes made in parameters are permanent.  Here pointers are used to store the address. Syntax: void main() { ………….. swap(address of variable); …………
  • 15. } void swap(pointer variable) { ……….. } Example: void swap(int*,int*); void main() { int a=10,b=20; clrscr(); printf("before swap: a=%dt b=%d",a,b); swap(&a,&b); printf("nafter swap: a=%dt b=%d",a,b); } void swap(int *x, int *y) { int t; t=*x; *x=*y; *y=t; } OUTPUT: before swap: a=10 b=20 after swap: a=20 b=10 Recursion:  Recursion takes the form of function that calls itself.  A process being performed where one of the instructions is to repeat the process.  It is similar to looping.  Recursion is the process of calling the same function itself again and again until some condition is satisfied. Syntax: void function1(); { --- --- function1(); }  The above function function1() is called themselves continuously. Example: void main() { int n,f; printf("Enter the Number:");
  • 16. scanf("%d",&n); printf("nThe factorial of %d = %d",n,fact(n)); } int fact(int x) { int f; if(x==1) return 1; else f=x*fact(x-1); return f; } OUTPUT: Enter the Number:5 The factorial of 5 = 120 Tower of Hanoi:  The Tower of Hanoi is a mathematical game or puzzle.  It consists of three rods, and a number of disks of different sizes which can slide onto any rod.  The puzzle starts with the disks in a neat stack in ascending order of size on one rod, the smallest at the top, thus making a conical shape. The objective of the puzzle is to move the entire stack to another rod, obeying the following simple rules: 1. Only one disk can be moved at a time. 2. Each move consists of taking the upper disk from one of the stacks and placing it on top of another stack i.e. a disk can only be moved if it is the uppermost disk on a stack. 3. No disk may be placed on top of a smaller disk. With three disks, the puzzle can be solved in seven moves. The minimum number of moves required to solve a Tower of Hanoi puzzle is 2n - 1, where n is the number of disks.
  • 17.  A pointer is a variable that is used to store the address of another variable.  It is declared like other variables and also it is always denoted by asterisk “*” operator.  Each variable has two attributes: o Address o Value  It can be used to access and manipulate data stored in the memory.  Ordinary Variable: int a=5; aaccess the value &a access the address of variable. a variable 5 value 4002 address Syntax: Data_type *pointer_variable; Example: int *p; Advantages: 1. It is increase the speed of execution. 2. It is saving memory space. 3. It enables us to access the memory directly. 4. It is also provide an alternate way to access an array. 5. Multiple data items can receive in the function. Initializing pointer:  The process of assigning the address of a variable to a pointer variable is called initialization.  The location of the variable in system memory.  This can be achieved through the ampersand(&) symbol.  The ampersand(&) symbol is an address operator. Unit-4 Pointers and Structures POINTERS
  • 18.  It takes the address of the variable.  Pointers must be initializing with assigning address of the variable. Example: void main() { int a=10,*p; p=&a; printf("n*p=%dtp=%dt&p=%dt&a=%d",*p,p,&p,&a); } OUTPUT: *p=10 p=-12 &p=-14 &a=-12  *pvalue of the address stored in pointer variable.  Paddress of the variable.  &paddress of the pointer variable.  &aaddress of the variable. a variable *p 10 value -12 -12 address -14 Pointer Arithmetic:  C pointer is an address, which is a numeric value.  Therefore, you can perform arithmetic operations on a pointer just as you can a numeric value.  There are four arithmetic operators that can be used on pointers: ++, --, +, and - Data type Initial Address operation address after operation bytes of data type char 4000 ++ 4001 1 char 4000 -- 3999 1 int 4000 ++ 4002 2 int 4000 -- 3998 2 float 4000 ++ 4004 4 float 4000 -- 3996 4 Incrementing a Pointer  Incrementing pointer is generally used in array.  The variable pointer to access each succeeding element of the array.  Incrementing pointer variable depends upon datatype of the pointer variable. Example: void main () { int var[] = {10, 100, 200}; int i, *ptr; ptr = var; for ( i = 0; i < 3; i++) { printf("nAddress of var[%d] = %u", i, ptr ); printf("nValue of var[%d] = %d", i, *ptr ); ptr++; } } OUTPUT:
  • 19. Address of var[0] = 65520 Value of var[0] = 10 Address of var[1] = 65522 Value of var[1] = 100 Address of var[2] = 65524 Value of var[2] = 200 Decrementing a Pointer  The same considerations apply to decrementing a pointer, which decreases its value by the number of bytes of its data type as shown below: Example: void main () { int var[] = {10, 100, 200}; int i, *ptr; ptr = &var[3-1]; for ( i = 3; i > 0; i--) { printf("Address of var[%d] = %un", i, ptr ); printf("Value of var[%d] = %dn", i, *ptr ); ptr--; } } OUTPUT: Address of var[3] = 65524 Value of var[3] = 200 Address of var[2] = 65522 Value of var[2] = 100 Address of var[1] = 65520 Value of var[1] = 10 Pointers and Arrays or Pointers and Functions: • The elements of the array can also be accessed through a pointer. • Pointers also send the array to functions. Syntax: Pointer_variable=array_name; Example: void fun(int[]); void main() { int a[3]={10,20,30},*p; p=a; fun(p); } void fun(int b[]) { int i,total=0;
  • 20. for(i=0;i<3;i++) total=total+b[i]; printf("nTotal=%d",total); } OUTPUT: Total=60 Structures:  Structure is a compound datatype.  It stores different type of data items.  It is used to store dissimilar data items.  Structure is creating with the “struct” keyword.  It is the one of the storage unit.  Different type of data items can be store in different memory space.  The elements of structure are called members.  It must be declare and defined. Structure Declaration and Definition:  It must be declare and defined.  Structure is creating with the “struct” keyword.  Structure finished declaration with semicolon(;).  Accessing members with dot(.) operator. Syntax: struct structure_name { Datatype variables; ---- }; Creating structure Variable: struct structure_name structure_variable; Structures FLOAT INT CHAR DOUBLE Structures and Union
  • 21. Accessing structure Member: structure_variable.member; Difference between structure and array: S.No. Array Structure 1. It is a collection of similar data items. it is collection of dissimilar data items 2. It is derived data type. It is a user defined data type. 3. It behaves like a built-in data types. It must be declared and defined. 4. An array can be increase or decrease. Its members can be added. Example: //Student Details using Structure struct stud { int regno,m1,m2,m3,total; char name[20],result[5]; }; void main() { struct stud s1,s2; printf("nStructures"); printf("nEnter the Regno, Name:"); scanf("%d%s",&s1.regno,s1.name); printf("nEnter the Mark1, Mark2, Mark3:"); scanf("%d%d%d",&s1.m1,&s1.m2,&s1.m3); s1.total=s1.m1+s1.m2+s1.m3; if(s1.m1<50||s1.m2<50||s1.m3<50) strcpy(s1.result,"Fail"); else strcpy(s1.result,"Pass"); s2=s1; //Assigning structure printf("RegnotNametMark1tMark2tMark3tTotaltResultn"); printf("%dt%st%dt%dt%dt%dt%s",s1.regno,s1.name,s1.m1,s1.m2,s1.m3,s1.total,s1.result); printf("nStructure--2"); printf("nRegnotNametMark1tMark2tMark3tTotaltResultn"); printf("%dt%st%dt%dt%dt%dt%s",s2.regno,s2.name,s2.m1,s2.m2,s2.m3,s2.total,s2.result); getch(); } OUTPUT: Enter the Regno, Name:345 kumar Enter the Mark1, Mark2, Mark3:67 78 61 Regno Name Mark1 Mark2 Mark3 Total Result 345 kumar 67 78 61 206 Pass Structure--2 Regno Name Mark1 Mark2 Mark3 Total Result 345 kumar 67 78 61 206 Pass Structure within structure:  A structure can be declared within another structure.  It is also called nesting of structure.  The structure variables can be normal variable or pointer variable.
  • 22.  Nesting of more than one type of structure is allowed.  Structure cannot be nested within itself. Syntax: struct struct_1 { ---- ---- }; struct struct_2 { ---- ---- struct struct_1 s1; }; Example: // Structure within structure struct college_detail { int college_id; char college_name[20]; }; struct student_detail { int regno; char name[20]; float percent; struct college_detail c1; }; void main() { struct student_detail s1={703,"kumar",87.3,1300,"XYZ college"}; printf("nStructures within Structuren"); printf("RegnotNametpercentagetCollege IDtCollege Namen"); printf("%dt%st%ft%dt%s",s1.regno,s1.name,s1.percent,s1.c1.college_id,s1.c1.college_name); getch(); } OUTPUT: Structures within Structure Regno Name percentage College ID College Name 703 kumar 87.300003 1300 XYZ college Example: //Employee Details using Structure void dummy(float *a) { float b=*a; //perform some floating access dummy (&b); //calling a floating point function } struct employee1 { int empno; char name[10]; float salary; };
  • 23. void main() { struct employee1 e[10]; int i,n; printf("nEnter the no.of Employees:"); scanf("%d",&n); for(i=0;i<n;i++) { printf("nEnter the employee empno,name,salary:"); scanf("%d%s%f",&e[i].empno,e[i].name,&e[i].salary); } printf("nEmployee Detailsn"); printf("nEMPNOtNAMEtSALARY"); for(i=0;i<n;i++) printf("n%dt%st%.2f",e[i].empno,e[i].name,e[i].salary); getch(); } OUTPUT: Enter the no.of Employees:2 Enter the employee empno,name,salary:23 Raj 5000 Enter the employee empno,name,salary:24 Kumar 3500 Employee Details EMPNO NAME SALARY 23 Raj 5000.00 24 Kumar 3500.00 Union • A Union is a collection of different data items, which are stored under a common name. • Here same memory is shared by its members. • The keyword union is used to define a union. • Size of union is equal to the size of largest member. • Memory allocated is shared by individual members of union. • The address is same for all the members of a union. • Altering the value of any of the member will alter other member values. • Only one member can be accessed at a time. • Only the first member of a union can be initialized. Syntax: union union_name
  • 24. { union element1; union element2; ………………… }; Example: union result { int mark; float avg; char grade; }; union result s; Structure Union 1.The keyword struct is used to define a structure 1. The keyword union is used to define a union. 2. The size of structure is greater than or equal to the sum of sizes of its members. 2. Size of union is equal to the size of largest member. 3. Each member within a structure is assigned unique storage area of location. 3. Memory allocated is shared by individual members of union. 4. The address of each member will be in ascending order. 4. The address is same for all the members of a union. 5 Altering the value of a member will not affect other members of the structure. 5. Altering the value of any of the member will alter other member values. 6. Individual member can be accessed at a time 6. Only one member can be accessed at a time. 7. Several members of a structure can initialize at once. 7. Only the first member of a union can be initialized. Example: void dummy(float *a) { float b=*a; //perform some floating access dummy (&b); //calling a floating point function } union employee1 { int empno; char name[10]; float salary; }; void main() { union employee1 e[10]; int i,n; printf("nEnter the no.of Employees:"); scanf("%d",&n); for(i=0;i<n;i++) { printf("nEnter the employee empno,name,salary:"); scanf("%d%s%f",&e[i].empno,e[i].name,&e[i].salary); } printf("nEmployee Detailsn"); printf("nEMPNOtNAMEtSALARY"); for(i=0;i<n;i++)
  • 25. printf("n%dt%st%.2f",e[i].empno,e[i].name,e[i].salary); getch(); } OUTPUT: Enter the no.of Employees:2 Enter the employee empno,name,salary:23 Raj 5000 Enter the employee empno,name,salary:24 Kumar 3500 Employee Details EMPNO NAME SALARY 16384 5000.00 -16384 3500.00 Preprocessor:  It is a program that processes the source program before compilation.  The C preprocessor executes before a program is compiled.  Preprocessor directives begin with # and only white-space characters and comments may appear before a preprocessor directive on a line.  It operates under the following directives 1. File Inclusion 2. Macro substitution 3. Conditional inclusion File Inclusion: • It is used to include some file that contains functions or some definitions. • Copy of a specified file included in place of the directive Syntax: #include<filename> Searches standard library for file (or) #include“filename” Searches for user-defined files Example: #include<stdio.h> #include<conio.h> #include "addition.txt" void main() { int a,b; printf("nEnter the numbers:"); scanf("%d%d",&a,&b); printf("The Value is %d",add(a,b)); getch(); } addition.txt int add(int a,int b) { return(a+b); } OUTPUT: Enter the numbers:7 4 The Value is 11
  • 26. Macro Substitution: • It is used to define and use integer, string, or identifier in the source program • The three forms of macros are – Simple Macro – Argumented Macro – Nested Macro 1) Simple Macro:  It is used to define some constants. Syntax #define identifier string/integer Example: #include<stdio.h> #include<conio.h> #define pi 3.14 #define CITY "chennai" void main() { printf("The Value is %f",2*pi); printf("nThe Value CITY is %s",CITY); getch(); } OUTPUT: The Value is 6.280000 The Value CITY is chennai 2) Argumented Macro • It is used to define some complex forms in the source program. Syntax: #define identifier (v1,v2,….) string/integer Example: #include<stdio.h> #include<conio.h> #define cube(n) (n*n*n) void main() { printf("The Value of 3 cube is %d",cube(3)); getch(); } OUTPUT: The Value of 3 cube is 27 3) Nested Macro  Here one macro is used by another macro. Example: #include<stdio.h> #include<conio.h> #define a 3 #define sq a*a void main() { printf("The Value is %d",sq); getch(); } Output: The Value is 9
  • 27. Conditional Inclusion:  It is used to include some conditional statements. Example: #include<stdio.h> #include<conio.h> #define a 3 #ifdef a #define c a+5 #endif void main() { printf("nThe value C is %d",c); getch(); } Output: The value C is 8