Arrays
Hello Reader. I am writing this article on Arrays as per my knowledge. Hope So you will get good knowledge.
Introduction
The primary variables which we have discussed so far, such as ordinary ints, floats and chars, are capable of holding one value only. For example:
int a;char c;
float b;
Here the variables a, b and c are capable of storing one value at a time, that is we can not store more than one value in a, b and c at a time. But in our daily life we have come across many such situations where we need to refer a group of similar data by a single name, say a set of 100 integer values or a set of 500 real values or a set of 50 characters. For example, let you want to store 100 integer variables, then there are two ways to do so:
- either use 100 different integer variables, say n1, n2, n3,….,n100
- or use a common name to all 100 integers and then refer to each integer in terms of its position within the list of items
The former approach naturally does not seem so good. But the later approach is beneficial for the C compiler as well as for the programmer. The later approach is done using an entity called an array. An array is basically a group of data items, which are similar in nature and that, are differentiated from one another by their position within the array. In the subsequent sections we will discuss various types of arrays.
One Dimensional Array
A one-dimensional array is a structured collection of similar data items whose individual item can be accessed by using an index that indicates the position within the collection.
A typical one-dimensional array is defined as:
data-type array-name [size];
Here data-type describes the type of data stored in each location of array and array-name is the name associated with the set of values. The name of the array can not be the same as that of any other variable declared within the function. Finally the size is a positive integer constant which instructs the C compiler how many space should be reserved. The size of the array is specified using the subscript notation ([ ]). The subscript used to declare an array is called a dimension.
For example, if we want to store 100 integer values then its array declaration will be as:
int ival[100];
Similarly, if we want to store 50 real numbers then its array declaration will be as:
float fval[50];
Here ival and fval are array names that can store 100 values of data type integers and 50 values of data type float.
Accessing Array Elements
An individual array element of an array is accessed by writing the name of the array variable, followed by an expression that results in a positive integer value, enclosed with in square bracket as:
array-name [expression]
The numbering of elements in an array starts from 0.
For example, if we have an integer array as:
int val[100];
then
1st data item in this declaration is referred as val[0]2nd data item in this declaration is referred asval[1]
3rd data item in this declaration is referred as val[2]
…. …. ….
…. …. ….
…. …. ….
98th data item in this declaration is referred as val[97]
99th data item in this declaration is referred as val[98]
100th data item in this declaration is referred as val[99]
Thus the ith data item is referred to as
val[i-1]
We can assign an individual element of an array, read a value into it, writes its contents, pass it as a parameter and use it in an expression.
Thus if we want to access say 40th location in array val[], then we will use following notation:
item = val[39] ;
and if we want to store an integer 28 at 60th location then we will assign it as:
val[59] = 28 ;
Reading data items into array
Generally we read data items into array from 0 to (size-1), where size contains the actual size of an array, using for loop as:
for (i = 0; i<= size-1; i++)
{
printf(“Please enter array element #%d := ”, i+1);
scanf(“%d”, &val[i]);
}
Here the first data item in array val [] is placed into location &val [0], that’s why i has 0 initial value and this process will be repeated until i reaches (size – 1). Like ordinary integer, we have placed the “address of” operator (&) on the left side of val [].
Displaying data items of array
On the same track if we want to display the data items of array val [], we will use the following for–loop:
for (i = 0; i <= size–1; i++)
printf(“\nArray element #%d : %d”, i+1, val[i]);
Now let us read a simple program that illustrates the concept of an array.
/* Program - 1.c */
#include
main()
{
int val[5];
int i;
for (i = 0; i<5; i++)
{
printf("Please enter array element #%d : ", i+1);
scanf("%d", &val[i]);
}
for (i = 0; i < 5; i++)
printf("\nArray element #%d : %d", i+1, val[i]);
}
When you run this program, you get following output….
Please enter array element #1 : 15
Please enter array element #2 : 20
Please enter array element #3 : 12
Please enter array element #4 : 41
Please enter array element #5 : 22
Array element #1 : 15
Array element #2 : 20
Array element #3 : 12
Array element #4 : 41
Array element #5 : 22
In this program, we have entered array elements through keyboard and displayed them on the screen.
Now let us see some examples of using one dimensional array.
Some Examples
Example-1 : Write a program that searches a data item from a set of 10 numbers using linear search.
/* Program - 2.c */
#include
main()
{
int val[10];
int i, item, flag;
flag = 0;
printf("\n");
for (i = 0; i<10; i++)
{
printf("Please enter array element #%d : ", i+1);
scanf("%d", &val[i]);
}
printf("\nEnter the data item to be searched : ");
scanf("%d", &item);
for (i = 0; i < 10; i++)
{
if (item == val[i])
{
flag = 1;
break;
}
}
if (flag == 1)
printf("\nItem %d found.", item);
else
printf("\nItem %d not found.", item);
}
Example-2 Write a program that sorts a set of numbers in ascending order using Selection sort.
/* Program - 3.c */
#include
main()
{
int num[10];
int i, j, temp, n;
n = 10; /* initialize n to the size of the array */
for (i = 0; i
{
printf("Please enter array element #%d : ", i+1);
scanf("%d", &num[i]);
}
printf("\nUnsorted list of elements is as....\n");
for (i = 0; i
printf("%d\t", num[i]);
for(i=0; i
{
for(j=i+1; j
{
if (num[i] > num[j])
{
temp = num[i];
num[i] = num[j];
num[j] = temp;
}
}
}
printf("\nSorted list of elements is as....\n");
for (i = 0; i
printf("%d\t", num[i]);
}
The output of this program is as….
Please enter array element #1 : 13
Please enter array element #2 : 9
Please enter array element #3 : 18
Please enter array element #4 : 23
Please enter array element #5 : 11
Please enter array element #6 : 55
Please enter array element #7 : 22
Please enter array element #8 : 32
Please enter array element #9 : 20
Please enter array element #10 : 15
Unsorted list of elements is as....
13 9 18 23 11 55 22 32 20 15
Sorted list of elements is as....
9 11 13 15 18 20 22 23 32 55
The output of this program is as….
Please enter array element #1 : 23
Please enter array element #2 : 44
Please enter array element #3 : 12
Please enter array element #4 : 61
Please enter array element #5 : 18
Please enter array element #6 : 42
Please enter array element #7 : 11
Please enter array element #8 : 22
Please enter array element #9 : 20
Please enter array element #10 : 46
Enter the data item to be searched : 11
Item 11 found.
Initialization of Single Dimensional Array
In earlier programs, we have read data items into array through keyboard. But like ordinary variables, you can also initialize the array elements at the time of declaration as follows:
int num[5] = {12, 15, -23, 45, 10};
float sal[6] = {10.54, 26.9, 345.98, -25.5, 45.25, -55.75};
Here array name num contains 5 integers and array sal contains 6 real values. The earlier declaration causes num[0] to be initialized to 12, num[1] to 15, and so on. Similarly sal[0] is initialized 10.54, sal[1] to 26.9, and so on. A semicolon will always follow the closing brace One main point to remember is that whenever we initialize array elements during its declaration it is not necessary to mention its size that is its size is optional. Thus the following statements are also valid statements:
int num[ ] = {12, 15, -23, 45, 10};
float sal[ ] = {10.54, 26.9, 345.98, -25.5, 45.25, -55.75};
What about the boundary Limitation of an Array
Since C does not provide any facility of checking the validity of the subscript while using arrays, therefore we access the data items of an array, it is totally our duty to remember the size of the array. The compiler will not flash any error message if you try to violate the boundary of an array in your program.
Please do not try to execute the following program on your system, otherwise be ready for some disastrous result because a wrong subscripting may overlap your some important data.
/* Program - 4.c */
#include
main()
{
int num[ ] = {12, 15, -23, 45, 10};
int i;
num[6] = 50;
num[7] = 52;
for (i = 0; i < 7; i++)
printf("\nArray element #%d : %d", i+1, val[i]);
}
Multidimensional Arrays
The concept of single dimensional array is extended to multidimensional array. In multidimensional arrays, we will discuss two-dimensional and three-dimensional arrays only. Firstly we will study two-dimensional array.
Two-dimensional Arrays
Two-dimensional array is basically a collection of similar components, structured in two dimensions. In other words, a two-dimensional array is that one which have more than one row and more than one column. Two-dimensional array is useful for representing games like chess, tic – tac – toe or Scrabble. So two-dimensional array is used to represent a table with rows and columns. Each data item (component) in a table is accessed by a pair of row and column numbers of the item in that table.
Figure 1 shows a two dimensional array that has 10 rows and 20 columns. Since the numbering starts from 0, therefore rows are accessed by an integer ranges from 0 to 9 and columns from 0 to 19. Each data item is accessed by a row-column pair, with the row a number in the range 0..9 and the column a number in the range 0..19.
Figure 1
A two dimensional array is defined in exactly the same way as a one dimensional array, except that two index types must be used rather than one. The syntax of defining a two-dimensional array is as:
data-type array-name [m][n] ;
Here array-name is the name of a two dimensional array, containing data items of data-type, of having ‘m’ number of rows and ‘n’ number of columns.
If we want to use a table of 5 rows and 6 columns of having integer values then we will define it as:
int num[5][6] ;
Here num is the name of two-dimensional array with dimensions (5*6).
Accessing data items of two dimensional arrays
An individual data item of a two dimensional array is accessed by specifying the row and column of a a two dimensional array as:
num [i][j]
where ‘i’ refers to the row number and ‘j’ refers to the column number.
Now the data item in 3rd row and 5th column is referred as:
num [2][4]
Reading data items into a Two-dimensional Array
We read in the values of two-dimensional array by using two nested for loop as:
for(i=0; i
{
for(j=0; j
scanf(“%d”, &num[i][j]);
}
Here the first data item in array num[] is placed into location &num[0][0], that’s why i and j have initial value 0 each and this process will be repeated until i reaches row and j reaches col. Like single dimensional array, it is necessary to place the “address of” operator (&) on the left side of num[].
Displaying data items of array
On the same track if we want to display the data items of array num[], we will use the following nested for–loop:
for(i=0; i
{
printf(“\n”);
for(j=0; j
printf(“%d”, num[i][j]);
}
Let us see a simple program that reads and displays the elements of a two-dimensional matrix.
/* Program - 5.c */
#include
main()
{
int num[3][4];
int i, j;
printf("\nReading the contents of a two dimensional matrix (3*4).\n");
for(i=0; i<3; i++)
{
for(j=0; j<4; j++)
{
scanf("%d", &num[i][j]);
}
}
printf("\nDisplaying the contents of a two dimensional matrix (3*4).\n");
for(i=0; i<3; i++)
{
printf("\n");
for(j=0; j<4; j++)
{
printf("%d\t", num[i][j]);
}
}
}
The output of this program is as….
Reading the contents of a two dimensional matrix (3*4).
13 20 8 1
25 10 32 27
19 21 44 16
Displaying the contents of a two dimensional matrix (3*4).
13 20 8 1
25 10 32 27
19 21 44 16
Initialization of a Two-Dimensional Array
Like single dimensional array, we can also initialize two-dimensional array during its declaration as:
int num[3][4] = {
{12, 15, 30, 42},
{32, 20, 83, 35},
{15, 67, 20, 13}
};
We can also initialize it as:
int num[3][2] = {11, 31, 53, 24, 15, 16};
While initializing a two dimensional array, the declaration of first dimension, that is row, is optional but the second dimension (column) declaration is not optional. The user has to explicitly mention the size of column. Thus the following statement is completely valid:
int num[][2] = {11, 12, 13, 14, 15, 16};
But the following statements will be completely invalid:
int num[][] = {11, 12, 13, 14, 15, 16};
int num[3][] = {11, 12, 13, 14, 15, 16};
Matrices
Since a two dimensional array has two dimensions, therefore matrices are excellent example of two-dimensional array. Now we will how to use two-dimensional arrays while solving matrices problems.
Some Examples
Let us study some examples based on matrices.
Example-1 : Write a program that adds two matrices.
/* Program - 6.c */
#include
main()
{
int a[10][10], b[10][10], c[10][10];
int i, j, row1, row2, col1, col2;
printf("\nEnter the row and column of first matrix : ");
scanf("%d %d", &row1, &col1);
printf("\nEnter the row and column of second matrix : ");
scanf("%d %d", &row2, &col2);
if ((row1 == row2) && (col1 == col2))
{
printf("\nReading the contents of first matrix (%d*%d).\n", row1, col1);
for(i=0; i
{
for(j=0; j
{
scanf("%d", &a[i][j]);
}
}
printf("\nReading the contents of second matrix (%d*%d).\n", row2, col2);
for(i=0; i
{
for(j=0; j
{
scanf("%d", &b[i][j]);
}
}
for(i=0; i
{
for(j=0; j
c[i][j] = a[i][j] + b[i][j];
}
printf("\nAddition of two matrices is as:\n");
for(i=0; i
{
printf("\n");
for(j=0; j
{
printf("%d\t", c[i][j]);
}
}
}
else
printf("\nYou have entered wrong dimensions.\n");
}
Here are some sample outputs of this program:
First Run:
Enter the row and column of first matrix : 3 4
Enter the row and column of second matrix : 4 4
You have entered wrong dimensions.
Second Run:
Enter the row and column of first matrix : 3 4
Enter the row and column of second matrix : 3 4
Reading the contents of first matrix (3*4).
1 2 3 4
5 6 7 8
9 1 2 3
Reading the contents of second matrix (3*4).
9 8 7 6
5 4 3 2
1 9 8 7
Addition of two matrices is as:
10 10 10 10
10 10 10 10
10 10 10 10
In this program, we are using three two dimensional arrays a, b and c. The size of all arrays are initially set to (10*10). In this program we firstly ask the user to provide the row and column of both matrixes before reading the data items into arrays. The number of rows and columns of both matrices should be same; otherwise we will get an error message. And remember that user has to keep in mind about the boundaries of array because the C compiler will not bother about this disaster. If above two conditions are fully satisfied then the elements of both ‘a’ and ‘b’ two-dimensional arrays are read.
Example-2 : Write a program that multiplies two matrices.
/* Program - 7.c */
#include
main()
{
int a[10][10], b[10][10], c[10][10];
int i, j, k, row1, row2, col1, col2;
printf("\nEnter the row and column of first matrix : ");
scanf("%d %d", &row1, &col1);
printf("\nEnter the row and column of second matrix : ");
scanf("%d %d", &row2, &col2);
if (col1 == row2)
{
printf("\nReading the contents of first matrix (%d*%d).\n", row1, col1);
for(i=0; i
{
for(j=0; j
{
scanf("%d", &a[i][j]);
}
}
printf("\nReading the contents of second matrix (%d*%d).\n", row2, col2);
for(i=0; i
{
for(j=0; j
{
scanf("%d", &b[i][j]);
}
}
for(i=0; i
{
for(j=0; j
{
c[i][j] = 0;
for(k=0; k
c[i][j] += a[i][k] * b[k][j];
}
}
printf("\nMultiplication of two matrices is as:\n");
for(i=0; i
{
printf("\n");
for(j=0; j
{
printf("%d\t", c[i][j]);
}
}
}
else
printf("\nYou have entered wrong dimensions.\n");
}
Here are some sample outputs of this program:
First Run:
Enter the row and column of first matrix : 2 4
Enter the row and column of second matrix : 4 3
Reading the contents of first matrix (2*4).
2 4 5 6
1 6 3 8
Reading the contents of second matrix (4*3).
5 3 8
9 0 1
3 5 7
4 6 1
Multiplication of two matrices is as:
85 67 61
100 66 43
Second Run:
Enter the row and column of first matrix : 2 4
Enter the row and column of second matrix : 3 4
You have entered wrong dimensions.
Three Dimensional Arrays
C does not put any limit on the number of dimensions that an array can have. We understand three dimensional array concepts by following example. Let we want to keep the information of items, month wise, sold from different stores. Each data items that has been sold is represented by three indexes:
m-num – the month in which it was sold
s-num – the store numbers from where it was sold
i-num – which item number was sold
And its declaration is as:
int sales[m-num][s-num][i-num];
We know that two loops are necessary to access each component in a two-dimensional array, likewise it takes three loops to access each component in a three dimensional array. The only problem is to find out – which index controls the outer loop, the middle loop and the inner loop. If we want to calculate the monthly sales by the stores then month will control the outer loop and store will control the middle loop. If we want to calculate monthly sales by item number then month will control the outer loop and item number will control the middle.
For example, let you declare the three dimensional as:
int sales[12[5][10];
A graphical representation of the array variable sales is shown in figure-11.2. The number of data items in sales is 600 (12*5*10).
Figure 2
In following loop, we read in the values of array sales:
for (i=0; i
{
for (j=0; j
{
for (k=0; k < i-num; k++)
scanf(“%d”, &sales[i][j][k]);
}
}
Similarly if we want to print the output of sales report according to the item number sold from different stores monthwise, we will use following loops:
for (i=0 ; i < i-num ; i++)
{
for (j=0; j
{
for (k=0; k
printf(“%d”, &sales[i][j][k]) ;
printf(“\n”);
}
printf(“\n”);
}
Initialization of Three Dimensional Array
Like single dimensional array or two-dimensional array we can also initialize three-dimensional array as:
int sales [3][4][2] = {
{
{5, 3},
{6, 9},
{2, 7},
{9, 2}
},
{
{4, 3},
{1, 0},
{8, 2},
{1, 5}
},
{
{1, 12},
{56, 9},
{12, 27},
{99, 20}
},
{
{44, 33},
{21, 10},
{18, 82},
{11, 35}
}
};
Array of Characters
Since we know that an array is a collection of data items of the same data type that referenced by a single name. Earlier we have discussed about an array of ints or array of floats only. In this chapter we will also discuss an array of chars and their cousin string.
Like array of ints, we can have an array of characters. An array of chars is declared as:
char array-name [size];
Here array-name is the name of array containing data items of character type and the size is the total number characters in array-name.
For example, if we declare the following statement:
char ch[20] ;
Here ch is the name of an array, which is capable of storing 20 characters. The individual character of this array can be accessed by using a subscript or an index as:
ch[index_no];
Like an array of int, the array indexes starts from 0 in array of chars also. It means that if we want to refer the 5th element of ch[] array then we write as:
ch [4]
Similarly you can access other data items of this character array.
The way you read the data items of integer array, you read the data items of character array as:
for (i=0; i
scanf(“%c”, &ch[i]);
And the procedure of writing the output of character array is also same, as follows:
for (i=0; i
printf(“%c”,ch[i]);
Following program illustrates the concept of an array of char:
/* Program - 9.c */
#include
main()
{
char ch[11];
int i;
printf("\nPlease enter any 11 characters : ");
for(i=0; i<11; i++)
scanf("%c", &ch[i]);
printf("\nYou have entered these characters : ");
for(i=0; i<11; i++)
printf("%c",ch[i]);
}
The output of this program is as….
Please enter any 11 characters : Atishrestha
You have entered these characters : Atishrestha
And like array of int, the characters of ch-array are also stored in consecutive memory locations as shown below:
64000
64002
64004
64006
64008
64010
64012
64014
64016
64018
64020
A t i s h r e s t h a
Since, in C each character occupies one byte in memory that’s why the difference between two adjacent characters is 1.
Initialization of Character array
Like array of ints or floats, we can also initialize an array of char during its declaration as:
char ch[11] = {‘A’, ‘t’, ‘i’, ‘s’, ‘h’, ‘r’ , ‘e’, ‘s’, ‘t’, ‘h’, ‘a’};
or we can also write it as:
char ch[] = {‘A’, ‘t’, ‘i’, ‘s’, ‘h’, ‘r’ , ‘e’, ‘s’, ‘t’, ‘h’, ‘a’};
It means that if we initialize the character array during its declaration, then the size declaration is optional, and it is the duty of user to remember the number of characters stored in the array.
Strings
The most familiar use of one-dimensional character array is the ‘string’. A string is defined by a character array terminated by a NULL character. And this NULL character is represented by a ‘\0’. Here you should not confuse between the ‘\0’ and ‘0’ character. That character sequence ‘\0’ is not treated as two characters, rather than it is treated as a single character, known as a NULL character. And another distinguished feature is that the ASCII value of NULL character is 0 whereas the ASCII value of 0 is 48.
Thus when we are going to initialize a string, then it becomes necessary to insert the NULL character at the end of the string as shown below:
char name[6] = {‘L’, ‘o’, ‘h’, ‘i’, ‘t’, ‘\0’};
Now look at the earlier initialization and this later initialization. In earlier initialization we did not insert a NULL (\0) character, so it is a simple an array of chars, whereas in later initialization we have inserted a NULL (\0) character at the end, therefore it is not just a simple array of char, rather it can be treated as a string.
Basically there are two ways of initializing a string:
char name[6] = {‘L’, ‘o’, ‘h’, ‘i’, ‘t’, ‘\0’};char name[6] = “Lohit” ;
In earlier initialization (first one) of these strings, we are storing the characters individually and therefore it is essential to insert a NULL character at the end, whereas in later case (second one) the null character is inserted automatically by the compiler. One main point to remember that while declaring an array of char as a string then the size of string should be declared one character longer. It means that if an array of chars can hold 6 characters then it can store 5 characters as a string because last character stored in the string is a NULL character. On the other hand, if we want to store only characters then it can store 5 characters.
Now we will see how to display the output of strings. In first method we just write the print statement as we have used earlier i.e.
/* Program – st.c */#include
main()
{ char name[6] = “Lohit”;
int counter;
for (counter = 0; counter <6; counter++)
printf(“%c”, name[counter]);
}
The output of this program is as….
Lohit
The limitation of this program is that programmer has to mention the length of the string in his program. One may ask - Is there any other option to find the end of the string? Its answer is yes. And here introduces the advantage of associating a NULL (\0) character at the end of the string. Even if we do not know the number of character in a string, but we can easily traverse from one character to next until a NULL character appears.
Following program illustrates this concept clearer:
/* Program – st1.c */#include
main()
{
char name1[] = "Adam";
char name2[] = "Gilchrist";
int counter;
printf("\nThis output has come without a NULL character.");
for(counter=0; counter<4; counter++)
printf("%c",name1[counter]);
printf("\nThis output has come with the help of a NULL character."):
for(counter=0; name2[counter] != '\0'; counter++)
printf("%c", name2[counter]);
}
The output of this program is as….
This output has come without a NULL character.
Adam
This output has come with the help of a NULL character.
Gilchrist
In this program we have used two loops. First loop uses number of characters stored in the array and it ends when the counter variable ‘i’ becomes 4. Second loop continues until the ‘\0’ character appears in the variable name2[i]. Because we all know that each string is always ended by the ‘\0’ (NULL) character. Now you may better understand the use of NULL character.
In above program we have accessed the elements of character array one by one. Fortunately C provides a better way to access the complete string simultaneously by providing a format specifier %s in the format string. We all know that
%d is used for integer%f is used for float and
%c is used for character variables
Similarly
%s
is used for strings.
Following program illustrates this concept.
/* Program - st2.c */#include
main()
{
char name1[] = "Adam";
char name2[] = "Gilchrist";
printf("\nFirst name : %s", name1);
printf("\nSecond name : %s", name2);
}
The output of this program is as….
First name : Adam
Second name : Gilchrist
Similarly we can also receive a string from the keyboard by using %s as format specifier in strong format of scanf() as depicts in following program:
/* Program - st3.c */#include
main()
{ char name1[15], name2[15];
printf("\nEnter first name : ");
scanf("%s", name1);
printf("Enter second name : ");
scanf("%s", name2);
printf("\nFirst name : %s", name1);
printf("\nSecond name : %s", name2);
}
The output of this program is as….
Enter first name : Atishrestha
Enter second name : Sagar
First name : Atishrestha
Second name : Sagar
The first limitation of using ‘%s’ in format specifier is that the programmer has to keep in mind about the size of character array. It means that if you are declaring 15 as a size of array char then you can not store more than 15 characters into it. If you have stored more than 15 characters then the result would be unpredictable because upto 15 there is no problem, but after this if you just type another character then it may overlap over some other important information and thus it may lead to disastrous result. So be care full when you are receiving strings from the keyboard.
Another limitation with the receiving of strings from keyboard is that you can not receive multi words string from the keyboard through scanf () statement. What should you expect the output of the following program?
/* Program - st4.c */#include
main()
{
char name[20];
printf("\nEnter your name : ");
scanf("%s", name);
printf("Your name is %s.", name);
}
The output of this program is as….
Enter your name : Nikita Sagar
Your name is Nikita.
From the output of this program it is clear that if you type Nikita Sagar then only the first word ‘Nikita’ would be stored in string name2. It happens so because after typing ‘Nikita’ when you typed ‘Sagar’ just after one or more spaces then it would automatically terminate the string. That’s why we receive only first word ‘Nikita’.
Fortunately C also provides a standard function gets() to receive multiword strings from keyboard and puts() to print multiword strings on the screen.
Following program illustrates this concept:
/* Program - st5.c */#include
main()
{ char name1[15], name2[15];
printf(“\nEnter the name of first user : ”);
gets(user1);
printf(“\nEnter the name of second user : ”);
gets(user2);
printf(“\nFirst user name : ");
puts(user1);
printf(“\nSecond user name : ”);
puts(user2);
}
The output of this program is as….
Enter the name of first user : Steve Waugh
Enter the name of second user : Mark Waugh
First user name : Steve Waugh
Second user name : Mark Waugh
In this program we have used two built-in functions gets () and puts () to receive and display the multi words string respectively. But these functions are not without limitation. The main limitation is that we can receive only and only one string by using function gets () and similarly we can display only one string at a time. It means that following statements are absolutely invalid:
gets (name1, name2);puts (name1, name2);
Like
printf() function, in puts()
function we can also display the string constant on the screen.
Now let us write a simple string program that converts an uppercase string into lower case string. That is if you entered following string
HOW ARE YOU?
You program should display following string
how are you?
We know that the ASCII value of uppercase letters (A, B, C,…. X, Y and Z) come between 65 and 90 and the ASCII value of lower case letters (a, b, c,….x, y and z) falls between 97 to 122. The difference between the each uppercase letter and its corresponding lowercase letter is of 32.
Following program uses this difference to convert uppercase letters to lowercase:
/* Program - st6.c */#include
main()
{ char name[40];
int i =0;
puts("\nEnter any upper case string : ");
gets(name);
puts("You have entered this upper case string : ");
puts(name);
while (name[i] != '\0')
{
if ((name[i] >=65) && (name[i] <=90))
name[i] = name[i]+32 ;
i++ ;
}
puts("\nChanged lower case string : ");
puts(name);
}
The output of this program is as….
Enter any upper case string : HOW ARE YOU?
You have entered this upper case string : HOW ARE YOU?
Changed lower case string : how are you?
You can try yourself another program that converts a lowercase string into an uppercase string.
Array of Strings
Array of strings is also known as two-dimensional array of characters. The declaration of two-dimensional array of characters is as:
char array-name[row][col] ;
Here array_name is the name of a two-dimensional array of strings, row contains number of strings and col contains the number of columns reserved for each string.
For example, consider the following declaration
char days[7][10];
Here days is the name of array having 7 strings (or rows) and 10 is the number of columns reserved for each string (row).
We can also initialize the array of strings during its declaration as:
char days[7][10] = {{‘M’, ‘O’, ‘N’, ‘D’, ‘A’, ‘Y’, ‘\0’},
{‘T’, ‘U’, ‘E’, ‘S’, ‘D’, ‘A’, ‘Y’, ‘\0’},
{‘W’, ‘E’, ‘D’, ‘N’, ‘E’, ‘S’, ‘D’, ‘A’, ‘Y’, ‘\0’},
{‘T’, ‘H’, ‘R’, ‘U’, ‘S’, ‘D’, ‘A’, ‘Y’, ‘\0’},
{‘F’, ‘R’, ‘I’, ‘D’, ‘A’, ‘Y’, ‘\0’},
{‘S’, ‘A’, ‘T’, ‘U’, ‘R’, ‘D’, ‘A’, ‘Y’, ‘\0’},
{‘S’, ‘U’, ‘N’, ‘D’, ‘A’, ‘Y’, ‘\0’}
};
Another way of initializing the array of strings is as:
char days[7][10] = {“MONDAY”,
“TUESDAY”,
“WEDNESDAY”,
“THRUSDAY”,
“FRIDAY”,
“SATURDAY”,
“SUNDAY”
};
Naturally the later initialization is more easily understandable for the C lovers.
If we want to display the contents of array of strings named days [][] then we will use the following statement:
for (i=0; i<=6 ; i++)printf (“\n %s”,days[i]);
You can also use the following statement to display the contents of array of strings named days [][]
for (i=0; i<=6 ; i++)printf (“\n %s”,&days[i][0]);
Similarly if we want to read the strings into array from the keyboard we will use the following statement:
for (i=0; i<=6 ; i++)scanf (“\n %s”,days[i]);
Following program will clear this concept more.
/* Program - st7.c */#include
main()
{
char days[7][10] = {
"MONDAY",
"TUESDAY",
"WEDNESDAY",
"THRUSDAY",
"FRIDAY",
"SATURDAY",
"SUNDAY "
};
int choice;
printf("\nEnter any week day number : ");
scanf("%d", &choice);
if ((choice >=1)&&(choice<=7))
printf("\nYou have entered : %s",days[choice-1]);
else
printf("\nYou have entered wrong number.");
}
Here are some sample outputs of this program….
First Run :
Enter any week day number : 3
You have entered : WEDNESDAY
Second Run :
Enter any week day number : 8
You have entered wrong day number.
You can also receive array of characters through the console using the scanf() function.
Features of C++
In this article you can read some major features of C++.
Data Declaration in C++
C++ provides the facility of declaration of variables with the statements of the program. In contrast to this we have to declare all the variables at the beginning of a block in ANSI C. But we are fortunate that C++ allows us to declare the variables anywhere in the program but prior to its use. The plus point of this type of declaration is that the program becomes more readable, because the variable is declared and initialized close to where it is actually used.
Following code segment illustrates this:
#include
void main()
{
….
for(int j=1; j<=n; j++) /* OK in C++ but in ANSI C */
{
….
….
}
….
}
This facility is very useful because we can declare a variable when needed and initialize it immediately.
New Looks of Functions
Like C, every C++ program is basically a collection of one more functions in which main() is an essential function. C++ provides several new features to make functions more efficient and safe to use. In C++ we have to declare a function prototype, complete with a list of receiving arguments that the function accepts and its return type. Of course we can use function prototype in C, they are not mandatory. However if we do not want to declare its prototype in C++ then we have to define it before its first call.
Now let us study some new features functions of C++.
Default Arguments in Functions
C++ provides the facility of defining default values for arguments, that are not passed when the function is called, when we provide a prototype for a function. A C++ function prototype can declare that one or more of the function’s argument have default argument values. For example, consider the function Box() which draws a box on the screen. We may provide the default values for the box dimension as follows:
void Box(int x1=5, int y1=5, int x2=20, int y2=75);
Now when a call to the function Box() does not contain the corresponding arguments, the compiler inserts the default values where it expects to see the arguments. Let us understand this concept of default arguments by examining the following code segment:
Box( ); /* same as Box(5, 5, 20, 75) */
….
Box(10, 10); /* same as Box(10, 10, 20 75) */
….
Box(15); /* same as Box(15, 5, 20 75) */
….
Now let us examine this code. When we call the function Box() with no arguments then the function prototype fills x1, y1, x2 and y2 with default values. In second call statement Box(10, 10), the first and second formal arguments are replaced with actual arguments and the third and forth formal arguments will use default values, which is 20 and 75. In third call when we pass only single value then it will replace only first default value, however the remaining three default values will remain. Note that it is impossible to give a non-default value for the x2 argument without specifying the values for x1 and y1. Thus in default arguments case, we will have to remember two main points:
- default values are always been taken from trailing variables.
- default values should be defined where we are defining the function prototype and should not be repeated in function definition.
Overloading Functions
C++ provides the facility of having several functions with the same name. This feature is called overloading function. Function overloading is the process of having unique name for two or more functions as long as their argument lists differ, that is two functions are said to be overloaded if they have identical name and have different argument lists.
C++ provides already some in built overloaded functions. For example, the arithmetic expression
10 + 20
calls the addition operation for integer operands, whereas the expression
10.0 + 20.0
calls a different addition operation that handles floating point operands. Like this we can also define a set of user-defined functions that perform the same general action but that apply to different to argument types. In ANSI C we have three different functions for calculating area of three different shapes, as follows:
float area_circle(float);
float area_triangle(float, float);
int area_rectangle(int, int);
Here each function performs the similar actions, that is each function returns the area of the argument(s) that it receives. In C++ we can use the name area() for all three versions and declare them as follows:
float area(float);
float area(float, float);
int area(int, int);
Here user has to write a separate function definition for each overloaded area() function that has a unique set of parameters. These three functions are called as follows:
….
float radius=20.5;
float base = 10.5;
float height = 19.6;
int length = 15;
int breadth = 20;
….
x = area(radius);
….
y = area(base, height);
….
z = area(length * breadth);
….
Here the C++ compiler selects the corresponding function by comparing the types of arguments in the call with those that are specified in the function’s declaration. It is so because overloaded functions are identified by the values or parameters passed to them. So when a call area(radius) is made then that function will be called which receives one float argument. Similarly when a call area(base, height) is made then that function will be called which receives two float arguments. One main point to note here is that overloaded functions are not identified by what values are returned by them, rather they are identified by the argument lists.
Now the question arises - when to overload a function name and when not. The function overloading is prohibited especially when a set of functions operate on the same of data type but perform different activity; instead such functions should be defined with unique names. The conclusion is that if your program logic needs a certain feature then use it. The programmer should not force to use overloaded function, just for simply it is there, it should be implemented only where it feels natural to use them.
Inline Functions
Generally when a function is called, the control is transferred to that function, along with some values if necessary, and after execution, the control is transferred back to the calling function. Obviously it saves memory space but certainly increases execution time. To reduce this execution time, C++ language provides inline functions.
The syntax of declaring inline functions is
inline function_name(list_of_arguments)
{
// Function body
}
A function is made “inline” by using the keyword inline before the function’s return type of the function definition. Whenever we call inline function, the C++ compiler places the entire code of inline function directly inside the code of the calling function. In other words we can say that inline functions are just like preprocessor macros because the compiler substitutes the entire function body for each inline function call. But these two are differ in a crucial aspect. Let us see where they differ.
Consider the following code segment:
….
#define multiply(a, b) (a*b)
….
x = multiply(6+1, 10);
….
Here the C preprocessor expands this statement as:
x = (6+1* 10);
This evaluates to 16 instead of the result of multiplying (6+1) and 10, which should have been 70. However if we use inline function as:
….
inline multiple(int a, int b)
{
return (a*b);
}
void main()
{
….
….
x = multiply(6+1, 10);
….
}
Now when the inline function multiply() is called, it produces the output correctly, that is 70. Another plus point of inline functions over preprocessor macro is that inline functions can also be overloaded like true functions.
The limitation of inline function is that the entire inline function should always occur before main () or they are called. Don’t get confused between the using of inline and normal functions. If the function code is small, straight-line or when there are relatively few calls to it then use inline function otherwise uses the normal function.
Remember that when we define the function inline, it is up to the C++ compiler whether to insert the code of inline function or not to insert. It is because we are just requesting the C++ compiler. The compiler may ignore this request, because the function declared inline might not be a good candidate for expansion at the point of call. So there is no hard and fast rule that its code must be placed at the place where the call is being made. The compiler may overrule you without saying so.
Friend Functions
One of the important features of object-oriented programming is data hiding of data members. The rules of data hiding is that only member functions of a class can access the private data of a class. But sometime we need to operate on private data members of two classes outside those classes. This facility is provided by using a friend function. A friend function is used to operate on objects of two different classes. Logically, such a function should be a member of both classes. But it is impossible. The only way to achieve this goal is by using a friend function that acts as a bridge between two different classes. A friend function belongs to neither, and able to access both.
Following code segment illustrates this concept.
….
class Sample;
class Example
{
private :
int i;
public :
Example (int ii)
{
i=ii;
}
friend int add(const Example &ff, const Sample &ss);
};
class Sample
{
private :
int j;
public :
Sample (int jj)
{
j=jj;
}
friend int add(const Example &ff, const Sample &ss);
};
int add(const Example &ff, const Sample &ss)
{
int temp;
temp = ff.i+ss.j;
return temp;
}
void main()
{
Example f(100);
Sample s(200);
int number;
number = add (f, s);
cout << number;
}
When we run this program, we get the following output….
300
In this code segment we have used to two classes Example and Sample. The constructor in these classes initialize their private data member i and j to 100 and 200 respectively. In both classes we have declared a function add() to access their private data member as:
friend int add(const Example &ff, const Sample &ss);
This declaration can be placed anywhere in the class, either in private section or in the public section. Note that the friend declaration is necessary in both classes. Another notable point is the declaration class Sample; at the beginning of the program. This forward declaration is necessary because we can not refer a class until it has been declared. The class Sample is being referred to in the declaration of the function add() in class Example. So class Sample must be declared before Example.
This declaration tells the compiler that the class Sample is defined later. However, If we do not do this then the compiler can not understand the Sample type when it encounters the Example’s friend declaration and therefore the compiler will report an error message. If you place the entire class Sample definition before class Example then the compiler would not know what the Example type is when it encounters the friend declaration in the Sample class type. That’s why it is necessary to use the forward declaration.
Look at the definition for add(). This does not use the keyword friend and the scope resolution operator (::). The keyword friend is used only for the prototype appearing in a class using the function and the scope resolution operator is not used because this friend function does not belong to any class. It means that the friend function has file scope, rather than class scope. Thus there will only one friend function with a specific name and signature (list of arguments received) per file.
Struct in C++
Another important features of C++ is that we can start using the name of a struct as soon as its definition is started. In C, let we have following self-referential structure as:
typedef struct Employee
{
char name[20];
int age;
float salary;
struct Employee *link; /* pointer to another Employee node */
} Employee;
Employee *e; /* define an Employee node */
However in C++ we can have the same code in much simpler way, as follows:
struct Employee
{
char name[20];
int age;
float salary;
Employee *link; /* pointer to another Employee node */
} ;
Employee *e; /* define an Employee node */
This code segment shows that the name of a struct can be used inside the definition of the struct itself. Note that C++ structures offer more than their C counterparts: they can hold functions declaration and definitions as well as data members. Following code segment illustrates this:
struct Employee
{
char name[20];
int age;
float salary;
void getdata()
{
cin >> name >> age >> salary;
}
void display()
{
cout << name << age <
}
};
We access the member function of a struct in the same way we access its data members, that is using a dot (.) operator.
Introduction to Reference
A reference is referred to as an alias or synonym, that is an alternate name for another variable. Using reference we can pass large amount of data without the overhead of copying them. References are much like pointers. You can do anything with a reference that you can do with a pointer. Of course pointer also is an important feature of C and C++, but sometimes it may trouble you and even a good programmer for some complex operations. However it has certainly some plus points over pointers.
A reference is declared using the type specifier with the address-of (&) operator. A reference must be initialized when it is declared. Following code segment illustrates this :
….
int a=10;
int &b = a; // declaration and initialization of a reference variable
….
Here we have declared an integer variable, a, that has another name, b. Note that a reference can not be made to refer to another variable once it is initialized o some variable. If you make any change to a reference then that change is actually applied to the variable to which the reference refers. For example,
b+= 5;
adds 5 to a, the variable referred to by b. Another main point to note that each definition of a reference must be preceded by the address of operator. For example,
int &x = a, y = b;
defines one reference and one variable.
Another main point to remember is that a reference is neither a copy nor a pointer to the object to which it refers. Instead it is just like another name. Look at the following code segment:
….
int a = 20 ;
int & b = a;
cout << “\n a = ” << a << “ Address of a = ” << &a ;
cout << “\n b = ” << b << “ Address of b = ” << &b ;
….
The output of this code segment is
a = 20 Address of a = Ox8facfff420
b = 20 Address of b = Ox8facfff420
Thus we can say that the two addresses are same.
Standard I/O
We know that ANSI C provides all the standard library I/O functions in the stdio library. C++ also provides the stdio library as well as a group of classes and fuctions for I/O defined in the iostream library. To access these, we must include the directive #include in our program. There are many advantages in using iostream rather than stdio, such as the syntax is simpler, more elegant, and more intuitive in C++ than in ANSI C, formatting output is simplifier by extensive use of overloading operators, etc.
C++ provides four predefined stream objects defined as follows:
- cin – standard input object, usually associated with the keyboard, and corresponding to stdin in C
- cout – standard output object, usually associated with the display, and corresponding to stdout in C
- cerr – standard error object, usually associated with the display, and corresponding to stderr in C
- clog – a buffered version of cerr (no C equivalent)
We can easily redirect these standard streams from and to other devices and files. There are several classes in iostream library. The istream class includes overloaded definition for the >> operator for the standard data type
(int, long, double, float, char and char *(string)).
For example, in the following statement
cin >> n;
the C++ compiler calls the appropriate >> operator function for the istream cin defined in iostream.h and uses it to direct this input stream into the memory location represented by the variable ‘n’. Similarly the ostream class includes overloaded definition for the << operator for the standard data type (int, long, double, float, char and char *(string)). Thus
cout << n;
sends the value of ‘n’ to ostream cout for output. Since the return type of these both operator functions are a reference to the appropriate stream class type in addition to moving the data, we can use these operators in cascading manner for input or output sequence of characters:
cin >> a >> b >> c;
cout << a << b << c;
We can also cascade two or more different data types in a single statement using cout as:
…
int age=20;
float salary=20000.50;
char name[20];
cout << "Name : " << name << "Age : " << age << "Salary : " << salary;
….
Introduction
In this my article you can read how to define, declare and call C functions. Before writing of large and complex programs, one should remember that our program should be readable, understandable, easily debugged and easily modified. Therefore the idea is to break a large problem into subproblems that can be handled more easily. If the subproblem is still a bit complex, it can be further divided it into smaller subproblems. This process continues until each subproblem can not be further divided. For example – in a magical matrixes problem, one module could read data items into matrix, one could display these data items, one could provides the result of two matrices, other may add diagonal elements of a matrix, and so on. These subproblems are referred to as modules.
Thus when a problem has been divided into subproblems or modules, it can be easily programmed to solve a problem. Each module performs a well-defined task. In C we refer these modules as functions. Therefore the concept is that functions are the basic building blocks in our C language.
C is basically a collection of functions in which main() is an essential function. The C functions you have used so far, such as printf and scanf, are built into the C libraries. However, in C you can also write our own functions to organize and simplify large and complex programs. This chapter describes how to define, declare and call C functions.
Function Types
A function is an independent collection of declarations and statements usually designed to perform a specific task. C supports two types of basic functions:
- Standard (library) functions
- User-defined functions
Standard Functions
The functions, which are already defined in the C libraries for the users, are called as standard functions. The standard functions are also called as library functions or ready made functions. You can use these standard functions in your program, but you can not change the statements of these standard functions. For instance, printf(), scanf(), gotoxy(), clrscr(), etc. are some more commonly used standard functions.
User-defined Functions
The functions, which are defined by the user for its sake of convenience, are known as user-defined functions. You can write as many functions as you need.
The Function Definition
A function definition specifies the name of the function, the numbers and types of its formal argument and the declaration and statements that determine what it does. It can also specify the return type of the function. The function definition is the actual body of the function. The function definition starts with the function header and then comes the body of the function, or you can say the function block.
The general syntax of a typical function definition is as:
data-type func-name(list-of-formal-arguments & its declaration){
declaration of local variables, if any;
Statement-1;
Statement-2;
Statement-3;
Statement-n;
return (value);
}
Now let us discuss this. The very first line of the function definition is called as function header. The function header consists of three parts – return data type, function name and list of formal arguments. Here the data-type is type of data returned by this function to the calling function. The data-type can be either a basic data type or a user-defined data type.
The return data type given in the function definition must match the return type in the declaration of the function elsewhere in the program. If the type is not specified then its return type is an int by default. However, functions with other return data types must be defined or declared before they are called. Obviously a function’s return data type is used only when the function returns a value. Functions can not return arrays or functions rather they can return pointers to any data type, including arrays and functions.
After the return type, we have function name, func-name. The function name is any legal identifier followed by the function parenthesis without any spaces in between.
The arguments (or parameters) come inside the parenthesis, preceded by their types and separated by commas. The list-of-formal-arguments consists of one or more arguments. If the function does not use any parameter then the word void is used inside the parenthesis. No doubt, the empty parenthesis can be used.
And in curly brackets, after function parenthesis, we write the body of the function, which consists of local variables, if any, and statements. A function body is a compound statement containing the statements that define what the function does. It may also contain the local variables, which are used by these statements.
When the function is called, storage is created for the local variables and local initializations are performed. When the function is called the control is transferred to the function and the execution of function starts from the first statement in the compound statement and it will continue execution until a return statement is executed or the end of the function body is encountered. After the completion of execution of the program, the control is returned to the point at which the function was called.
Here are some examples of function definitions:
(i)
float sum(int a, float b){
….
}
(ii)
char lowercase(char ch){
….
}
The first definition tells that the sum() function receives two variables – one is integer and other is float, which are stored in two formal arguments a and b and after the execution of the function sum(), it returns a value whose type is float.
The second definition tells that the lowercase() function receives one character value in the formal argument ch and after its execution it returns a char value.
Actual and Formal Arguments
Before the discussion of functions in details, I want to clear your concept about the arguments. In C interfacing between functions are provided by actual arguments or by externally declared variables. Basically we have two types of arguments in using functions:
- Actual arguments
- Formal arguments
The variables given to a function in the call statement are called as actual arguments and the variables listed in the definition of a function are called as formal arguments. Communication between the calling function and the called function is carried through the use of two lists of parameters: the actual parameter list, which is in the calling statement of the function and the formal parameter list, which is specified in the function definition. When a function is executed, it uses the actual arguments given to it in the function call.
All actual arguments are passed by value. A copy of the actual arguments is assigned to the corresponding formal parameters. In this case the function uses this copy without affecting the variable from which it was originally derived.
As stated earlier, formal parameters are variables that receives values passed to a function by a function call. There are two ways of declaration of function’s formal parameters:
- In the old form of a function definition, the formal parameters were declared following the closing parenthesis, immediately before the opening brace of the function body. In that form, the parenthesis consists of the name of each of the formal parameters and the order in which they receive the values in the function call.
Following function definition shows this old-style definition:
swap (a, b)int a, b;
{
…. /* Statements */
}
In the new form of a function definition, the formal parameters declaration specify the types, sizes, and identifiers of value stored in the formal parameters. Each identifier in the formal parameter list must be preceded by its appropriate type specifier. This type of function definition is called as function prototype definition because the parenthesis following the function name contains the complete declaration of the function’s formal parameters. Later on we will discuss about function prototypes.
Following function definition shows function prototype definition:
swap (int a, int b){
…. /* Statements */
}
Here one should remember that the types of the actual arguments in calls to a function must be assigned compatible with the types of the corresponding formal parameters. A formal parameter can have any basic data type, structures, unions, arrays or pointer type.
Function Calls
A function is called in much the same way it is declared. Any function is called through a function call. A function call is an expression that transfers the control and actual arguments, if any, to a function. The syntax of a typical function call is:
func-name (list-of-actual-arguments);
Here the func-name is the name of the function to be called and the list-of-actual-arguments contains a list of the actual arguments (separated by commas) passed to the function. If the function takes no argument, the list-of-actual-arguments can be empty. The first argument in the list is always correspond to the first formal parameter of the function, the second one corresponds to the second formal parameter and so on through the list.
After the execution of the function call, the control is transferred to the first statement in the function. The control is returned back from the called function to the caller when the called function encounters a return statement. If no return statement is executed, the control is returned back after the execution of the last statement of the called function. In such cases, the return value is undefined.
One main point to note here is that when the called function uses the copies of the actual arguments, any change it makes to the formal arguments do not affect the values of the variables from which the copies may have been made.
The return of a Function
A function’s return type is used only when the function returns a value. A function returns a value when a return statement containing an expression is executed. Generally the function block ends with the return statement. The general syntax of the return statement is
return(expression);
Here the parenthesis is optional. If the return statement does not contain an expression, the return value is undefined. Let us see some examples of return statements:
return area;return (a*b);
If the function does not return any value then no return statement is used.
Since main() function does not return any value, therefore no type is specified in its header. But some compilers (like Turbo C or Turbo C++) give a warning if you do not use the return statement at the end of the main block. You can avoid this warning by writing main function as:
main(){
….
….
return (0);
}
You can also avoid the warning message by writing its return type void as:
void main(){
….
….
}
However in some other books, you may also run across programs with the main function declared as:
void main(void){
….
….
}
User-defined Functions Types
There are four types of user defined functions:
- Functions with no arguments and no return value
- Function with no arguments but return value
- Functions with arguments but no return value
- unction with arguments and return value
Now we will discuss these types one by one.
Functions with no arguments and no return value
The functions that neither receives any argument from the calling function nor returns any value to the calling function are known as functions with no arguments and no return value. Look at the following example:
/* Program - lohit1.c */
#includemain()
{
printf("\nWelcome.");
sample();
printf("\nBye.");
}
sample()
{
int a, b, c;
printf("\nEnter any two numbers : ");
scanf("%d %d", &a, &b);
c = a+b;
printf("Addition of two numbers: %d", c);
}
The output of this program is as:
Welcome
Enter any two numbers: 10 20
Addition of two numbers: 30
Bye
In this program we call a function sample() in function main(), with no arguments. Here main() is known as the calling function and sample() is known as called function. In function main(), when we call the function sample(), the control is transferred to the function sample() from the function main(). And after the execution of called sample() function, the control is transferred back to the calling function at the point from where the control was transferred to the called function. Since we are not passing any arguments to the function sample(), so there will be no formal arguments.
In a C program, we may have one or more than one function in which main() is an essential function because main() is a function, which tells the C compiler that the execution of the program starts from here. There is no restriction on the number of functions that might be present in the C program. And note that the functions would execute in the order in which they are called, not in the order in which they are written. We may define any function anywhere in the program and in any function we can call any function. But it is a good habit to define the functions in the same order in which they are called.
If a function takes no argument or contains the keyword void in its declaration then the compiler expects zero argument in function call and zero formal arguments in function definition. These four functions do not return any value to the function main(). If any function do not return any value then we must use the keyword void as a function’s return type.
Functions with no arguments but return values
In this category we include those functions, which do not receive any type of arguments but returns some value. Look at the following program in which we have called function sum() and multiply() that receive no arguments but return a value.
/* Program – lohit2.c */
#includemain()
{
int item;
item = sum();
printf("The addition of two numbers : ", item);
item = multiply();
printf("The multiplication of two numbers : ", item);
}
sum()
{
int a , b , c ;
printf("\nEnter any two integers for addition : ");
scanf("%d %d", &a, &b);
c = a+b;
return (c);
}
multiply()
{
int a , b , c ;
printf("\nEnter any two integers for multiplication : ");
scanf("%d %d", &a, &b);
c = a*b;
return (c);
}
The output of this program is as….
Enter any two integers for addition:10 20
The addition of two numbers : 30
Enter any two integer for multiplication: 15 30
The multiplication of two numbers : 450
In this program we have called two functions add() and multiply(). These functions have local variables, such as ‘a’, ‘b’ and ‘c’, declaration within it. These variables are accessible only with in the block in which they are defined. In these function we are returning the value stored in variable ‘c’ to the calling function. When a function returns some value then it must be stored in some variable. In this program we have used a variable ‘c’ to store this returning value. We have already studied that the return statement is used to return a value from the calling function to the called function. The return statement is used to return a single value only.
Functions with arguments but no return value
In this category we include those functions, which transfer actual arguments in formal arguments but no value is returned from the calling function to the called function. Look at the following program-chap1205.c, in which we have called function sum() and multiply() with two actual arguments a and b that are collected in two formal arguments x and y respectively but both these function do not return any value.
/* Program – lohit3.c */
#includemain()
{
int a , b , c ;
printf("\nEnter any two integers for addition : ");
scanf("%d %d",&a, &b);
sum(a,b) ;
printf("\nEnter any two integers for multiplication : ");
scanf("%d %d",&a, &b);
multiply(a, b);
}
sum(int x, int y)
{
int z;
z = x+y ;
printf("\nThe addition of two numbers : %d", z);
}
multiply(int x, int y)
{
int z ;
z = x*y ;
printf("\nThe multiplication of two numbers : %d", z);
}
The output of this program is as….
Enter any two integers for addition:10 20
The addition of two numbers : 30
Enter any two integer for multiplication: 15 30
The multiplication of two numbers : 450
Functions passing arguments with some return value
The function that passes a list of parameters to calling functions and returns some value from calling function to the called function comes under this category.
Following program illustrates this concept.
/* Program – lohit4.c */
#includemain()
{
int a, b, c;
printf("\nEnter any two integers for addition: ");
scanf("%d %d", &a, &b);
c = sum(a, b) ;
printf("The addition of two numbers : %d", c);
printf("\nEnter any two integers for multiplication: ");
scanf("%d %d", &a, &b);
c = multiply(a, b);
printf("The multiplication of two numbers : %d",c);
}
sum(int x, int y)
{
int z;
z = x+y;
return z;
}
multiply(int x, int y)
{
int z;
z = x*y;
return z;
}
The output of this program is as….
Enter any two integers for addition:10 20
The addition of two numbers : 30
Enter any two integer for multiplication: 15 30
The multiplication of two numbers : 450
In this we have called two functions sum() and multiply() using two call statements:
c = sum(a,b) ; andc = multiply(a,b) ;
After the execution of both these functions, they return an integer value which is stored in variable ‘c’ in main function.
Now look at the following program.
/* Program – lohit5.c */
#includemain()
{
int a, b, c;
float x, y, z;
printf(“\nEnter any two integers for addition: ”);
scanf(“%d %d”,&a, &b);
c = addint(a, b);
printf(“The addition of two integers : %d”, c);
printf(“\nEnter any two real numbers for addition: ”);
scanf(“%f %f”, &x, &y);
z = addfloat(x, y);
printf(“The addition of two real numbers : %d”, z);
}
addint(int aa, int bb)
{
int cc;
cc = aa+bb;
return cc;
}
addfloat(float xx, float yy)
{
int zz;
zz = xx+yy;
return zz;
}
In this program we call two functions addint() and addfloat() which receives two integer values and real values respectively and returns the result of addition of these two variables.
The output of this program is as….
Enter any two integers for addition: 10 20
The addition of two integers : 30
Enter any two real numbers for addition: 15.0 35.0
The addition of two real numbers : 50.0
This is perfectly right. But what will happen if you pass 15.3 and 35.1 to addfloat() function. In this case, you will expect the following output:
Enter any two integers for addition: 10 20
The addition of two integers : 30
Enter any two real numbers for addition: 15.3 35.1
The addition of two real numbers : 50.4
But when you run your program with these real values, you will get following output:
Enter any two integers for addition: 10 20
The addition of two integers : 30
Enter any two real numbers for addition: 15.3 35.1
The addition of two real numbers : 50.0
It happened so because the formal parameter xx and yy receives values 15.3 and 35.1 respectively. And when these values are added we get 50.4. Till now nothing is wrong. But the problem comes in return statement. Here in function definition we are not including any data type before the function name addfloat() and by default any return statement returns an integer value. Thus 50.4 is converted into integer value 50 and returned back and stored in variable z. Since z is a float variable, therefore the integer value 50 is converted into 50.0. That’s why we get 50.0 as output of addition of two real numbers. To overcome this limitation we can use function declaration or function prototype. Which we use in next article.
Creating, Compiling, Linking and Executing C++ Programs
Let see how to invoke Turbo C++, how to name our programs, how to compile our programs, how to link our programs and how to execute our programs.
Invoking Turbo C++
To start Turbo C++, firstly we move to the directory in which we have installed our Turbo C++ software and then we will type TC at the DOS command prompt. If we have installed Turbo C++ in the root directory C:\> then we type TC as:
C:\>TC
As we type this and press Enter key we get the Turbo C++ IDE (Integrated Development Environment) screen that consists of a menu bar that contains menu options, such as File, Edit, Search, Run,
Figure1
Compile, and so on. It will mostly be blank, with the menu bar at the top and the status line on the bottom. The Turbo C++ includes all the facilities to develop and execute programs, such as editor, compiler, debugger, linker, and so on. The first character of each menu option is highlighted. You can select any menu option by pressing the ALT tab key and the highlighted character of the respective menu option. For example, if you want to select Edit menu option then you will press the TAB key and key containing the E character simultaneously as
ALT + E.
Naming Our Source Program
Now we are ready to work under Turbo C++ IDE . After invoking the Turbo C++ we select NEW option from the File menu. An edit window will appear with the filename NONAME00.CPP. Since it is the name specified by the Turbo C++ IDE, therefore you need to change this. For this we select the Save As option from the File menu. As we do this a dialog box will appear that asks for the name of our source program, for example CHAP0101.CPP, as shown in figure-****. After this the new name, that is CHAP0101.CPP, will appear at the top of the Edit window because we have changed the file name from the NONAME00.CPP to CHAP0101.CPP. Now the cursor is placed in the upper-left corner of the Edit window. Now we can type our source program, chap0101.cpp as shown in figure-2 as written in the earlier section, using arrow keys, tab key and Enter key to move the cursor.
Figure 2
Once we complete our typing we should save it to the disk by selecting Save from the File menu, or by pressing the F2. It is a good habit to this before compiling and executing our program.
Figure 3
Compiling The Source Program
The program that we type into the Edit window constitutes the source file, having .CPP extension. It is an ASCII file, you can not execute it directly. Therefore firstly it should be compiled into an object file. To compile the source file, we select Compile from Compile menu and will press Enter key. If there is no syntax error in the source program then the resulting window shows- Warning: 0, Errors: 0 and finally Success : Press any key. This compilation process creates an object file, which has an extension OBJ. However if there is any error then the compiler displays the appropriate error messages, called diagnostic messages, that tells the cause of the error and the compilation process terminates. Therefore go back to the source program, correct it and compile it again. You can also compile the source program by pressing the ALT and F9 keys simultaneously.
Figure-3 shows various stages of compilation of a C++ program.
Figure 4
Linking The Program
Once the source program has been converted into an object file, it is still not in the form that you can run. The reason behind this is that there may be some references to standard library functions or user-defined functions in other object files, which are compiled separately. Therefore these object files are to be linked together along with standard library functions that are contained in library files. To link our object file, select Link from the Compile menu. After this the .OBJ file will be compiled with the one or more library files. The result of this linking process produces an executable file with .EXE extension. Figure-4 depicts this linking process.
This chap0101.cpp program is a standalone executable program, which you can directly execute at command prompt as:
C:\TC> CHAP0101
This will execute the program and the results will get displayed on the screen.
Figure 5
Executing (Running) The Program
To execute (run) the .EXE file, select Run from RUN menu and press Enter key. Th result will be displayed on the screen and controls returns back to the editing screen. However you can also execute the .EXE file by pressing CTRL and F9 keys simultaneously. To see result select User Screen from WINDOW menu or by pressing ALT and F5 keys simultaneously.
More Articles …
Page 12 of 21