Program:
#include <stdio.h>
#include <conio.h>
void main()
{
int i=1, j;
while(i<=3)
{
for(j=1; j<=3; j++)
{
printf(" * ");
if(j==2)
goto stop;
}
i = i + 1;
}
stop:
printf("\n Exited !");
}
Output :
**
Exited
Functions:
1. Functions
2. Types of Functions:
Built in functions
User defined functions
3. Types of function definition or Types of function declaration
4. Categories of functions
5. Parameter passing mechanism
6. Advantages
7. Recursion
Functions in C :
The function is a self contained block of statements which performs a coherent task of a same kind.
C program does not execute the functions directly. It is required to invoke or call that functions. When a function is called in a
program then program control goes to the function body. Then, it executes the statements which are involved in a function body.
Therefore, it is possible to call fuction whenever we want to process that functions statements.
Types of functions :
There are 2(two) types of functions as:
1. Built in Functions
2. User Defined Functions
1.Built in Functions :
These functions are also called as 'library functions'. These functions are provided by system. These functions are stored in library
files.
Examples:
scanf()
printf()
strcpy ()
tolower ()
toupper()
strcmp ()
strlen ()
strcat ()
2.User Defined Functions :
The functions which are created by user for program are known as 'User defined
functions'.
Syntax:
void main()
{
<return_type><function_name>([<argu_list>]); // Function prototype
<function_name>([<arguments>]); // Function Call
}
<return_type> <function_name>([<argu_list>]) // Function definition
{
<function_body>;
}
Example Program:
#include <stdio.h>
#include <conio.h>
void add()
{
int a, b, c;
printf("\n Enter Any 2 Numbers : ");
scanf("%d %d",&a,&b);
c = a + b;
printf("\n Addition is : %d",c);
}
void main()
{
void add();
add();
}
Output :
Enter Any 2 Numbers : 23 6
Addition is : 29
Advantages :
It is easy to use.
Debugging is more suitable for programs.
It reduces the size of a program.
It is easy to understand the actual logic of a program.
Highly suited in case of large programs.
By using functions in a program, it is possible to construct modular and structured programs.
Reusability
Types of function definition or Types of function declaration:
There are different methods to define functions. The following two ways are used in defining functions:
1. NonANSI style
2. ANSI style
Non-ANSI style:
The general form of a NonANSI function definition is as follows.
type name_of_function (parameter_list)
parameter definition;
{
variable declaration; //with in the function
statement1;
statement2;
...
...
...
return(value_computed); //returns(sends) the output result to calling function
}
where,
type........................................datatype of return value
name_of_function..................user defined function
parameter_list.......................parameters received from calling function
parameterdefinition..............type declaration of parameters of parameter_list
Note: All the statements that are placed between the left brace and the corresponding right brace would constitute the body of a
function.
Example: To calculate sum of two integers by using functions concept(Non-ANSI style).
#include<stdio.h>
main(){
int a,b,sum;
scanf("%d%d",&a,&b);
sum=add(a,b); //passing parameters to calling function (add)
printf("sum=%d",sum);
}
int add(x,y) //called function
int x,y;
{
int k;
k=x+y;
return k;
}
ANSI style:
The general form of an ANSI function definition is as follows.
type name_of_function (parameter definition)
{
variable declaration; //with in the function
statement1;
statement2;
...
...
...
return(value_computed); //returns(sends) the output result to calling function
}
where,
type........................................datatype of return value
name_of_function..................user defined function
parameterdefinition..............type declaration of parameters of parameter_list
Example: To calculate sum of two integers by using functions concept(ANSI style).
#include<stdio.h>
main(){
int a,b,sum;
scanf("%d%d",&a,&b);
sum=add(a,b); //passing parameters to calling function (add)
printf("sum=%d",sum);
}
int add(int x,int y) //called function
{
int k;
k=x+y;
return k;
}
Note1:
In the NonANSI style, only a list of parameters was given and all these parameters were separated by a comma. But, in the ANSI
style the parameter list is replaced by the parameter definition.
Note2:
Most of today’s compilers use the ANSI style. Therefore, it is necessary for the programmers to write the programs using the ANSI
style of function definition.
Categories of function:
We have some other types of functions where the arguments and the return value may be present or absent. Such functions can be
categorized into:
1. No arguments and no return value
2. Arguments but no return value
3. No arguments but return value
4. Arguments and return value
1.Functions with No Arguments and No Return values :
Here, the called function does not receive any data from the calling function. And, it does not return any value back to the calling
function. Hence there is no data transfer between the calling function and the called function.
Example:
//Write a C Program to illustrate the func&on with no arguments and no return value
#include<stdio.h>
main()
{
read_value(); //calling function
}
read_value() // No return value and is a called function
{
char name[10];
printf("Enter your name:\n");
scanf("%s",name);
printf("your name is %s\n",name);
}
2. Functions with Arguments but No Return Value :
Here, the called function receives the data from the calling function. The arguments and parameters should match in number, data
type and order. But, the called function does not return any value back to the calling function.Instead, it prints the data in its scope
only. It is a oneway data communication between the calling function and the called function.
Example:
#include<stdio.h>
main(){
int a,b,sum;
scanf("%d%d",&a,&b);
add(a,b);
}
int add(int x,int y) //called function
{
int k;
k=x+y;
printf("sum=%d",k);
}
3.Funcitons with No Arguments and Return Values :
Here, the called function does not receive any data from the calling function. It manages with its local data to perform the specified
taks. However, after the specified processing the called function returns the computed data to the calling function. It is also a one
way data communication between the calling function and the called function.
Example:
#include<stdio.h>
main(){
int sum;
sum=add();
printf("sum=%d",sum);
}
int add() //called function
{
int a,b,k;
scanf("%d%d",&a,&b);
k=a+b;
return k;
}
4.Arguments and return value:
Here, the called function receives data from the calling function.After the specified processing the called function returns the
computed data to the calling function. It is a twoway data communication between the calling function and the called function.
Example:
#include<stdio.h>
main(){
int a,b,sum;
scanf("%d%d",&a,&b);
sum=add(a,b);
printf("sum=%d",sum);
}
int add(int x,int y)
{
int k;
k=x+y;
return k;
}
Parameter passing mechanism:
The process of transmtting the values from one function to other is known as parameter passing. There are two methods of
parameter passing
1. Call by value
2. Call by reference
1.Call by value:
when the values of the arguments are passed from a calling function to a called function the values are copied into the called
function.If any changes are made to the values in the called function, there will not be any change in the orginal values within the
calling function.
Example:
#include<stdio.h>
#include<math.h>
main()
{
int a,b,x;
int hi(int x,int y);
a=10;b=20;
printf("a=%d\tb=%d\n",a,b);
x=hi(a,b);
printf("a=%d\tb=%d\n",a,b);
printf("x=%d\n",x);
}
int hi(int x,int y)
{
int sum;
sum=x+y;
x=pow(x,2);
y=sqrt(x);
printf("x=%d\ty=%d\n",x,y);
return sum;
}
Output:
a=10 b=20
x=100 y=10
a=10 b=20
x=30
Note: There is no change in the values of a and b before and after the function execution .
2. Call-by-Reference :
In this method, the actual values are not passed, instead of their values addresses are passed to a calling function. Here, no values
are copied as the memory locations themselves are referenced. If any modification is made to the values in the called function, then
the orginal values will get changed within the calling function. Passing of addresses requires the knowledge of pointers.
Note:When the pointers are passed as arguments, the following two points must be considered.
1.In the calling function, the function is invoked with the function name and addresses of actual parameters enclosed within the
parentheses.
i.e., function_name(&var1, &var2, ......, &varn);
where, var1, var2, . . . . , varn are actual parameters(arguments)
2.In the parameter list of the called function each and every formal parameter (pointers) must be preceded by an indirection
operator (*).
i.e. data_type function_name(*var1, *var2, . . . *varn) ;
Example:
#include<stdio.h>
main()
{
int a,b;
int hi(int *x,int *y); //function prototype
a=10;b=20;
printf("--------Before calling function-----------\n\ta=%d\tb=%d\n",a,b); //Before calling function
hi(&a,&b); //function call
printf("--------After calling function-----------\n\ta=%d\tb=%d\n",a,b); //after calling function
}
int hi(int *x,int *y)
{
int temp;
temp=*x;
*x=*y;
*y=temp;
}
Output:
--------Before calling function-----------
a=10 b=20
--------After calling function-----------
a=20 b=10
Recursion:
When a function of body calls the same function then it is called as 'recursive function.'
Example:
Recursion()
{
printf(“Congratulations\n”);
Recursion();
}
The two basic phases of a recursive process:
winding(recursive or tail part)
unwinding(basic or terminating part).
In the winding phase, each recursive call perpetuates the recursion by making anadditional recursive call itself. The winding phase
terminates when one of the calls reaches a terminating condition.
A terminating condition defines the state at which a recursive function should return instead of making another recursive call .
Every recursive function must have at least one terminating condition otherwise, the winding phase never terminates. Once the
winding phase is complete, the process enters the unwinding phase, in which previous instances of the function are revisited in
reverse order. This phase continues until the original call returns, at which point the recursive process is complete.
Note: In the recursion process we use the stack principle(Last-In-First-Out) to obtain the result.
Types of Recursion:
1. Basic Recursion
2. Tail Recursion
Example for Basic Recursion:
#include<stdio.h>
main(){
int a,f;
printf("Enter a no: ");
scanf("%d",&a);
f=fact(a);
printf("%d\n",f);
}
fact(int x){
if(x==0)
return 1;
else
return x*fact(x-1);
Tail Recursion:
A recursive function is said to be tail recursive if all recursive calls within it are tail recursive. A recursive call is tail recursive
when it is the last statement that will be executed within the body of a function and its return value is not a part of an
expression. Tail-recursive functions are characterized as having nothing to do during the unwinding phase.
Example for Tail Recursion:
#include<stdio.h>
main(){
int a,f,b=1;
printf("Enter a no: ");
scanf("%d",&a);
f=fact(a,b);
printf("%d\n",f);
}
fact(int x,int y){
if(x==0)
return y;
else
return fact(x-1,x*y);
Features :
1. There should be at least one if statement used to terminate recursion.
2. It does not contain any looping statements.
Advantages :
1. It is easy to use.
2. It represents compact programming strctures.
Disadvantages :
1. It is slower than that of looping statements because each time function is called.
Note : It can be applied to calculate factorial of a number, fibonancci series,GCD of integers.
Array:
Basically array is a static datastructure.It is a collection of homogenous data stored under unique name. The values in an array is
called as 'elements of an array.' These elements are accessed by numbers called as 'subscripts or index numbers.' Arrays may be of
any variable type. Array is also called as 'subscripted variable.'Arrays of any type can be formed in C.
Syntax:
datatype Array_name[dimension or length];
Arrays can be created from any of the C data types int, float, char.In C, arrays starts at position 0. The elements of the array
occupy adjacent locations in memory.
Unsized array initialisation:
If unsized arrays are declared, the C compiler automatically creates an array big enough to hold all the initializers. This is called
an unsized array.
Example declaration/initializations are as follows:
char e1[] = "read error\n";
char e2[] = "write error\n";
int sgrs[][2] =
{
1,1,
2,4,
3,9
4,16,
};
Array Initialization:
Arrays may be initialized at the time of declaration.
The following example initializes a ten-element integer array:
int i[10] = { 1,2,3,4,5,6,7,8,9,10 };
another Example:
char str[9] = "I like C"; (or)
char str[9] = { 'I',' ','l','i','k','e',' ','C','\0' };
When the string constant method is used, the compiler automatically supplies the null terminator.
Multi-dimensional arrays are initialized in the same way as single-dimension arrays, e.g.:
int sgrs[6][2] =
{
1,1,
2,4,
3,9,
4,16,
5,25,
6,36
};
Types of an Array :
1. Single Dimensional Array or 1D array
2. Multiple Dimensional Array (which may 2D,3D,......nD,etc. Array)
Single dimensional array:
The array which is used to represent and store data in a linear form is called as “single or one dimensional array.”
Syntax:
<data-type> <array_name> [size];
Example:
int a[3] = {2, 3, 5};
char ch[20] = "TechnoExam" ;
float stax[3] = {5003.23, 1940.32, 123.20} ;
Total size(in bytes):
total size = length of array * size of data type;
Example:
In above example, 'a' is an array of type integer which has storage size of 3 elements. The total size would be 3 * 4 = 12 bytes
Memory Allocation :
Memory allocation for one dimensional array is given below
A[0] A[1] A[2] Upto A[n]
5 -8 77 23
Example Program: Calulate sum of the given integers.
#include<stdio.h>
main()
{
int i,n;
printf("Enter the length of an array:");
scanf("%d",&n);
int array[n],k;
printf("Enter array elements...\n");
for(i=0;i<n;i++)
{
scanf("%d",&k);
array[i]=k; //Reading array elements
}
int sum=0;
for(i=0;i<n;i++)
{
sum=sum+array[i]; //Adding array elements
}
printf("sum=%d\n",sum);
}
Features :
Array size should be positive number only.
String array always terminates with null character ('\0').
Array elements are countered from 0 to n-1.
Useful for multiple reading of elements (numbers).
Disadvantages :
There is no easy method to initialize large number of array elements.
It is difficult to initialize selected elements.
Two Dimensional Array :
The array which is used to represent and store data in a tabular form is called as 'two dimensional array.' Such type of array
specially used to represent data in a matrix form.
Syntax:
<data-type> <array_name> [no.rows][no.columns];
Total size(in bytes):
Total size = no.rows*no.columns * size of data type;
Example:
int a[3][4];
In above example, a is an array of type integer which has storage size of 3 * 4 matrix. The total size would be 3 * 4* 4 = 48 bytes.
It is also called as 'multidimensional array.'
A[0][0] A[0][1] A[0][2] A[0][3]
A[1][0] A[1][1] A[1][2] A[1][3]
A[2][0] A[2][1] A[2][2] A[2][3]
Note: Where A[i][j].........Represents the element which is in the position i and j.
Example: Read and display a 3*3 matrix
Program:
#include<stdio.h>
main(){
system("clear");
int i,j;
int matrix[3][3];
printf(".....Enter the array elements.......\n");
for(i=0;i<3;i++)
{
for(j=0;j<3;j++)
{
scanf("%d",&matrix[i][j]);
}
}
printf("........The given matrix is.........:\n");
for(i=0;i<3;i++)
{
for(j=0;j<3;j++)
{
printf("%8d",matrix[i][j]);
}
printf("\n");
}
}
Iutput:
.....Enter the array elements.......
4
9
2
5
2
9
4
2
8
Output:
........The given matrix is.........:
4 9 2
5 2 9
4 2 8
Limitations of two dimensional array :
We cannot delete any element from an array.
If we dont know that how many elements have to be stored in a memory in advance, then there will be memory wastage if
large array size is specified.
Note: The dimensions of a array is depends on the number of pair of brackets which are representing in the array declaration.
Ex:if we have 4 pair of brackets in the array declaration i.e.,the 4D array.
Structure :
A structure is a collection of one or more variables, possibly of different data types, grouped together under a single name for
convenient handling.Keyword 'struct' is used to declare structure.
The variables which are declared inside the structure are called as 'members of structure'.
Syntax:
struct structure_nm
{
<data-type> element 1;
<data-type> element 2;
-----------
-----------
<data-type> element n;
}struct_var;