Function and Pointers
Function
A function is a self-contained block of statements that perform a coherent task of some kind. Every C program can be thought of as a collection of these functions. As we noted earlier, using a function is something like hiring a person to do a specific job for you. Sometimes the interaction with this person is very simple; sometimes it’s complex.
Function are also use to resolve the complexity of program. If you write the whole program inside the main() function then it will very difficult to find out some mistake. But if you are using two or more functions in the program for different tasks. And the reading or output of one task is coming wrong than you will check just that function, not the whole program.
=================================
main( )
{
message( ) ;
printf ( "\nCry, and you stop the monotony!" ) ;
}
message( )
{
printf ( "\nSmile, and the world smiles with you..." ) ;
}
=================================
Here, main( ) itself is a function and through it we are calling the functionmessage( ). What do we mean when we say that main( ) ‘calls’ the functionmessage( )? We mean that the control passes to the function message( ).The activity of main( ) is temporarily suspended; it falls asleep while themessage( ) function wakes up and goes to work. When the message( )function runs out of statements to execute, the control returns to main( ),which comes to life again and begins executing its code at the exact point where it left off. Thus, main( ) becomes the ‘calling’ function, whereasmessage( ) becomes the ‘called’ function.
Passing values between functions:
/* Sending and receiving values between functions */ #include<stdio.h> Int calsum ( x, y, z ); /*Prototype*/ main( ) { int a, b, c, sum ; printf ( "\nEnter any three numbers " ) ; scanf ( "%d %d %d", &a, &b, &c ) ; sum = calsum ( a, b, c ) ; printf ( "\nSum = %d", sum ) ; } Int calsum ( x, y, z ) { int d ; d = x + y + z ; return ( d ) ; } | In this programming we are declaring three integer values into the main function. And we have to add these three integers. We can perform this task by the main function but we will perform it by using a separate function to understand how a function executes. Function Call: Sum= calsum (a,b,c) this is function call that we have initialized all three integers with value and now we need start execution on these integers. This function call take us at the function where it has written. Int calsum (a,b,c); is our function that will perform the edition task. Inside this function we declare an integer (d), and d= a + b +c ; and then after there is return d ;command. That return the value of d to the main function where it called. And store the result in sum variable in main function . and thenprintf() command will print this result. |
Prototype:
If you are writing all the function before the main() program then there is no need to write prototype. But if you are writing the functions (those are called in main function) after the main() function then you must be declare function prototype. That which functions you will perform or call inside the main function.
In the second line of program int calsum ( x , y , z ) ; is prototype. In prototype there are three parts. One is data type. That is int in this function. This data type shows that what kind of data the function will return to the main function. Second is function name that is calsum here, you can write any name that show what you are going to do. It will be very easy to understand the program for others if you will write the name with similar to your execution. (x , y , z) are the variables on which the program will execute.
You also seen that in the main() function we declare three variables int a , b , c ; and also in the function call you write calcum(a , b , c ); but in the actual function is we write ( x , y , z) . the compiler will automatically match the variable in the same sequence that you write in the function call.
Recursion:
In C, it is possible for the functions to call themselves. A function is called ‘recursive’ if a statement within the body of a function calls the same function. Sometimes called ‘circular definition’, recursion is thus the process of defining something in terms of itself.
Let us now see a simple example of recursion. Suppose we want to calculate the factorial value of an integer. As we know, the factorial of a number is the product of all the integers between 1 and that number. For example, 4 factorial is 4 * 3 * 2 * 1. This can also be expressed as 4! = 4 * 3! where ‘!’ stands for factorial. Thus factorial of a number can be expressed in the form of itself.
==================================
main( )
{
int a, fact ;
printf ( "\nEnter any number " ) ;
scanf ( "%d", &a ) ;
fact = rec ( a ) ;
printf ( "Factorial value = %d", fact ) ;
}
rec ( int x )
{
int f ;
if ( x == 1 )
return ( 1 ) ;
else
f = x * rec ( x - 1 ) ;
return ( f ) ;
}
====================================
4. Write a C program that reads a line of text from keyboard and then prints the list of characters that occur in the input line right after a star character. This list must be printed without duplicates.
For example, if the entered line of text is:
T*e bal*n*e is n**ative
The program must write the characters:
en*a
Hint: consider that there are no more than 256 different characters in the character set.
#include <stdio.h>
#define MAXCHARS 256
main() {
char chars[MAXCHARS]; /* the characters to print */
int nchars; /* the number of characters to print */
char curr, prev; /* the last two characters read */
int i; /* array index */
nchars = 0;
printf("Enter a line of text\n");
scanf("%c",&curr); /* read first character */
while(curr!='\n') {
prev = curr; /* save previous character */
scanf("%c",&curr); /* and read new one */
if (prev=='*') { /* if previous character is star */
/* look for character curr in list of characters to print */
for(i=0; i<nchars && chars[i]!=curr; i++)
;
/* if not found add curr to list of characters to print */
if(i==nchars) {
chars[nchars]=curr;
nchars++;
}
}
}
printf("List of characters that follow a star:\n");
for (i=0; i<nchars; i++)
printf("%c",chars[i]);
printf("\n");
}
= = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = =
Write a C program that reads a sequence of integers terminated by a –1, checks that the number of
zeros in the sequence is even and no less than 2, and finally writes the same sequence but omitting all the
For example, if the input sequence is
12 3 0 4 2 0 7 0 0 6 0 23 5 0 8 -1
the program must write the following output sequence:
12 3 7 6 8 -1
Solving this problem requires storing the elements of the (output) sequence, so we have to fix a limit on
#include <stdio.h>
#include <math.h>
#define MAX 100
main()
{
int nzeros, i, n, x;
int sequence[MAX];
printf("Enter the sequence terminated by a -1:\n");
nzeros = 0;
scanf("%d",&x);
for (i=0; i<MAX && x!=-1; ) {
if (x==0)
nzeros++;
else if (nzeros%2==0) {
sequence[i]=x;
i++;
}
scanf("%d", &x);
}
if (i==MAX)
printf("Sequence is too long\n");
else {
sequence[i]=-1;
i++;
}
n = i;
if(nzeros<2 || (nzeros%2 != 0))
printf("Error: wrong number of zeros\n");
else {
for (i=0; i<n; i++)
printf("%d ", sequence[i]);
printf("\n");
}
}
= = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = =
Array:
An array is group of memory locations related by the fact that they are all having the same name and the same type. Like other languages, C uses arrays as a way of describing a collection of variables with identical properties. The group has a single name for all of the members, with the individual members being selected by an index. Here's an array being declared: array first element starts from 0 and goes up to one less of the size that you wrote inside the brackets of array name
Int ar [100];
The name of the array is ar and its members are accessed as ar[0] through to ar[99] inclusive, as Figure
for example if there are 100 students in the class and you have to find the average result of that class. First of all you will collect the marks of every student at one place and then you will add then and devise with total number of students in the class. Why you collect all the marks at one place because the marks of all student will be same type. And now if we have to make this program with c.
= = = = = = = = = = = = = = = = = = = = = = = = = = = = = =
#include<stdio.h>
main( )
{
int avg,
sum = 0 ;
int i ;
int marks[30] ; /* array declaration */
for ( i = 0 ; i <= 29 ; i++ )
{
printf ( "\nEnter marks " ) ;
scanf ( "%d", &marks[i] ) ; /* store data in array */
}
for ( i = 0 ; i <= 29 ; i++ )
sum = sum + marks[i] ; /* read data from an array*/
avg = sum / 30 ;
printf ( "\nAverage marks = %d", avg ) ;
}
= = = = = = = = = = = = = = = = = = = = = = = = = = = = = =
In this program we have to find the average of class of 30 students. So we have declared an array marks with 30 elements. Marks[0] for first student, marks[1] for second and so on . first we have to collect the marks of all students for that we will use scanf() command. One way is this that we write scanf() command at 30 times. Like scanf(“%d”,array[0])
And every time just change array number for example for second student
scanf(“%d”,array[1]) and so on. So you can write at 30 times. But if there is 10000 students then how you will write at 10000 times. To solve this problem we will use for loop. And inside the for loop we use the scanf() command just once and at the place of array[0] or array[1], we will write array[i] because in the for( ) loop we are using (i) as counter, which is counting from 0 to 29.
So in the scanf(“%d”,array[i]); the marks of each student will automatically save in different array element. And after collecting data. If we have to read the array to print the data or to perform some other task. We will run another loop and print each element. Or add each element like in his program we are doing.
Array types:
Int array[10] ;to store the integer values like: {0,1,2,3,4,5,6,7,8,9} float array [5]; to store the floating point integers: {0.0, 1.0, 2.1, 3.2, 4.3} char array[7]; to store the characters {a,b,c,d,e,f,g}
Character array also can store integer type data but integers type array cannot store any character type data.
Some Example C Programs:
#include <stdio.h>
#define SIZE 12
/* function main begins program execution */
int main()
{
/* if we have just some elements to store in array and we already know the values then we can write like this in this case each element will store at exact position for example this first element 1 will store at a[0] and so on. */
int a[ SIZE ] = { 1, 3, 5, 4, 7, 2, 99, 16, 45, 67, 89, 45 };
int i; /* counter */
int total = 0; /* sum of array */
/* sum contents of array a */
for ( i = 0; i < SIZE; i++ ) {
total += a[ i ];
} /* end for */
printf( "Total of array element values is %d\n", total );
return 0; /* indicates successful termination */
}
= = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = =
Write a C program that initially reads a positive integer N, and checks that N is indeed positive and less than 100. If the check fails the program must stop with an error message. Otherwise, the program must get on and read a sequence of N real numbers and then write the standard deviation of the sequence. If we denote the numbers in the sequence x0 x1 ... xN-1, the standard deviation of the sequence can be computed by the formula:
where x is the arithmetic mean of the N real numbers.
#include <stdio.h>
#include <math.h>
#define MAX 100
main()
{
int n, i;
float numbers[MAX], sum, mean, sqsum, sdev;
printf("Enter N:\n");
scanf("%d", &n);
if(n<0 || n>=MAX)
printf("Error: wrong value for N\n");
else {
printf("Enter sequence:\n");
sum=0;
for (i=0; i<n; i++) {
scanf("%f", &numbers[i]);
sum = sum + numbers[i];
}
mean = sum/n;
sqsum=0;
for (i=0; i<n; i++)
sqsum += (numbers[i]-mean)*(numbers[i]-mean);
sdev = sqrt(sqsum/n);
printf("Standard deviation of sequence is: %f\n", sdev);
}
}
= = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = =
Write a C program that reads from keyboard an integer number N, checks that N does not exceed 100, then reads a sequence of N integers from keyboard and finally prints out the same sequence but omitting duplicates. Program execution example:
Enter N: 10
Enter input sequence: 10 3 24 3 1 0 6 0 0 10
Output sequence: 10 3 24 1 0 6
Solution:
#include <stdio.h>
#define MAX 100
void main()
{
int n, i, j, x;
int numbers[MAX]; /* the set of the different integers entered so far */
int count; /* number of different integers entered so far */
printf("Enter n: ");
scanf("%d",&n);
if (n>100 || n<=0)
printf("Error: n must be a positive integer that does not exceed %d\n", MAX);
else {
/* start reading sequence: read first number, store it and output it */
printf("Enter input sequence: ");
scanf("%d",&x);
numbers[0] = x;
count = 1;
printf("Output sequence: %d ", x);
/* read the rest of the input sequence and output non-duplicated numbers */
for (i=0; i<n-1; i++) {
scanf("%d",&x); /* read x */
/* look for x in array of stored numbers */
for (j=0; j<count; j++)
if (numbers[j]==x)
break;
/* if x has not been found, store it in next array position and print it*/
if (j==count) {
numbers[count]=x;
count++;
printf("%d ", x);
}
}
printf("\n");
}
}
= = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = =
4) Write a C program that reads from keyboard a sequence of 20 integers and then writes separately the list of positive integers in the sequence and the list of negative integers in the sequence, in the same order as they occur in the input sequence.
Example:
Input:
10 –2 3 67 –12 8 –9 –2 3 8 12 6 15 –2 0 10 –11 –11 –10 1
Output:
Positive integers: 10 3 67 8 3 8 12 6 15 10 1
Negative integers: –2 –12 –9 –2 –2 –11 –11 –10
Solution:
#include <stdio.h>
#define N 20
void main()
{
int i, x;
int npos, nneg; /* number of positive and negative numbers in the list */
int pos[N], neg[N]; /* lists of positive and negative numbers */
npos = 0;
nneg = 0;
/* read integers and store positive and negative integers separately */
for (i=0; i<N; i++) {
scanf("%d",&x);
if (x>0) {
pos[npos]=x;
npos++;
}
else if (x<0) {
neg[nneg]=x;
nneg++;
}
}
/* write stored lists */
printf("Positive integers: ");
for (i=0; i<npos; i++)
printf("%d ", pos[i]);
printf("\n");
printf("Negative integers: ");
for (i=0; i<nneg; i++)
printf("%d ", neg[i]);
}
= = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = =
4. Write a C program that reads a line of text from keyboard and then prints the list of characters that occur in the input line right after a star character. This list must be printed without duplicates.
For example, if the entered line of text is:
T*e bal*n*e is n**ative
The program must write the characters:
en*a
Hint: consider that there are no more than 256 different characters in the character set.
#include <stdio.h>
#define MAXCHARS 256
main() {
char chars[MAXCHARS]; /* the characters to print */
int nchars; /* the number of characters to print */
char curr, prev; /* the last two characters read */
int i; /* array index */
nchars = 0;
printf("Enter a line of text\n");
scanf("%c",&curr); /* read first character */
while(curr!='\n') {
prev = curr; /* save previous character */
scanf("%c",&curr); /* and read new one */
if (prev=='*') { /* if previous character is star */
/* look for character curr in list of characters to print */
for(i=0; i<nchars && chars[i]!=curr; i++)
;
/* if not found add curr to list of characters to print */
if(i==nchars) {
chars[nchars]=curr;
nchars++;
}
}
}
printf("List of characters that follow a star:\n");
for (i=0; i<nchars; i++)
printf("%c",chars[i]);
printf("\n");
}
= = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = =
Write a C program that reads a sequence of integers terminated by a –1, checks that the number of
zeros in the sequence is even and no less than 2, and finally writes the same sequence but omitting all the
zeros and all the integers that are between the first and second zeros, between the third and fourth zeros
and so on. If the number of zeros in the sequence is not even or if it is less than 2 the program must
terminate immediately with an error message.
For example, if the input sequence is
12 3 0 4 2 0 7 0 0 6 0 23 5 0 8 -1
the program must write the following output sequence:
12 3 7 6 8 -1
Solving this problem requires storing the elements of the (output) sequence, so we have to fix a limit on
the maximum size of the sequence
#include <stdio.h>
#include <math.h>
#define MAX 100
main()
{
int nzeros, i, n, x;
int sequence[MAX];
printf("Enter the sequence terminated by a -1:\n");
nzeros = 0;
scanf("%d",&x);
for (i=0; i<MAX && x!=-1; ) {
if (x==0)
nzeros++;
else if (nzeros%2==0) {
sequence[i]=x;
i++;
}
scanf("%d", &x);
}
if (i==MAX)
printf("Sequence is too long\n");
else {
sequence[i]=-1;
i++;
}
n = i;
if(nzeros<2 || (nzeros%2 != 0))
printf("Error: wrong number of zeros\n");
else {
for (i=0; i<n; i++)
printf("%d ", sequence[i]);
printf("\n");
}
}
= = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = =
Passing Array to the function:
Before we have studied that how to pass an integr or some character to the the function. But now we have to pass an array to the function.
Prototype: the function header or prototype for the function modifyarray will be like.
void modifyarray ( int b[] , int size )
this prototype indicates that the modifyarray expects to receive an array of integer in parameter b and the number of array elements in parameter size. The size of the array is not required between the array brackets. If it is included between the brackets the compiler will check the that if it is zero the compiler will compile the program but if it is greater than zero then ignore it. If you specify the negative size of array then it will be compilation error because arrays are automatically passed by reference.
For example you have declared an array in the main function.
Int student [24] ;
No we have to perform some task on this array in the function modifyarray. So we wall call the function and pass the parameters of array to the function like this. Modifyarray ( student , 24)
Student is the array name the we declare in the main function and it will link with array b[] in the function . 24 is the total number of elements in the array and it will link with size integer in the function. Lets study an example of passing array to the function.
= = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = =
#include<stdio.h>
#define SIZE 5
void modifyarray(int b[],int size);
void modifyelement(int e);
int main (void)
{
int array[SIZE]={0,1,2,3,4,};
int i;
printf("value of original array\n");
for(i=0; i<SIZE; i++)
{
printf("%3d",array[i]);
}
printf("\n");
modifyarray(array,SIZE);
printf("the value of modify array");
for(i=0; i<SIZE; i++)
{
printf("%3d",array[i]);
}
printf("\n");
printf("the value of a[3] is %d\n",array[3]);
modifyelement(array[3]);
printf("the value of a[3] is %d\n",array[3]);
return 0;
}
void modifyarray(int b[],int size)
{
int j;
for(j=0; j<size; j++)
{
b[j]*=2;
}
}
void modifyelement(int e)
{
printf("the value of modify element is %d\n",e*=2);
}
= = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = =
= = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = =