Nothing Special   »   [go: up one dir, main page]

MCT-242L CP1 2022 LM13 33

Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 18

Department of Mechatronics and Control Engineering

University of Engineering and Technology Lahore

LAB 13: PASSING FUNCION ARGUMENTS IN C


MCT-242L: Computer Programming-I Lab (Fall-2022)
Registration No. 2022-MC-33

OBJECTIVE:
This lab builds on the concept of user-defined functions and scope of variables in C Language. At the end of
this lab, you should be able to:

● Describe what is meant by passing function arguments

● Differentiate between passing arguments by value and by reference

● Use both techniques to solve programming problems

APPARATUS:

● Laptop\PC with following tools installed


o Visual Studio Code with C/C++ and Code Runner Extensions
o C/C++ mingw-w64 tools for Windows 10

FUNCTION ARGUMENTS

If a function is to use arguments, it must declare variables that accept the values of the arguments. These
variables are called the formal parameters of the function. Formal parameters behave like other local
variables inside the function and are created upon entry into the function and destroyed upon exit.

While calling a function, there are two ways in which arguments can be passed to a function:

Call Type Description


This method copies the actual value of an argument into the formal parameter of
Passing arguments
the function. In this case, changes made to the parameter inside the function
by value
have no effect on the argument.
This method copies the address of an argument into the formal parameter. Inside
Passing arguments
the function, the address is used to access the actual argument used in the call.
by reference
This means that changes made to the parameter affect the argument.

Passing Arguments by Value

1 | Page Computer Programming-I Lab


Department of Mechatronics and Control Engineering
University of Engineering and Technology Lahore

By default, arguments in C functions are passed by value. When arguments are passed by value, a copy of
argument is passed to the function. Therefore, changes made to the formal parameter by the called function
have no effect on a corresponding parameter. Consider the function swap() definition as follows:

Example 13.1: Passing Arguments by Value


/* Example_13_1.c: Passing Arguments by Value
----------------------------------------------------------------------
This program demonstrates concept of passing arguments by value in C.
----------------------------------------------------------------------
Written by Shujat Ali (engrshujatali@gmail.com) on 23-Oct-2021.
IDE: Visual Studio Code 1.60.0
C Compiler: GCC (Rev. 5, Built by MSYS2 Project) 10.3.0 */

#include <stdio.h>

// Function declaration
void swap(int, int);
int main ()
{
// local variable definition
int a = 100, b = 200;

printf("Before swap, value of a = %d\n", a );


printf("Before swap, value of b = %d\n", b );

swap(a, b); // function call

printf("After swap, value of a = %d\n", a );


printf("After swap, value of b = %d\n", b );

return 0;
}
// Function definition to swap the values
void swap(int x, int y)
{
int temp;
temp = x; // save the value of x
x = y; // put y into x
y = temp; // put temp into y
}

// End of program
Before swap, value of a = 100
Before swap, value of b = 200
Program Output
After swap, value of a = 100
After swap, value of b = 200

2 | Page Computer Programming-I Lab


Department of Mechatronics and Control Engineering
University of Engineering and Technology Lahore

It shows that there are no changes in the values, though they had been changed inside the function.

Passing Arguments by Reference

The passing arguments by reference method of passing arguments to a function copies the address of an
argument into the formal parameter. Inside the function, the address is used to access the actual argument
used in the call. It means the changes made to the parameter affect the passed argument.

When passing arguments by value, the only way to return a value back to the caller is using the return
statement. While this is suitable in many cases, there are few cases where better options are available. One
such cases when writing a program that needs to modify the value of an array (e.g., sorting an array). In this
case, it is more efficient and clearer to have the function modify the actual array passed to it, rather than
trying to get something back to the caller. One way to allow functions to modify the value of the argument is
by using pass by reference.

To pass a value by reference, argument pointers are passed to the functions just like any other value. So
accordingly, you need to declare the function parameters as pointer types as in the following function
swap(), which exchanges the values of the two integer variables pointed to, by their arguments.

Example 13.2: Passing Arguments by Reference


/* Example_13_2.c: Passing Arguments by Reference
-------------------------------------------------------------------------
This program demonstrates concept of passing arguments by reference in C.
-------------------------------------------------------------------------
Written by Shujat Ali (engrshujatali@gmail.com) on 23-Oct-2021.
IDE: Visual Studio Code 1.60.0
C Compiler: GCC (Rev. 5, Built by MSYS2 Project) 10.3.0 */

#include <stdio.h>
// Function declaration
void swap(int *, int *);

int main ()
{
// local variable definition
int a = 100, b = 200;

printf("Before swap, value of a = %d\n", a );


printf("Before swap, value of b = %d\n", b );

swap(&a, &b); // function call

printf("After swap, value of a = %d\n", a );


printf("After swap, value of b = %d\n", b );
int a=10, b=20, temp;
return 0; int *x=&a;
} int *y=&b;
temp = x; // save the value of x
*x = *y; // put y into x
*y = temp;
printf("After swap, value of a = %d\n",
3 | Page *x ); Computer Programming-I Lab
printf("After swap, value of b = %d\n",
Department of Mechatronics and Control Engineering
University of Engineering and Technology Lahore

// Function definition to swap the values


void swap(int *x, int *y)
{ int temp;
temp = *x; // save the value of x
*x = *y; // put y into x
*y = temp; // put temp into y
}

// End of program
Before swap, value of a = 100
Before swap, value of b = 200
Program Output
After swap, value of a = 200
After swap, value of b = 100

The function parameters int *x and int *y are pointers, allowing the function to receive the addresses of
actual variables. By dereferencing the pointers with *x and *y, the function can access and modify the
values at the memory locations pointed to by x and y. This is a form of "call by reference" because the
function can indirectly modify the original values of x and y in the calling code.

● temp is a regular integer variable, not a pointer. It is used to store the value, not the address.

● temp = *x; saves the value pointed to by x in the variable temp. It doesn't store the address of x; it
stores the value that x points to.
● *x = *y; assigns the value pointed to by y to the memory location pointed to by x. It modifies the value
stored at the address pointed to by x.
● *y = temp; assigns the value stored in temp (the original value of *x) to the memory location pointed to
by y. It modifies the value stored at the address pointed to by y.

temp is a regular variable storing values. *x = *y; and *y = temp; are operations that modify the values at
the memory locations pointed to by x and y, respectively. They do not deal with addresses; they deal with
the values stored at those addresses. In summary, the use of pointers in the swap function allows it to modify
the values at the addresses pointed to by x and y, achieving a form of "call by reference" behavior. In
contrast, passing by value would involve working with copies of the values and would not modify the
original variables.

Example 13.3: Referencing & Dereferencing


/* Example_13_3.c: referencing and dereferencing
-------------------------------------------------------------------------
This program demonstrates concept of referencing and dereferencing in C.
-------------------------------------------------------------------------
IDE: Visual Studio Code 1.60.0
C Compiler: GCC (Rev. 5, Built by MSYS2 Project) 10.3.0 */
#include <stdio.h>
int main ()

4 | Page Computer Programming-I Lab


Department of Mechatronics and Control Engineering
University of Engineering and Technology Lahore

{
int x = 42; int *ptr; // pointer variable 'ptr'
ptr = &x; // Referencing: 'ptr' stores the address of 'x'
int y=*ptr; //Dereferencing 'ptr' to get the value: y now holds the value stored at
the memory address pointed to by 'ptr'
printf("Value of x: %d\n", x);
printf("Address of x: %p\n", ptr); // address of x, %p is used to print addresses
printf("Address of x: %p\n", &x); // %p is used to print addresses
printf("Value at the address stored in ptr: %d\n", y); // Dereferencing
printf("Value at the address stored in ptr: %d\n", *ptr);
return 0;
}

}
// End of program
Value of x: 42
Address of x: 000000d3553ffc74
Program Output Address of x: 000000d3553ffc74
Value at the address stored in ptr: 42
Value at the address stored in ptr: 42

&x: This gives you the address of variable x.


ptr: This is a pointer variable that can hold memory addresses.
The line ptr = &x; describes the assignment of the address of x to the pointer. Which is when dereferenced
by *ptr gives the value of the variable whose address was stored at the memory location pointed to by ptr.

Referencing:

Definition: Referencing is the process of obtaining the memory address of a variable.


Operator: The reference operator & is used for referencing.
Example: From example 13.3
int x = 42;
int *ptr = &x; // 'ptr' stores the address of 'x'

Purpose: Obtaining the address of a variable allows you to create pointers that point to that address.

Dereferencing:

Definition: Dereferencing is the process of accessing the value stored at a memory address pointed to by a
pointer.
Operator: The dereference operator * is used for dereferencing.
Example: From example 13.3
int y=*ptr; // 'y' now holds the value stored at the memory address pointed to by
'ptr'

5 | Page Computer Programming-I Lab


Department of Mechatronics and Control Engineering
University of Engineering and Technology Lahore

Purpose: Dereferencing allows you to access and manipulate the value stored at a specific memory location
through a pointer.

Referencing (&x) obtains the address of variable x and stores it in the pointer ptr. Dereferencing (*ptr)
accesses the value stored at the memory address pointed to by ptr. In summary, referencing is about
obtaining memory addresses, and dereferencing is about accessing values stored at those addresses through
pointers.

6 | Page Computer Programming-I Lab


Department of Mechatronics and Control Engineering
University of Engineering and Technology Lahore

When to Use Call by Value and Call by Reference in C?


Copying is expensive, and we have to use our resources wisely. Imagine copying a large object like an array
with over a million elements only to enumerate the values inside the array, doing so will result in a waste of
time and memory. Time is valuable and we can omit to copy when:

1. We intend to read state information about an object, or


2. Allow a function to modify the state of our object.

However, when we do not intend our function to alter the state of our object outside of our function, copying
prevents us from making unintentional mistakes and introduce bugs. Now we know when to use call by
value and call by reference in C.
Now we will discuss the advantages and disadvantages of call by value and call by reference in C.

Advantages of Using Call by Value Method

● Guarantees that changes that alter the behavior of a parameter stay within its scope and do not affect
the value of an object passed into the function
● Reduce the chance of introducing subtle bugs which can be difficult to monitor.

● Passing by value removes the possible side effects of a function which makes your program easier to
maintain and reason with.

Advantages of Using Call by Reference Method

● Calling a function by reference does not incur performance penalties that copying would require.
Likewise, it does not duplicate the memory necessary to access the content of an object that resides
in our program.
● Allows a function to update the value of an object that is passed into it.

● Allows you to pass functions as references through a technique called function pointers which may
alter the behavior of a function. Likewise, lambda expressions may also be passed inside a function.
Both enable function composition which has neat theoretical properties.

Disadvantages of Using Call by Value Method

● Incurs performance penalty when copying large objects.


● Requires reallocating memory with the same size as the object passed into the function.

Disadvantages of Using Call by Reference Method

● For every function that shares with the same object, your responsibility of tracking each change also
expands.

7 | Page Computer Programming-I Lab


Department of Mechatronics and Control Engineering
University of Engineering and Technology Lahore

● Making sure that the object does not die out abruptly is a serious issue about calling a function by
reference. This is especially true in the context of a multithreaded application.

8 | Page Computer Programming-I Lab


Department of Mechatronics and Control Engineering
University of Engineering and Technology Lahore

LAB SUBMISSION:
Create a Visual Studio Code Workspace, Lab_13 and c files (Task_13_1.c to Task_13_7.c) for individual
tasks and add them to Lab_13 workspace.

TASK 13.1: Circular Shift [1 point]


Write a function Circular_Shift() that takes 3 parameters (x, y, z) and
performs circular shift to their values. e.g., if x = 5, y = 8, z = 10
then after one circular shift y = 5, z = 8, x =10. In the main()
function, take three values from user and pass it to the defined
function.
Note: Don’t use any printf() function call inside the defined function.
Enter the value of x >> 15
Enter the value of y >> 10
Enter the value of z >> 20
Sample Output 1
After circular shift, x = 20
After circular shift, y = 15
After circular shift, z = 10

Answer: #include <stdio.h>

void Circular_Shift(int *x, int *y, int *z)


{
int temp = *x;
*x = *z;
*z = *y;
*y = temp;
}

int main()
{
int x, y, z;

printf("Enter the value of x >> ");


scanf("%d", &x);

printf("Enter the value of y >> ");


scanf("%d", &y);

9 | Page Computer Programming-I Lab


Department of Mechatronics and Control Engineering
University of Engineering and Technology Lahore

printf("Enter the value of z >> ");


scanf("%d", &z);

Circular_Shift(&x, &y, &z);

printf("After circular shift, x = %d\n", x);


printf("After circular shift, y = %d\n", y);
printf("After circular shift, z = %d\n", z);

return 0;
}

TASK 13.2: Four Basic Operations [1 point]


Write a function four_operations() that takes 6 parameters (1st two
operands and next four result of addition, subtraction, multiplication,
and division) and returns nothing. Pass arguments by value for first 2
parameters and by reference for next four. In the main() function, take
the values of both operands from user and pass it to the defined
function. User must display the results obtained from the defined
function to screen in main().
Note: Don’t use any printf() function call inside the defined function.
Enter the 1st operand >> 110.5
Enter the 2nd operand >> 23.25

Sample Output 1 The sum of both operands is 133.75


The difference of both operands is 87.25
The product of both operands is 2569.12
The quotient of both operands is 4.75

Answer: #include <stdio.h>

void four_operations(float x, float y, float *addition, float *subtraction, float


*multiplication, float *division)
{
*addition = x + y;
*subtraction = x - y;
*multiplication = x * y;
*division = x / y;
}

10 | Page Computer Programming-I Lab


Department of Mechatronics and Control Engineering
University of Engineering and Technology Lahore

int main()
{
float operand1, operand2, addition, subtraction, multiplication, division;
printf("Enter the 1st number >> ");
scanf("%f", &operand1);
printf("Enter the 2nd number >> ");
scanf("%f", &operand2);

four_operations(operand1, operand2, &addition, &subtraction, &multiplication,


&division);

printf("The addition of both numbers is %.2f\n", addition);


printf("The difference of both numbers is %.2f\n", subtraction);
printf("The product of both numbers is %.2f\n", multiplication);
printf("The quotient of both numbers is %.2f\n", division);

return 0;
}

TASK 13.3: Ascending Order [1 point]


Write a function Ascending_Order() that takes 4 integer parameters,
assign values based on ascending order and returns nothing. In the
main() function, take the values from user and pass it to the defined
function. User must display the results obtained from the defined
function to screen in main().
Note: Don’t use any printf() function call inside the defined function.
Enter n1 >> 55
Enter n2 >> 76
Enter n3 >> 23
Enter n4 >> 38
Sample Output 1
The value of n1 is 23
The value of n2 is 38
The value of n3 is 55
The value of n4 is 76

Answer: #include <stdio.h>


void Ascending_Order(int a, int b, int c, int d, int *x, int *y, int *m, int *o)

{
if (a > b)

11 | Page Computer Programming-I Lab


Department of Mechatronics and Control Engineering
University of Engineering and Technology Lahore

{
int temp = a;
a = b;
b = temp;
}

if (a > c)
{
int temp = a;
a = c;
c = temp;
}

if (a > d)
{
int temp = a;
a = d;
d = temp;
}

if (b > c)
{
int temp = b;
b = c;
c = temp;
}

if (b > d)
{
int temp = b;
b = d;
d = temp;
}

if (c > d)
{
int temp = c;
c = d;
d = temp;
}

12 | Page Computer Programming-I Lab


Department of Mechatronics and Control Engineering
University of Engineering and Technology Lahore

*x = a;
*y = b;
*m = c;
*o = d;
}
int main ()
{
int n1, n2, n3, n4, x, y, m, o;
printf("Enter n1: ");
scanf("%d", &n1);
printf("Enter n2: ");
scanf("%d", &n2);
printf("Enter n3: ");
scanf("%d", &n3);
printf("Enter n4: ");
scanf("%d", &n4);

Ascending_Order(n1, n2, n3, n4, &x, &y, &m, &o); // function call

printf("The value of n1 is %d\n", x);


printf("The value of n2 is %d\n", y);
printf("The value of n3 is %d\n", m);
printf("The value of n4 is %d\n", o);

return 0;

TASK 13.4: Number of Digits [1 point]


Write a function Number_of_Digits() that takes an integer and returns
number of digits in it. In the main() function, take the integer from
user and pass it to the defined function. User must display the number
of digits obtained from the defined function to screen in main().
Enter the number >> 32415
Sample Output 1
Number of digits are 5
Enter the number >> 1529812
Sample Output 2
Number of digits are 7

Answer: #include <stdio.h>

13 | Page Computer Programming-I Lab


Department of Mechatronics and Control Engineering
University of Engineering and Technology Lahore

void Number_of_Digits(int digit, int *value)


{
*value = 0;
do
{
(*value)++;
digit /= 10;
} while (digit != 0);
}

int main()
{
int digit, value;
printf("Enter the number >> ");
scanf("%d", &digit);

Number_of_Digits(digit, &value);

printf("Number of digits are %d\n", value);


return 0;
}

TASK 13.5: Kth Digit [1 point]


Write a function k_Digit() that takes an integer and digit number (k)
and returns kth digit of the given number. In the main() function, take
the integer and digit number from user and pass it to the defined
function. User must display the kth digit obtained from the defined
function to screen in main().
Note: If digit k is greater than the number of digits in given number,
then function must return 0.
Enter the number >> 32415
Sample Output 1 Enter the digit number >> 3
3rd digit of 32415 is 4
Enter the number >> 5298601
Sample Output 2 Enter the digit number >> 5
5th digit of 5298601 is 9

Answer: #include <stdio.h>


#include <math.h>

int k_Digit(int *, int *);

14 | Page Computer Programming-I Lab


Department of Mechatronics and Control Engineering
University of Engineering and Technology Lahore

int main()
{
int number, digit, kth = 0;
printf("Enter the Number >> ");
scanf("%d", &number);

printf("Enter the Digit Number >> ");


scanf("%d", &digit);

kth = k_Digit(&number, &digit);


printf("%d digit of %d is %d", digit, number, kth);
}

int k_Digit(int *mth, int *nth)


{
int a, b, c, x, y, z, i = 0;
int digv = *mth, unit = *nth, valV = *mth;
while (digv != 0)
{
c = i + 1;
digv /= 10;
i++;
}

b = c + 1 - unit;
x = pow(10, b);
a = valV % x;
y = pow(10, b - 1);
z = a / y;
return z;
}

TASK 13.6: Fibonacci Sequence [1 point]


Write a function Fibonacci_sequence() that takes an integer and prints
the Fibonacci Sequence up to that term. In the main() function, take
the integer user and pass it to the defined function.
Note: In a Fibonacci sequence the sum of two successive terms gives the
third term. Following are the first few terms of the Fibonacci
sequence: 1 1 2 3 5 8 13 21 34 55 89...

15 | Page Computer Programming-I Lab


Department of Mechatronics and Control Engineering
University of Engineering and Technology Lahore

Enter the number of terms >> 15


Sample Output 1 1st 15 terms of Fibonacci Sequence are
1 1 2 3 5 8 13 21 34 55 89 144 233 377 610
Enter the number of terms >> 7
Sample Output 2 1st 7 terms of Fibonacci Sequence are
1 1 2 3 5 8 13

Answer: #include<stdio.h>

int main()
{
int n , fb;
printf("Enter the number of terms >> ");
scanf("%d", &n);

Fibonacci_Sequence(n , &fb);
return 0;
}

void Fibonacci_Sequence(int n , int *fb)


{
int term1 = 1, term2 = 1, term3;

printf("1st %d terms of Fibonacci Sequence are \n", n);

for(int i = 1; i <= n; i++)


{
*fb = term1;
printf("%d\t", *fb);

term3 = term1 + term2;

term1 = term2;
term2 = term3;
fb++;
}
printf("\n");
}

TASK 13.7: Perfect Number [1 point]

16 | Page Computer Programming-I Lab


Department of Mechatronics and Control Engineering
University of Engineering and Technology Lahore

Write a function Perfect_Number() that takes an integer and return 1 if


the given number is perfect otherwise returns 0. In the main()
function, take the integer user and pass it to the defined function.
After that check if the number is perfect and display a message on
computer screen.
Note: A perfect number is a positive integer that is equal to the sum
of its positive divisors, excluding the number itself. E.g., 6 has
divisors 1, 2 and 3, and 1 + 2 + 3 = 6, so 6 is a perfect number
Enter the number >> 28
Sample Output 1
The given number is perfect.
Enter the number >> 127
Sample Output 2
The given number is not perfect.

Answer: #include<stdio.h>

void Perfect_Number(int num , int *sqre)


{
int sum = 0;
for (int i = 1; i < num; i++)
{
if(num % i == 0)
sum += i;
}
if (*sqre =(num == sum))
{
printf("The given number is perfect.");
}
else
{
printf("The given number is not perfect.");
}
}

int main()
{
int num , sqre;
printf("Enter the number >> ");

17 | Page Computer Programming-I Lab


Department of Mechatronics and Control Engineering
University of Engineering and Technology Lahore

scanf("%d" , &num);

Perfect_Number(num , &sqre);

return 0;
}

Students are advised to fill the manual and submit it before the upcoming lab. Kindly rename the file as
‘MCT-242L_CP1_2022_LM13_XX’, where XX is your roll number. After completing the manual, turn it in Google Classroom.

18 | Page Computer Programming-I Lab

You might also like