Professional Documents
Culture Documents
Lab Pointers, Function, String
Lab Pointers, Function, String
• In call by value method, the value of the actual parameters is copied into the
formal parameters. In other words, we can say that the value of the variable
is used in the function call in the call by value method.
• In call by value method, we can not modify the value of the actual
parameter by the formal parameter.
• In call by value, different memory is allocated for actual and formal
parameters since the value of the actual parameter is copied into the formal
parameter.
• The actual parameter is the argument which is used in the function call
whereas formal parameter is the argument which is used in the function
definition.
Example 1
Update the input value using function(call by value)
#include<stdio.h>
void change(int num) {
printf("Before adding value inside function num=%d \n",num);
num=num+100;
printf("After adding value inside function num=%d \n", num);
}
int main() {
int x=100;
printf("Before function call x=%d \n", x);
change(x);//passing value in function
printf("After function call x=%d \n", x);
return 0;
}
Output
• Before function call x=100
• Before adding value inside function num=100
• After adding value inside function num=200
• After function call x=100
Call by reference in C
#include<stdio.h>
void change(int *num) {
printf("Before adding value inside function num=%d \n",*num);
(*num) += 100;
printf("After adding value inside function num=%d \n", *num);
}
int main() {
int x=100;
printf("Before function call x=%d \n", x);
change(&x);//passing reference in function
printf("After function call x=%d \n", x);
return 0;
}
Output
• Before function call x=100
• Before adding value inside function num=100
• After adding value inside function num=200
• After function call x=200
Pass arrays to a function in C
#include <stdio.h>
void display(int age1, int age2) {
printf("%d\n", age1);
printf("%d\n", age2);
}
int main() {
int ageArray[] = {2, 8, 4, 12};
// pass second and third elements to display()
display(ageArray[1], ageArray[2]);
return 0;
}
Output
•8
•4
Example- Program to calculate the sum of array elements by passing to a function
#include <stdio.h>
float calculateSum(float num[]);
int main() {
float result, num[] = {23.4, 55, 22.6, 3, 40.5, 18};
// num array is passed to calculateSum()
result = calculateSum(num);
printf("Result = %.2f", result);
Click to add text
return 0;
}
float calculateSum(float num[]) {
float sum = 0.0;
for (int i = 0 ; i < 6; ++i) {
sum += num[i];
}
return sum;
}
• Output
• Result = 162.50
• To pass an entire array to a function, only the name of the array is passed as an argument.
• result = calculateSum(num);
• However, notice the use of [] in the function definition.
Example
#include <stdio.h>
int* returnp(int []);
int main() {
int a[]={1,2,3,4,5};
int *p;
p=returnp(a);
printf("%d", *p);
return 0;
}
int* returnp(int a[])
{
a=a+1;
return a;
}