Sunday 27 January 2019

Passing Arrays To Functions

Passing One-dimensional Array to a Function
Example 1: Passing single element of an array to function
#include <stdio.h>
#include<conio.h>
void display(int age)
{
    printf("%d", age);
}

void main()
{
    int ageArray[] = {12, 23, 14};
   clrscr();
    display(ageArray[2]); //Passing array element ageArray[2]
  getch();
}
Output
14
Example 2: Passing an array to a function(taking value from user)
#include <stdio.h>
void display(int marks[20])
{
   
     int  i, n;

     printf("Enter n:\n ");
     scanf("%d", &n);
      
for(i=0; i<n; ++i)       //Input statement
     {
         printf("Enter number%d: ",i+1);
         scanf("%d", &marks[i]);
        }
   
for(int i=0; i<n; ++i)      // Output statement
     {
       printf("Array is:%d\n", marks[i]);
       }
}

void main()
{
int marks[20], i, n;
clrscr();

    display(marks); //Passing array element marks[n]
getch();
}
Example 3: Passing an entire array to a function
#include <stdio.h>
float average(float age[]);

int main()
{
          float avg, age[] = {12.6, 33, 22.6, 8, 20.5, 49};
          avg = average(age); // Only name of an array is passed as an argument
          printf("Average age = %f", avg);
          return 0;
}

float average(float age[])
{
          int i;
          float avg, sum = 0.0;
          for (i = 0; i < 6; ++i) {
                   sum += age[i];
          }
          avg = (sum / 6);
          return avg;
}
Output:
Average age =24.28333

Passing Multi-dimensional Arrays to Function
To pass multidimensional arrays to a function, only the name of the array is passed (similar to one dimensional array).
Example 1: Passing two-dimensional array to a function
#include <stdio.h>
void displayNumbers(int num[2][2]);
int main()
{
    int num[2][2], i, j;
    printf("Enter 4 numbers:\n");
    for (i = 0; i < 2; ++i)
        for (j = 0; j < 2; ++j)
            scanf("%d", &num[i][j]);

    // passing multi-dimensional array to a function
    displayNumbers(num);
    return 0;
}

void displayNumbers(int num[2][2])
{
    int i, j;
    printf("Displaying:\n");
    for (i = 0; i < 2; ++i)
        for (j = 0; j < 2; ++j)
            printf("%d\n", num[i][j]);
}


1 comment:

  1. You don't realize how quickly technology is changing. Data science is highly technical and is therefore in high demand. A career in data science will open up many lucrative job opportunities. So, if you have been wanting to start your career in Data Science, now is the best time to enroll in a data science program with one of the best data science training institute in noida.

    ReplyDelete

apply function in R

1) apply function: It takes 3 arguments matrix,margin and function.. Example: m<-matrix(c(1,2,3,4),nrow=2,ncol=2) m #1 indicates it is ap...