Functions, Arrays and Structure in C++ Programming Language.


       Functions, Arrays and Structure


  To review students with function declaration, definition, prototypes, function call, value passing as call by value and call by reference, arrays, arrays declaration, accessing array elements, structure declaration, usage and array of structure. 


Turbo C++ IDE  

array and structure


 Writing a C++ Program which will perform the following tasks
       State a function which receives a float and an int from main(), finds the product of these two and returns the product which is printed through main().
       Enter 10 elements to an array using for loop and finally display it to the user
       Retrieving or accessing values from array of structure


 is block of statements and is call for specific task to be performed in a program. Through function we can divide whole program in a module and thus it will be very easy to deal with modules or small pieces of programs. Any C++ program contains at least one function, that is main() function. There is no limit on number of functions that might be present in a C++ program. Each function in a program is called in the sequence specified by the function calls in main(). After performing task by each function, control returns to the main(). Function cannot be define inside another function

Every function in C++ programming language should be declared before they are used. These type of declaration are also called function prototype. Function prototype gives compiler information about function name, type of arguments to be passed and return type. The syntax of function prototype is as follow:
Return-type <function-name> (type(1) argument(1),....,type(n) argument(n)); For example:
      int add(int a, int b);
In the above example, int add(int a, int b); is a function prototype which provides following information to the compiler: 
       return type of the function is int. 
       name of the function is add() 
       two arguments of type int are passed to function. 

Function prototype is not needed if user-definition function is written before main() function.
For function to perform specific task, it must be called or invoked which is called as function call. The function can be called or invoked using following syntax:

function-name (argument(1),….argument(n));

When function is invoked using above syntax, control of program jump from that statement to function definition and execute the code inside that function.

Function definition contains programming codes to perform specific task. The syntax of function definition can be as follows:

return-type function-name
                          Block of statements;

Call by value is used when called function does not need to modify the value of the caller’s original variable. In this case a copy of the variable is passed to the function and when the function changes its values then it has no effect on the value of the variable in the main function as shown below:

void main()
     int i = 10, b = 20;

     swapv(a,b);    // Function call

     cout<<"\n a = "<<a<<" b = "<<b;


   swapv(int x, int y)     // Function Definition
    {       int t;

      t = x;       x = y;
      y = t;

      cout<<"\n x = "<<x<<" y = "<<y;

Output of variables a and b won’t change and will printed as a = 10 and b = 20.

Call by reference means that compiler will not create a local copy of the variable which you are referencing to. It will get access to the memory where the variable saved. When you are doing any operations with a referenced variable you can change the value of the variable. Address is passed by using symbol “&” and is received by using asterisk symbol “*” shown as:
void main()    {
     int i = 10, b = 20;      clrscr();

     cout<<"\n a = "<<a<<" b = "<<b;

   swapr(int *x, int *y)
    {       int t;
       t = *x;       *x = *y;
      *y = t;

      cout<<"\n x = "<<x<<" y = "<<y;     }

Output of variables and changes because it was passed by reference. 

Array is a data structure in C++, which stores a fixed size sequential collection of elements of the same type. An array is used to store a collection of data. It is often useful to think of an array as a collection of variables of the same type. Instead of declaring individual variables, such as number0, number1, ..., and number99, you declare one array variable such as numbers and use numbers[0], numbers[1], and ..., numbers[99] to represent individual variables. A specific element in an array is accessed by an index. All arrays consist of contiguous memory locations. The lowest address corresponds to the first element and the highest address to the last element.

Declaring an array in C++, the programmer specifies the type of the elements and the number of elements required by an array as follows: 
type array-Name [ array-Size ];

This is called a single-dimension array. The array-Size must be an integer constant greater than zero and type can be any valid C++ data type. For example, to declare a 4-element array called age of type int, use following statement: 
int num[4];

Array initialization is just like a variable. To initialize an array, we provide initializing values which are enclosed within curly braces in the declaration and placed following an equals sign after the array name. Following is an example of initializing an integer array at time of declaration. 
 int num[4]={23,34,65,74};

Array can be initialized using for loop rather than at time of declaration. Following is an example of initializing an array using for-loop. 

int arr[10]; 
           int i = 0; 
          for(i = 0; i < sizeof(arr); i++) 
   arr[i] = i;   // initializing an array }

To access an array elements, loop can be used to print all or individual elements of an array such as:

for(i = 0; i < sizeof(arr); i++) 
   printf(“%d”,arr[i]);   // initializing an array

Selection sort in C++ arrange numbers of an array in ascending order. The idea of selection sort is very simple: we repeatedly find the next largest element in the array and move it to its final position in the sorted array. Assume that you wish to sort the array in increasing order, i.e. the smallest element at the beginning of the array and the largest element at the end. We begin by selecting the largest element and moving it to the highest index position. We can do this by swapping the element at the highest index and the largest element. We then reduce the effective size of the array by one element and repeat the process on the smaller (sub) array. The process stops when the effective size of the array becomes 1 (an array of 1 element is already sorted).

Structure is a collection of one or more variable types. As we know, the elements in an array must be the same data type, and you must refer to the entire array by its name. Each element (called a member) in a structure can be a different data type. Structures have ability to group data of different data types together but work with that data as a whole. Suppose a company has inventory system so item name will be character array, quantity in stock will be integer and retail price will be in double, so to deal with such system we will use structure.  
To define a structure, we must use the struct statement. Structdefines for your program a new data type with more than one member. The format of the struct statement is
   Member definition;
   Member definition;
   Member definition;
} [one or more structure variables]

Each member definition is a normal variable definition, such as int i; or float sales[20]; or any other valid variable definition, including structure pointers if the structure requires a pointer as a member. At the end of the structure’s definition and before the final semicolon, you can specify one or more structure variables. Here is how you declare the CD structure:
struct cd_collection
{     char                 title [ 25 ];     char                 artist [ 20 ];     int                     num_songs;
    float                 price;
    char                 date_bought [ 8 ];
} cd_collection cd1, cd2, cd3;

There are five members in above structure: two character arrays, an integer, a floating-point value and a character array. The member names are title, artist, num_songs, price and date_bought. To access member of structure use the following syntax as:
cd1.price, cd2.price etc
Initialization of structure’s member can also be possible when you declare a structure such as:
struct cd_collection
{     char                 title [ 25 ];     char                 artist [ 20 ];     int                     num_songs;
    float                 price;
    char                 date_bought [ 8 ];
} cd_collection cd1 = 
                                            “Red Moon Men”,
                                            “Sam and the sneeds”,

To store data of 100 books one must require to use 100 different structure variables from book1 to book100, which is not very convenient. A better approach would be to use an array of structure.  
Arrays of structures are good for storing of complete set of data that fits within the structure format. Arrays of Structures store together several values of different types, grouped as structures. Arrays of structures also provide a means of holding data you read from the disk.
Declaring an Array of Structures is easy as you specify the number of reserved structures inside array brackets when you declare the structure variable. For example, the following structure declaration creates 1000 store structures, each containing three members.
struct stores
{     int                     employees;     int                     registers;     float                 price;
} stores store [ 1000 ];

Arrays of structures can be initialized and access using for loop and is a bit different from simple arrays.
In the following code, arrays of structures are initialized and then access too as shown
struct stores
{     int                     employees;     int                     registers;
    float                 price;
} stores store [ 100];
 int i ;
for ( i = 0 ; i <= 99 ; i++ )
printf ( "\n Enter employees, registers and price " ) ;
scanf ( "%d %d %f", &b[i].employees, &b[i].registers, &b[i].price ) ;
for ( i = 0 ; i <= 99 ; i++ )
printf ( "\n %d %d %f", b[i].employees, b[i].registers, b[i].price ) ;

Step 1: Create New C++ Program File and save it as lab4.cpp
Step 2: Write the following code as shown in figures below

product of float and int program

Figure 17 (a): Product of float and integer using function

product of float and int program

Figure 18 (b): Product of float and integer using function
Step 3: Save file again, compile and run it for required output as shown in figure below
product of float and int program output

Figure 18 (c): Product of float and integer using function

Step 4: Override lab4.cpp with the code shown in figure below.
enter and display value program

Figure 19 (a): Entering & displaying values to an integer array
Step 5: Save file again, compile and run it for required output as shown in figure below
enter and display value program output

Figure 19 (b): Entering & displaying values to an integer array         

Post a Comment