Types of Functions in C programming

                            There are mainly five types of functions in C language. Generally when talk about programming type refers to the data type but here we are not talking about that. The classification mainly based on number of arguments we pass and and the return values. Now take a look at them.



1)Functions with no arguments and no return value:

                           A C function without any arguments means you cannot pass data  to the called function. Similarly, function with no return type will not pass back data to the calling function. This type of function which does not return any value cannot be used in an expression it can be used only as independent statement.



Example:

#include<stdio.h>

#include<conio.h>

void printline()

{

int i;

printf("\n");

for(i=0;i<10;i++)

{

printf("-");

}

printf("\n");

}

void main()

{

clrscr();

printf("Welcome to function in C");

printline();

printf("Function easy to learn.");

printline();

getch();

}



code explanation:

Line 3: This C code block is a user defined function (UDF) whose task is to print a horizontal line.

Line 7: I have declared a “for loop” which loops 30 time and prints “-” symbol continuously.

Line 13: These line are “main()”  function code block.

Line no. 16 and 18 simply prints two different messages.

Line no. 17 and 18 calls our user defined function “printline()”. You can see output this program below



2) Functions with arguments and no return value:

                              A C function with arguments can perform much better than previous function type. This type of function can accept data from calling function. In other words, you send data to the called function from calling function but you cannot send result data back to the calling function. Rather, it displays the result on the terminal. But we can control the output of function by providing various values as arguments.



example:

#include<stdio.h>

#include<conio.h>

void add(int x, int y)

{

int result;

result = x+y;

printf("Sum of %d and %d is %d.\n\n",x,y,result);

}

void main()

{

clrscr();

add(30,15);

add(63,49);

add(952,321);

getch();

}



Code Explanation:

Line 3-8: This C code block is “add()” which accepts two integer type arguments. This UDF also has a integer variable “result” which stores the sum of values passed by calling function (in this example “main()”). Line no. 7 simply prints the result along with argument variable values.

Line 9-16: This code block is a “main()” function but only line no. 12, 13, 14 is important for us now. In these three lines we have called same function “add()” three times but with different values and each function call gives different output. So, you can see, we can control function’s output by providing different integer parameters which was not possible in function type 1. This is the difference between “function with no argument” and “function with argument”.



3) Functions with arguments and return value:

This type of function can send arguments (data) from the calling function to the called function and wait for the result to be returned back from the called function back to the calling function. And this type of function is mostly used in programming world because it can do two way communications; it can accept data as arguments as well as can send back data as return value.



Example:

#include<stdio.h>

#include<conio.h>

int add(int x, int y)

{

int result;

result = x+y;

return(result);

}

void main()

{

int z;

clrscr();

z = add(952,321);

printf("Result %d.\n\n",add(30,55));

printf("Result %d.\n\n",z);

getch();

}



Code Explanation:

Line No. 3-8: Look line no. 3 carefully, it starts with int. This int is the return type of the function, means it can only return integer type data to the calling function. If you want any function to return character values then you must change this to char type.

On line no. 7 you can see return statement, return is a keyword and in bracket we can give values which we want to return. You can assign any integer value to experiment with this return which ultimately will change its output. .

Line No. 9-17: In this code block only line no. 13, 14 and 15 is important. We have declared an integer “z” which we used in line no. 13. Why we are using integer variable “z” here? You know that our UDF “add()” returns an integer value on calling. To store that value we have declared an integer value. We have passed 952, 321 to the “add()” function, which finally return 1273 as result. This value will be stored in “z” integer variable. Now we can use “z” to print its value or to other function.



4) Functions with no arguments but returns value:

                                    We may need a function which does not take any argument but only returns values to the calling function then this type of function is useful. The best example of this type of function is “getchar()” library function which is declared in the header file “stdio.h”. We can declare a similar library function of own.



Example:

#include<stdio.h>

#include<conio.h>

int send()

{

int s;

printf("Enter a number : ");

scanf("%d",&s);

return(s);

}

void main()

{

int z;

clrscr();

z = send();

printf("\nYou entered : %d.", z);

getch();

}



Code Explanation:

In above code we just calling the function send at main function. Which will read value for "s" and return it to the function call. simple!



5) Functions that return multiple values.

                        Tell now we have learned and seen that in a function, return statement was able to return only single value. That is because; a return statement can return only one value. But if we want to send back more than one value then how we could do this?

                      We have used arguments to send values to the called function, in the same way we can also use arguments to send back information to the calling function. The arguments that are used to send back data are called Output Parameters. For this we use pointer variables to send back the information.

                       We use "*" to declare a pointer variable. The “*” is known as indirection operator whereas “&” known as address operator. We can get memory address of any variable by simply placing “&” before variable name. In the same way we get value stored at specific memory location by using “*” just before memory address. These things are a bit confusing but when you will understand pointer then these thing will become clearer.



Example:

#include<stdio.h>

#include<conio.h>

void calc(int x, int y, int *add, int *sub)

{

*add = x+y;

*sub = x-y;

}

void main()

{

int a=20, b=11, p,q;

clrscr();

calc(a,b,&p,&q);

printf("Sum =  %d, Sub = %d",p,q);

getch();

}



Code Explanation:

                     In this program  we call “calc()” and sends argument then it adds and subtract that two values and store that values in their respective pointers.

Line 3-7: . In line no. 3 looks something strange, let’s have a clear idea of it. “Calc()” function has four arguments, first two arguments need no explanation. Last two arguments are integer pointer which works as output parameters (arguments). Pointer can only store address of the value rather than value but when we add * to pointer variable then we can store value at that address.

Line no. 8-15: When we call “calc()” function in the line no. 12 then following assignments occurs. Value of variable “a” is assigned to “x”, value of variable “b” is assigned to “y”, address of “p” and “q” to “add” and “sub” respectively. In line no. 5 and 6 we are adding and subtracting values and storing the result at their respective memory location. This is how the program works.

Heap sort in C

c-techaravind
                                              To compile and execute the program, copy the code into a text file. Save the text file with the extinction .c (ex. program.c). Save your file in turboc2 or borland (it may your othe c-compiler). Now open you IDE (tc.exe) , goto file->pick file. Your source file will be loaded into IDE. Now you can compile and run the file easily.


#include <stdlib.h>
#include <stdio.h>


#define uint unsigned int

typedef int (*compare_func)(int, int);


void heap_sort(int This[], compare_func func_pointer, uint len)
{
/* heap sort */

uint half;
uint parents;

if (len <= 1)
return;

half = len >> 1;
for (parents = half; parents >= 1; --parents)
{
int tmp;
int level = 0;
uint child;

child = parents;
/* bottom-up downheap */

/* leaf-search for largest child path */
while (child <= half)
{
++level;
child += child;
if ((child < len) &&
((*func_pointer)(This[child], This[child - 1]) > 0))
++child;
}
/* bottom-up-search for rotation point */
tmp = This[parents - 1];
for (;;)
{
if (parents == child)
break;
if ((*func_pointer)(tmp, This[child - 1]) <= 0)
break;
child >>= 1;
--level;
}
/* rotate nodes from parents to rotation point */
for (;level > 0; --level)
{
This[(child >> level) - 1] =
This[(child >> (level - 1)) - 1];
}
This[child - 1] = tmp;
}

--len;
do
{
int tmp;
int level = 0;
uint child;

/* move max element to back of array */
tmp = This[len];
This[len] = This[0];
This[0] = tmp;

child = parents = 1;
half = len >> 1;

/* bottom-up downheap */

/* leaf-search for largest child path */
while (child <= half)
{
++level;
child += child;
if ((child < len) &&
((*func_pointer)(This[child], This[child - 1]) > 0))
++child;
}
/* bottom-up-search for rotation point */
for (;;)
{
if (parents == child)
break;
if ((*func_pointer)(tmp, This[child - 1]) <= 0)
break;
child >>= 1;
--level;
}
/* rotate nodes from parents to rotation point */
for (;level > 0; --level)
{
This[(child >> level) - 1] =
This[(child >> (level - 1)) - 1];
}
This[child - 1] = tmp;
} while (--len >= 1);
}


#define ARRAY_SIZE 250000

int my_array[ARRAY_SIZE];

void init()
{
int indx;

for (indx=0; indx < ARRAY_SIZE; ++indx)
{
my_array[indx] = rand();
}
}

int cmpfun(int a, int b)
{
if (a > b)
return 1;
else if (a < b)
return -1;
else
return 0;
}

int main()
{
int indx;

init();

heap_sort(my_array, cmpfun, ARRAY_SIZE);

for (indx=1; indx < ARRAY_SIZE; ++indx)
{
if (my_array[indx - 1] > my_array[indx])
{
printf("bad sort\n");
return(1);
}
}

return(0);
}


Factorial By Recursion in C

c-techaravind
                                              To compile and execute the program, copy the code into a text file. Save the text file with the extinction .c (ex. program.c). Save your file in turboc2 or borland (it may your othe c-compiler). Now open you IDE (tc.exe) , goto file->pick file. Your source file will be loaded into IDE. Now you can compile and run the file easily.




# include<stdio.h>

int factorial(unsigned int number)
{
if(number <= 1)
return 1;
return number * factorial(number - 1);
}
void main()
{
int x = 5;
printf("factorial of %d is %d",x,factorial(x));
}


Combinational Circuits(Half adder, Full adder)

           A combinational circuit is a connected arrangement of logic gates with a set of inputs and outputs. At any given time the binary values of outputs are a function of the binary combination of the inputs.

          Now below i will discuss two basic arthamatic circuits. I take these as my example of basic circuits. Before going to in this you need to have  some basic idea about logical gates go to  basic logical gates my previous post.



Half Adder:

            The most basic digital arithmetic circuits is the addition of two binary digits. A combinational circuit that performs the arithmetic addition of tow bits is called a half adder. the input variables of a half adder anre called the augend and addend bits. The output  variables the sum and carry.It is necessary to specify two out put variables because the of 1+1 is binary 10, which has tow digits. We assign symbols x and y to the tow input  variables. The C output is 0 unless both imputs are 1. The S output represents the least significant bitof the sum.



                                                               S=x`y+xy`

                                                               C=xy



Truth table

x       y      C       S

0      0       0       0

0      1       0       1

1      0       0       1

1      1       1       0





Full Adder:

                  A Full-adder is a combinational circuit that forms the arithmetic sum of three input bits. It consists of three inputs and two outputs. Two of the input variables, denoted by A and B, represent the two significant bits to be added. The thired input Cin represents the carry from the previous lower significatn position. Two outputs are necessary because the arithmetic sum o three dinary digits ranges in value from 0 to3, and binary 2 or 3 needs two digits. The two outputs are designated by the symbols S(for sum) and Cout (for carrry). The boolean expression of  Full adder is as follows.



                  
















truth tableInputs




Outputs
ABCinCoutS
00000
10001
01001
11010
00101
10110
01110
11111












 
Etutos © 2010-2011