DEFINTION OF A FUNCTION

A function  is a self- contained block of executable code that can be called from any other function. In many programs, a set 0f statements are to be executed repeatedly at various places in  the program and may with different sets of data, the idea of functions  comes in mind. You keep those repeating statements in a function and call them as  and when required .When a function is called, the control transfers to the called function, which will  be executed, and then transfers the control back to the calling function.
Example
 Program to illustrate a function

#include <stdio.h>

main()

{
 void sample( );
  printf("/n You are in main");
}
vold sample( )
{
pirintf ("\n You are in sample");
 }


OUTPUT 
You are in sample
 You are in main

 Here we are calling a function sample ( ) through main( ) i.e. control of execution transfers from main( ) to sample( ) , which means main( ) is suspended for some time and sample() is executed. After its execution the control returns back to main( ), at the statement following function call and the execution of main( ) is resumed.


The syntax of a function is:
return data type function_name (list of arguments)
{
datatype declaration of the arguments;
executable statements;
 return (expression);
}
where,
1) return data type is the same as the data type of the variable that is returned by the function using return statement.
2) a function_name is formed in the same way as variable names identifiers are formed.
3)the list of arguments or parameters are valid variable names as shown below. separated by commas: (data type1 var I .data type2 var2,  data type n var n)
 for example (int x, float y, char z).
4)arguments give the values which are passed from the calling function.
5)the body of function contains executable statements.
6)the return statement returns a single value to the calling function .

Example

Let us write a simple function that calculates the square of an integer .
/* Program to calculate the square of given integer*/

/* square( ) function */
 {
int square (int no)
 int result ;
 result=no*no;
 return (result);
}

main(){
 int n .sq;
printf(Enter a number to calculate square value");
scanf("%d",&n);
sq=square(n);
printf("\n square of the number is : %d",sq) ;
}

OUTPUT
Enter a number to calculate square value 5
 Square of the number is : 25




Mi Smart Band 4- India's No.1 Fitness Band, Up-to 20 Days Battery Life, Color AMOLED Full-Touch Screen, Waterproof with Music Control and Unlimited Watch Faces
  • The Mi Smart Band 4 features a 39.9% larger (than Mi Band 3) AMOLED color full-touch display with adjustable brightness, so everything is clear as can be
  • With music control on the band you can change the song, increase/decrease the volume and groove on without even touching your phone
  • With a sturdy 5ATM waterproof built, you can now take your band for a swim. It auto detects your swim style and captures 12 detailed data points for tracking
  • Health and wellness tracking at its best with 24/7 automatic heart rating monitoring and alerts to warn you when the heart rate is high
  • Style the band display as per your mood with unlimited watch faces. Simply pick a photo from your gallery and set it as your watch face
  • With the band on your wrist, you can receive text messages, silence or reject calls, and get social media notifications instantly
  • Up to 20 days of long lasting battery life for uninterrupted performance
  • Start your day right by understanding your sleep pattern with accurate light and deep sleep monitoring
  • 30+ features rolled into one band, your perfect companion

Built in String Functions and applications

The header file string.h (<string.h>) contains some string manipulation functions.


Strlen Function

The Strlen function returns the length of a string.It takes the string name as argument.

n=strlen(str);

where str is name of the string and n is the length of the string ,return by strlen function.

 Example
Write a program to read a string from the keyboard and display the length of the string on to the monitor by using strlen() function.

#include<stdio.h>
#include<string.h>

main()
{
char name[80];
int length;
printf("Enter your name:");
gets(name);
length=strlen(name);
printf("Your name has %d characters \n,"length);
}

OUTPUT
Enter your name: TYRAN
your name has 5 characters

Strcpy Function

In C,you cannot simplify assign one character array to another .You have to copy element by element.The string library <string.h> contains a function called strcpy for this purpose.The strcpy function is used to copy one string to another .The syntax is as follows:

strcpy(str1,str2);

where str1,str2 are two strings.the content of string str2 is copied on to string str1.

EXAMPLE

Write a program to read a string from the keyboard and  copy 5the string onto the second string and display the strings on to the  monitor by using strcpy() function.

#include<stdio.h>
#include<string.h>
main()
{
char first[80],second[80];
printf("Enter a string :");
 gets(first);
strcpy(second,first);
printf("\n First string is : %s,and second string is : %s\n",first,second);
}

OUTPUT
Enter a string : HONEY
First string is : HONEY, and second string is : HONEY

Strcmp Function

The strcmp function in the string library function which compares two strings, character by character and stops comparison when there is a difference in the ASCII value or the end of any one string and returns ASCII difference of the characters that is integer.If the return value zero means the two strings are equal ,a negative value means the first string is less than second,and a positive value means first greater than second.

n=strcmp(str1,str2);

where str1 and str2 are two strings to be compared and n is the returned value of differed characters.

EXAMPLE

Write a program to compare two strings.

#include<stdio.h>
#include<string.h>
main()
{
 char first[80],char second[80];
int value;
printf("Enter a string:");
gets(first);
printf("Enter another string:");
gets(second);
value=strcmp(fisrt,second);
if(value==0)
puts("The two strings are equal");
else if (value<0)
puts("The first  string is smaller");
else if (value>0)
puts("the first string is bigger");
}

OUTPUT
Enter a string :DOG
Enter another string :DOGGY
The first string is smaller


Strrev Function 

The strrev function reverse the given string.

strrev(str);

where string str will be reversed.

EXAMPLE

Write a program to reverse  a given string.

#include<stdio.h>
#include<string.h>

main()
{
char first[80];
printf("Enter a string:");
gets(first);
printf("\n Reverse if the given string is : %s",strrev(first));
 } 
 
 OUTPUT
Enter a string:PANKAJ
Reverse of the given string is :JAKNAP

Strspn Function

The  strspn function returns the position of the string,where first string mismatches with second string.

n=strspn(first,second);

where  first and second are two strings to be compared ,n is the number of character from which first string does not match with second string.

#include<stdio.h>
#include<string.h>

main()
{
char first[80],second[80];
printf("Enter first string:");
gets(first);
printf("\n Enter second string:");
gets(second);
printf("\n After %d characters there is no match ",strspn(first,second));
}

OUTPUT
Enter first string:ALEXANDER
Enter second string:ALEXSMITH
After 4 characters there is no match.
 

Display of Strings using different formatting techniques

The  printf  function with %s format is used to display the strings on the screen.For example ,the below statement display entire string:

printf("%s",name);

we can also specify the accuracy with which character array (string) is displayed .For example ,if you want to display first 5 characters from a field width of 15 characters ,you have to write as :

printf("15.5s",name);

if you include minus sign in  the format,the string will be printed left justified.
printf("%-10.5s",name);


EXAMPLE

Write a program to display the string "UNIX" in the following format.

U
UN
UNI
UNIX
UNIX
UNI
UN
U


#include<stdio.h>

main()
{
int x,y;
static char string[] ="UNIX";
printf("\n");
for(x=0;x<4;x++)
{
y=x+1;
printf("%-4,*s \n",y,string);

 }
for(x=3;x>=0;x--)
{
y=x+1;
printf("%-4.*s \n",y,string);

}
}

OUTPUT
U
UN
UNI
UNIX
UNIX
UNI
UN
U


Array of Strings
Array of strings are multiple strings,stored in the form of table.Declaring array of strings is same as strings,except it will have additional dimension to store the number of strings .Syntax is as follows:

char array-name[size][size];

For example,
char names[5][10]; 
where names is the name of the character array and the constant in the first square brackets will give number of string we are going to store ,and the value in second  square bracket will gives the maximum length of string.



Example
Write a program to initializes 3 names in an array of strings and display them onto monitor.

#include<stdio.h>

main()
{
int n ;
char names[3][10]={"Alex","Phillip","Collins"};
for(n=0;n<3;n++)
printf("%s\n",names[n]);

}

OUTPUT


Alex
Phillip
Collins

Declaration and Initialisation of Strings

Strings in C are group of characters ,digits and symbols enclosed in quotation marks .The end of the string is marked with a special character,the'\0'(null),which has the decimal value 0.There is a difference between a character stored in memory and a single character string stored in a memory.The character requires only one byte whereas the single character string requires two bytes (one byte for the character aand other byte for the delimiter).

Declaration of Strings

To declare a string,specify the data type as char and place the  number of characters in an array in square brackets after the string name.Syntax is as follows:

Char string-name[size];
for example -
char city[24];
char studname[50];

Initialization of strings

String can be initialized as follows:

String can be initialized as follows:
char name[8]={'P','R','O','G','R','A','M','\0'};

Each character of strings occupies 1 byte of memory(on 16 bit computing) .The size of character is machine dependent,and varies from 16 bit computers to 64 bit computers .The character of strings are stored in the contiguous(adjacent) memory location.

1 Byte 1 Byte 1 Byte 1 Byte 1 Byte 1 Byte 1 Byte 1 Byte
P R O G R A M \0
2001 2002 2003 2004 2005 2006 2007 \2008

The C compiler inserts the null (\0) character automatically at the end of the string.So initialization of the Null character is not essential.

You can set the initial value of a character array when you declare it by specifying a string literal .If the array is too small for the literal ,the literal will be truncated .If the literal  is smaller than the array ,then the final characters in the array will be undefined .If you don't specify the size of  the array,but do specify a literal,then C will set the array to the size of the literal ,including the null terminator.

char str[4]={'u','n','i','x'};
char str[5]={'u','n','i','x','\0'};
char str[3];
char str[]="UNIX";
char str[4]="unix";
char str[9]="unix";

All of the above declarations are legal.The first is valid declaration but it will cause major major problem because null is not-terminated.The fifth example suffers the size problem and fourth example is legal because the compiler will determine the length of string automatically and initialize the  last character to null-terminator .

String Constants

String constants have double quote marks around him them,and can be assigned to char pointers.Alternatively,you can assign a string constant to char array -either with no size specified ,or you can specify a size ,but don't forget to leave a for the null character !Suppose you create the following two code fragments and  run them:
/*fragment 1*/
 {
char *s;
s="hello" ;
printf("%s\n",s);
 }

/*fragment 2*/
{
 char s[100];
strcpy(s,"hello");
printf("%s\n",s);
}

These two fragments produce the same output ,but their internal behavior is different.In fragment 2 you can say s="hello"; . To understand the differences,you have to understand how the string constant table work in C.When your program is compiled ,the compiler forms the object code file ,which contain your machine code and a table of ll the string constant declared in a program.In fragment 1 ,the statement s="hello"; causes s to  point to the address of the string hello in the string constant table .Since this string is in the string constant table ,and therefore technically a part of executable code,you cannot modify it .You can only point to it and use it in a read-only manner.In fragment 2,the string hello also exists in the constant table ,so you can copy it into the array of characters  named s .Since s is not an address,the statement s="hello"; will not work n fragment 2.It will not compile.


EXAMPLE

Write  a program to read a name from the keyboard and display message Hello onto the monitor.


#include<stdio.h>
main()
{
char name[10];
printf("\n Enter your name:");
Scanf("%s",name);
printf("Hello %s\n",name);
}

OUTPUT
Enter your name : Pankaj
Hello Pankaj

MULTI-DIMENSIONAL ARRAYS

Multi dimensional array is an array in which more than one row and one column is present.Chess board is an example to two dimensional array.Two dimensional array use to indices to pinpoint an individual element of the array.This is very similar to what is called "algebraic notation ",commonly used in chess circles to record games and chess problems. '

Multi-Dimension Array Declaration

The syntax is as follows:

datatype array_name[Size1][SIZE2];

in the above statement,datatype is the name of some type of data,such as int,char.Size1 and Size2 are the size of an array's first(row) and second(column) dimension,respectively.8-by-8 array of integers is similar to a chessboard.Remember,because C arrays are zero-based,the indices on each side of the chessboard array run 0 through 7,rather than 1 to 8.

int chessboard[8][8];

Initialization of Two-dimensional arrays

If you have an m x n array then it will have  m*n  elements and will require m*n*elements size bytes of storage.To allocate storage for an array you must reserve this amount of memory.The element of two-dimensional array are stored row wise .
int tab[3][3]={1,2,3,4,5,6,7,8,9};
It means that elements
table[0][0] =1;
table[0][1] =2;
table[0][2] =3;
table[1][0] =4;
table[1][2] =5;
table[1][3] =6;
table[2][0] =7;
table[2][1] =8;
table[2][2] =9;

ARRAY INITIALIZATION

Array can be initialized at the time of declaration.The initial values must appear in the order in which they will be assigned to the individual array elements,enclosed within the braces and separated by commas.

Syntax of array initialization :

data type array-name[size]={value 1,value 2......value n};

Value 1 is the  value for the  first array element,value 2 is the value for second element,value n is the value for n array element.When you are initializing the values at the time of declaration,then there is no need to specify size.

int[10]={1,2,3,4,5,6,7,8,910};

int[]={1,2,3,4,5,6,7,8,9,10};


Character Array Initialization

The array of characters is implemented as in C.Strings are handled differently as far as initialization is concerned.A special character called null character '\0', implicitly suffixes every string.When the external or static string character array is assigned a string constant,the size specification is usually omitted and is automatically assigned;it will include the '\0' character ,added at the end.For example,consider the following two assignment statements:

char thing[3]="TIN";
char thing[]="TIN";

In the above statements the assignments are done differently .The first statement is not a string but simply an array storing three characters 'T','I','N' and is same as writing:

char thing[4]={'T','I','N'};
whereas ,the second one is four character string TIN\0.The change in the first assignment,as given below,can make it a string.

Example

Write a program to illustrate how the marks of 10 students are read in an array and then used to find the maximum marks obtained by a student in the class.

#include<stdio.h>
#define SIZE 10 

main()
{
int i=0;
int max=0;
int stud_marks[SIZE];
for(i=0;i<SIZE;i++)
 {
printf("Student no.=%d",i++);
printf("Enter the marks out of 50: ");
scanf("%d",&stud_marks[i]);
}
for(i=0;i<SIZE;i++)
{
 if(stud_marks[i]>max)
max=stud_marks[i];
}

printf("\n\n The maximum of the marks obtained among all the 10 students: %d",max);
} 
OUTPUT
Student no.=1 Enter the marks out of 50:10
Student no.=2 Enter the marks out of 50:17
Student no.=3 Enter the marks out of 50:23
Student no.=4 Enter the marks out of 50:40
Student no.=5 Enter the marks out of 50:49
Student no.=6 Enter the marks out of 50:34
Student no.=7 Enter the marks out of 50:37
Student no.=8 Enter the marks out of 50:16
Student no.=9 Enter the marks out of 50:08
Student no.=10 Enter the marks out of 50:37

Array

  • Array is a data structure storing a group of elements , all of which are of same data type.
  • All the elements of an array share the same name,and they are distinguished from one another with the help of an index.
  • Random access to every element using a numeric index.
  • A simple data structure,used for decades,which is extremely  useful.
  • Abstract Data type list is frequently associated with the array data structure.




The declaration of an array is just like any variable declaration with additional size or dimension.In the following section we will see how an array is declared.

Syntax of declaration is as follows :

data-type array_name[constant-size];
 
          Data-type refers to the type of elements you want to store
          Constant-size is the number of elements

The following are  some declaration for arrays:
int char[80];
float farr[500];
static int iarr[80];
char charray[40];


There are two restrictions for using arrays in C :

  • The amount of storage for a declared array had to be specified at compile time before execution.This means that an array has a fixed size.
  • The data  type of an array  applies uniformly to all the elements ;for this reason,an array is called a homogeneous data structure.
Size Specification

The size of an array should be declared using symbolic constant rather a fixed integer quantity .The use of a symbolic constant makes it easier to modify a program that uses an array .All reference to maximize the array size can be altered simply by changing the  value of the symbolic constant. 

Example

Write a program to declare and read values in an array and display them.

#include<stdio.h>
#define SIZE 5

main()
{
int i=0;

int stud_marks[SIZE];
for(i=0;i<SIZE;i++)
{
printf("Element no.=%d",i+1);
printf("Enter the value of element");
scanf("%d",&stud_marks[i]);
 }
printf("\n Following are the values stored in the corresponding array elements:\n\n ")
 for(i=0;i<SIZE;i++)
{
printf("value stored in a [%d] is %d\n"i,stud_marks[i]);
}
}

OUTPUT
 Element no.=1 Enter the Value of the element=11
 Element no.=2 Enter the Value of the element=12
 Element no.=3 Enter the Value of the element=13
 Element no.=4 Enter the Value of the element=14
 Element no.=5 Enter the Value of the element=15

Values stored in a corresponding array elements:

Value stored in a[0] is 11
Value stored in a[1] is 12
Value stored in a[2] is 13
Value stored in a[3] is 14
Value stored in a[4] is 15

The Continue statement

Unlike break statement,which is used to jump the control out of the loop,it is sometimes required to skip some part of the loop and to continue the execution
with next loop iteration.Continue statement used inside the loop helps to bypass the section of a loop and passes the control to the beginning of the loop to continue the execution with the next loop iteration.The syntax is follows :

continue;  





Example

Write a program to print the first 20 natural numbers skipping the  number  divisible by 5.

#include<stdio.h>

main()
{
int i;
for(i=1;i<=20;i++)
{
if((i%5)==0)
 continue;
 printf("%d",i);
}
}

OUTPUT
 1 2 3 4 6 7 8 9 11 12 13 14 16 17 18 19

The break statement

Sometimes,it is required to jump a loop irrespective of the conditional test value.Break statement is used inside any loop to allow the control jump to the immediate statement following the loop.The syntax is as follows:

break;

When nested loops are used,then the break jumps the control from the loop where it has been used.Break  statement can be used inside any loop.
   Example 

Write a program to calculate the first smallest divisor o a number.

#include<stdio.h>

main()
{
int div,num,i;
printf("Enter any number: \n");
scanf("%d",&num);
for(i=0;i<=num;i++)
{
if((num%i)==0)
{
 printf("Smallest divisor for number %d"",num,i);
break;
}
}
}

OUTPUT
Enter any number:
9
Smallest divisor of 9 is 3

THE goto STATEMENT

The goto statement is used to alter the normal sequence of program instructions by transferring the control to some other portion of the program .The syntax is as follows:

goto label;

Here,label is an identifier that is used to label the statement to which control will be transferred.The targeted statement  must be preceded by the unique label followed by colon.

label : statement ;

Although goto statement is used to alter the normal sequence of program  execution but its usage in the program should be avoided.The most common application are:

1)To branch  around statements under certain conditions in place of use of if-else statement .

2)To jump to the end of the loop under certain  conditions by passing the rest of the statements inside the loop in place of continue statement.

3)To jump out of the loop avoiding the use of break statement.

goto can never be used to jump into the loop from outside and it should be preferably used for forward jump.

Situations may arise,however,in which the goto statement can be useful.To the possible extent,the use of the goto statement should generally be avoided.




EXAMPLE

Write a program to print first 10 even numbers.

#include<stdio.h>
main(){
int i=2;
while(i)
 {
printf("%d",i);
i=i+2;
if(i>=20)
goto outside;
}
outside:printf("over")
}

OUTPUT
2 4 6 8 10 12 14 16 18 20 over

Loop Control Statements

Loop Control Statements are used when a section of code may either be executed a fixed number of times,or while  same condition is true.C gives you a choice of three types of loop statements,while,do-while and for.

1) The while loop keeps repeating an action until an associated condition returns false.This is useful where are programmer does not know in  advance how many times the loop will be traversed.

2)The do while loop is similar,but the condition is checked after the loop body is executed.This ensures that the loop body is run at least once.

3)The for loop is frequently used,usually where the loop will be traversed a fixed number of times.


The While Loop 

When in a program a single statement or certain group of statements are to be executed repeatedly depending  upon certain test condition,the while statement is used.

The syntax is as follows:

while (test condition)
{
body_of_the_loop;
}

Here,test condition is an expression that controls how long the loop keeps running.Body of the loop is a statement  or group of statements enclosed in braces and are repeatedly executed till the value of test condition evaluates to true.As soon as the condition evaluates to false,the control jumps to the first statement following the while statement.If condition initially itself is false,the body of the loop will never be executed.While loop is sometimes called as entry-control loop,as it controls the execution of the body of the loop depending upon the value of test condition.


Example 

Write a program to calculate the factorial of a given input natural number.

#include<stdio.h>
#include<math.h>

main()
{
int x;
long int fact=1;
printf("Enter any number to find factorial:\n");
scanf("%d",&x);
while(x>0)
{
fact=fact*x;
x=x-1;
}
 printf("Factorial is %d",fact);
}

OUTPUT

Enter any number to find factorial;
4
Factorial is 24

The do...while Loop 

There is another loop control structure which is very similar to the while statement called as the do....while statement.The only difference is that the expression which determines whether to carry on looping is evaluated at the end of  each loop.The syntax is as follows:

do{
statements(s);
}while(test condition);

In do-while loop,the body of loop is executed at least once before the condition is evaluated.Then the loop repeats body as long as condition is true.However,in while loop,the statement doesn't execute the body of the loop even once,if condition is false.That is why do-while loop is also called exit-control loop.


Example 

Write a program to print first ten  even natural numbers.

#include<stdio.h>
main()
{
int i=0;
int j=2;
do{
print("%d",j);
j=j+2;
i=i+1;
}
while(i<0);
}

OUTPUT
2 4 6 8 10 12 14 16 18 20


The for Loop

for statement makes it more convenient to count iterations of a loop and works well where the number of iterations of the loop is known before the loop is entered .The syntax is as follows:

for(initialization;test condition;increment or decrement)
{

statement(s);
}
The main purpose is to repeat statement while condition remains true,like the while loop.But in addition,for provides places to specify an initialization instruction and an increment or decrement of the control variable instruction.So this loop is specially designed to perform a repetitive action with a counter .



Example 

Write a program to print first n natural numbers.


#include<stdio.h>
main()
{
int i,n;
printf("Enter the value of n \n");
scanf("%d",&n);
printf("\n The first %d natural numbers are : \n",n);
for(i=1;i<=n;i++)
{
printf("%d",i);
}
}


OUTPUT

Enter value of n
6
The first 6 natural numbers are :
1 2 3 4 5 6