Showing posts sorted by relevance for query C function. Sort by date Show all posts

Function

Function

#A function is a group of statements that together perform a specific task. Every C program has at least one function, which is main().

Why use function ?

Function are used for divide a large code into module, due to this we can easily debug and maintain the code. For example if we write a calculator programs at that time we can write every logic in a separate function (For addition sum(), for subtraction sub()). Any function can be called many times.

Advantage of Function

  • Code Re-usability
  • Develop an application in module format.
  • Easily to debug the program.
  • Code optimization: No need to write lot of code.

Type of Function

There are two type of function in C Language. They are;
  • Library function or pre-define function.
  • User defined function.

Library function

Library functions are those which are predefined in C compiler. The implementation part of pre-defined functions is available in library files that are .lib/.obj files. .lib or .obj files are contained pre-compiled code. printf(), scanf(), clrscr(), pow() etc. are pre-defined functions.

Limitations of Library function

  • All predefined function are contained limited task only that is for what purpose function is designed for same purpose it should be used.
  • As a programmer we do not having any controls on predefined function implementation part is there in machine readable format.
  • In implementation whenever a predefined function is not supporting user requirement then go for user defined function.

User defined function

These functions are created by programmer according to their requirement for example suppose you want to create a function for add two number then you create a function with name sum() this type of function is called user defined function.

Defining a function.

Defining of function is nothing but give body of function that means write logic inside function body.

Syntax

 
return_type  function_name(parameter)
{
function body;
}
  • Return type: A function may return a value. The return_type is the data type of the value the function returns.Return type parameters and returns statement are optional.
  • Function name: Function name is the name of function it is decided by programmer or you.
  • Parameters: This is a value which is pass in function at the time of calling of function A parameter is like a placeholder. It is optional.
  • Function body: Function body is the collection of statements.

Function Declarations

A function declaration is the process of tells the compiler about a function name. The actual body of the function can be defined separately.

Syntax

return_type  function_name(parameter);
Note: At the time of function declaration function must be terminated with ;.

calling a function.

When we call any function control goes to function body and execute entire code. For call any function just write name of function and if any parameter is required then pass parameter.

Syntax

function_name(); 
    or  
variable=function_name(argument);  
Note: At the time of function calling function must be terminated with ';'.

Example of Function

 
#include<stdio.h>
#include<conio.h>

void sum(); // declaring a function
clrsct();
int a=10,b=20, c;

void sum()  // defining function
{
c=a+b;
printf("Sum: %d", c);
}
void main()
{
sum();  // calling function
}

Output

 
Sum: 30

Command LIne Arguments

Command Line Argument

#If any input value is passed through command prompt at the time of running of program is known as command line argument. It is a concept to passing the arguments to the main() function by using command prompt.

When Use Command Line Argument

When you need to developing an application for DOS operating system then in that case command line arguments are used. DOS operating system is a command interface operating system so by using command we execute the program. With the help of command line arguments we can create our own commands.
In Command line arguments application main() function will takes two arguments that is;
  • argc
  • argv
argc: argc is an integer type variable and it holds total number of arguments which is passed into main function. It take Number of arguments in the command line including program name.
argv[]: argv[] is a char* type variable, which holds actual arguments which is passed to main function.

Compile and run CMD programs

Command line arguments are not compile and run like normal C programs, these programs are compile and run on command prompt. To Compile and Link Command Line Program we need TCC Command.
  • First open command prompt
  • Follow you directory where your code saved.
  • For compile -> C:/TC/BIN>TCC mycmd.c
  • For run -> C:/TC/BIN>mycmd 10 20
  • Explanation: Here mycmd is your program file name and TCC is a Command. In "mycmd 10 20" statement we pass two arguments.

Example of Command line argument

#include<stdio.h>
#include<conio.h>

void main(int argc, char* argv[])
{
int i;
clrscr();
printf("Total number of arguments: %d",argc);
for(i=0;i< argc;i++)
{
printf("\n %d argument: %s",i,argv[i]);
getch();
}
}

Output

C:/TC/BIN>TCC mycmd.c
C:/TC/BIN>mycmd 10 20
Number of Arguments: 3
0 arguments c:/tc/bin/mycmd.exe
1 arguments: 10
2 arguments: 20
Note: In above output we passed two arguments but is show "Number of Arguments: 3" because argc take Number of arguments in the command line including program name. So here two arguments and one program name (mycmd.exe) total 3 arguments.

Example of Command line argument

#include<stdio.h>
#include<conio.h>

void main(int argc, char* argv[])
{
clrscr();
  printf("\n Program name  : %s \n", argv[0]);
  printf("1st arg  : %s \n", argv[1]);
  printf("2nd arg  : %s \n", argv[2]);
  printf("3rd arg  : %s \n", argv[3]);
  printf("4th arg  : %s \n", argv[4]);
  printf("5th arg  : %s \n", argv[5]);
getch();
}

Output

C:/TC/BIN>TCC mycmd.c
C:/TC/BIN>mycmd this is a program
Program name : c:/tc/bin/mycmd.c
1st arg : this
2nd arg : is
3rd arg : a
4th arg : program
5th arg : (null)
Explanation: In the above example.

Example

argc      =   5
argv[0]   =   "mycmd"
argv[1]   =   "this"
argv[2]   =   "is"
argv[3]   =   "a"
argv[4]   =   "program"
argv[5]   =   NULL

Why command line arguments program not directly run form TC IDE

Command line arguments related programs are not execute directly from TC IDE because arguments can not be passed.

Edit Command Line Argument Program

To Edit the Command Line Argument Program use edit Command.

Syntax

C:/cprogram>edit mycmd.c
  • Whenever the program is compiled and link we will get .exe file and that .exe file itself is command.
  • In above example program name is mycmd.c so executable file is mycmd.exe and command name is mycmd.
  • To load the application in to the memory we required to use program name and command name.

Access data from outside of main

  • argc and agrv are local variables to main function because those are the main function parameters.
  • According to the storage classes of C argc and argv are auto variable to main function, so we can not extend the range of auto variable.
  • By using argc and argv we can not access command from data outside of the main function.
  • In implementation when we required to access command from data outside of the main function then use _argc, _argv variables.
  • _argc and _argv are global variable which is declared in dos.h.

Example

#include<stdio.h>
#include<conio.h>
#include<dos.h>

void abc()
{
int i;
printf("data in abc:");
printf("\n Total no. of arguments: %d",_argc);
for (i=0;i< _argc;i++)
{
printf("\n %d argument: %s",i+1,_argv[i]);
}
}
void main(int argc, char*argv[])
{
int i;
clrscr();
printf("\n data in main:");
printf("\n total no. of arguments: %d",argc);
for(i=0;i< argc;i++)
{
printf("\n %d arguments:%s",i+1,argv[i]);
}
abc();
getch();
}

Function Arguments

Call by Value and Call by Reference in C

On the basis of arguments there are two types of function are available in C language, they are;

  • With argument
  • Without argument
If a function take any arguments, it must declare variables that accept the values as a arguments. These variables are called the formal parameters of the function. There are two ways to pass value or data to function in C language which is given below;
  • call by value
  • call by reference

                                             Call by value

In call by value, original value can not be changed or modified. In call by value, when you passed value to the function it is locally stored by the function parameter in stack memory location. If you change the value of function parameter, it is changed for the current function only but it not change the value of variable inside the caller method such as main().

Call by value

 
#include<stdio.h>
#include<conio.h>

void swap(int a, int b)
{
 int temp;
 temp=a;
 a=b;
 b=temp;
}

void main() 
{  
 int a=100, b=200;  
 clrscr();  
 swap(a, b);  // passing value to function
 printf("\nValue of a: %d",a);
 printf("\nValue of b: %d",b);
 getch();  
}  

Output

 
Value of a: 200
Value of b: 100

                                           Call by reference

In call by reference, original value is changed or modified because we pass reference (address). Here, address of the value is passed in the function, so actual and formal arguments shares the same address space. Hence, any value changed inside the function, is reflected inside as well as outside the function.

Example Call by reference

 
#include<stdio.h>
#include<conio.h>

void swap(int *a, int *b)
{
 int temp;
 temp=*a;
 *a=*b;
 *b=temp;
}

void main() 
{  
 int a=100, b=200;  
 clrscr();  
 swap(&a, &b);  // passing value to function
 printf("\nValue of a: %d",a);
 printf("\nValue of b: %d",b);
 getch();  
}  

Output

 
Value of a: 200
Value of b: 100

Difference between call by value and call by reference.

call by valuecall by reference
This method copy original value into function as a arguments.This method copy address of arguments into function as a arguments.
Changes made to the parameter inside the function have no effect on the argument.Changes made to the parameter affect the argument. Because address is used to access the actual argument.
Actual and formal arguments will be created in different memory locationActual and formal arguments will be created in same memory location
Note: By default, C uses call by value to pass arguments.

Important points related to Function

  • The basic purpose of the function is code reuse.
  • From any function we can invoke (call) any another functions.
  • Always compilation will be take place from top to bottom.
  • Always execution process will starts from main() and ends with main() only.
  • In implementation when we are calling a function which is define later for avoiding the compilation error we need to for forward declaration that is prototype is required.
  • In function definition first line is called function declaration or function header.
  • Always function declaration should be match with function declaratory.
  • In implementation whenever a function does not returns any values back to the calling place then specify the return type.
  • Void means nothing that is no return value.
  • In implementation whenever a function returns other than void then specify the return type as return value type that is on e type of return value it is returning same type of return statement should be mentioned.
  • Default return type of any function is an int.
  • Default parameter type of any function is void.

Structure of basic C program

Structure of C Program

#Every C program can be written with the following syntax.

Syntax

#include<headerfilename.h>  --> include section
Returntype function_name(list of parameters or no parameter)  --> user defined function
{
Set of statements
.........
}
Returntype main()  --> main block or main function
{
.........
.........
}

Include section

# include is a pre-processor directive can be used to include all the predefined functions of given header files into current C program before compilation.

Syntax

#include<headerfile.h>
C library is collection of header files, header files is a container which is collection of related predefined functions.

User defined function section

If any function is defined by the user is known as user defined function. Function is collection of statement used to perform a specific Operation.

Syntax

Return_type function_Name()
{
....... // called function
.......
}
In the above syntax function name can be any user defined name, return type represents which type of value it can return to its calling function.

Syntax

functionName(); // calling function
Note: User defined function are Optional in a C program.

Main function

This is starting executable block of any program (it is always executed by processor and OS ). One C program can have maximum one main() the entire statements of given program can be executed through main(). Without main() function no C program will be executed.

Syntax

Returntype main()
{
......
.....
}
If return type is void that function can not return any value to the operating system. So that void can be treated as no return type.

Example

#include<stdio.h>
#include<conio.h>

void main()
{
printf("Hello main");
}

Output

Hello main

IO statements in C language

IO represents input output statements and input statement can be used to read the input value from the standard input device (keyboard), output statement can be used to display the output in standard output device (Monitor) respectively. In C language IO statement can be achieve by using scanf() and printf().

Main() function in C

main() function in C

#main() function is the entry point of any C program. It is the point at which execution of program is started. When a C program is executed, the execution control goes directly to the main() function. Every C program have a main() function.

Syntax

 void main()
 {
  .........
  .........
 }
In above syntax;
  • void: is a keyword in C language, void means nothing, whenever we use void as a function return type then that function nothing return. here main() function no return any value.
  • In place of void we can also use int return type of main() function, at that time main() return integer type value.
  • main: is a name of function which is predefined function in C library.

Simple example of main()

Example

#include<stdio.h>

void main()
{
printf("This is main function");
}

Output

This is main function