Lecture_Week_9.1

Download as pdf or txt
Download as pdf or txt
You are on page 1of 41

Functions

Recap

Basics of Function Function Arguments Function Call


What is the need of a Formal Parameters Call by Value
function? Actual Parameters Call by Reference
Example
Content

FUNCTION WITH MACRO & INLINE MID-SEM ANSWERS


ARRAYS FUNCTIONS DISCUSSION
Function basics & Motivations

• Program redundancy can be reduced by creating a grouping of predefined


statements for repeatedly used operations, known as a function.

• This is Temperature conversion code;


• Cluttered repeated code; Error in c3;
Function basics & Motivations Cont..

• // Function to convert Fahrenheit to Celsius

float F2C(float f) {
float c= (f – 32.0) * (5.0 / 9.0);
return c;}
• The impact is even greater when the
operation has multiple statements.

• The main program is much simpler.


Modularize code.

Purpose of
Function: Enhance reusability.

Improve readability and


maintainability
• The general skeleton of a function in C is as follows:
return_type function_name ( parameter list ) {
// body of the function}
Example: int add(int a, int b){
return (a+b);}
▪ A function definition consists of:
Defining a ▪ a function header and
Function ▪ a function body
▪ Function Declaration tells the compiler about a
function's name, return type, and parameters
▪ A function definition provides the actual body
of the function
Function an Example:
Scope of the variables
Function
that finds
max(m,n)
Where is
the
function
defined?
Function Arguments

• A function argument (or parameter) is a value passed to a function when it is


called.
• The function can use these values to perform its task.
• Two types:
• Formal Arguments (declared in the function definition): Formal parameters
behave like local variables inside the function and are created upon entry
into the function and destroyed upon exit.
• Actual Arguments (provided during the function call)
Function Arguments Example
1. Formal Arguments:
Example: int add(int a, int b) {
return a + b;
}

2. Actual Arguments: Arguments are


passed to the function when it is called
Example: int result = add(5, 10); // 5 and
10 are actual arguments
Function Call ➢Two ways to call a function:
with Call by Value
Arguments Call by Reference
➢arguments can be passed to a function
using any o the above way
A copy of the actual argument is passed to the
function.

Modifying the parameter inside the function


does not affect the original argument.
Call by Example:
void changeValue(int x) {
Value x = 20;
}
int main() {
int num = 10;
changeValue(num);
printf("%d", num); // Output: 10
}
#include <stdio.h>
// Function to swap two numbers using call by value
void swapByValue(int a, int b) {
int temp = a;
a = b;
b = temp;
Another printf("Inside swap: a = %d, b = %d\n", a, b);
}
Example of int main() {
Call by int x = 10, y = 20;
printf("Before swap: x = %d, y = %d\n", x, y);
Value swapByValue(x, y); // Call by value
printf("After swap: x = %d, y = %d\n", x, y);
return 0;}
Output: Before swap: x = 10, y = 20
Inside swap: a = 20, b = 10
After swap: x = 10, y = 20
A reference (address) to the actual argument is
passed to the function.

Modifying the parameter inside the function does


affect the original argument.
Example:

Call by void changeValue(int *x) {


*x = 20;
Reference }

int main() {
int num = 10;
changeValue(&num);
printf("%d", num); // Output: 20
}
#include <stdio.h>
// Function to swap two numbers using call by reference
void swapByReference(int *a, int *b) {
int temp = *a;
*a = *b;
*b = temp;
Example of }
printf("Inside swap: a = %d, b = %d\n", *a, *b);

Call by int main() {

Reference
int x = 10, y = 20;
printf("Before swap: x = %d, y = %d\n", x, y);
swapByReference(&x, &y); // Call by reference
printf("After swap: x = %d, y = %d\n", x, y);
return 0;}
Output: Before swap: x = 10, y = 20
Inside swap: a = 20, b = 10
After swap: x = 20, y = 10
Command line argument in C
int main() {
• main() is mostly defined with a return type of int and without parameters. ...
}
• Command-line arguments are the values given after the name of the program in the command-
line.
• To pass command-line arguments, we define main() with two arguments: the first argument is
the number of command-line arguments and the second is a list of command-line
arguments. int main(int argc, char *argv[]) { /* ... */ }
or
int main(int argc, char **argv) { /* ... */ }
• Here,
• argc (ARGument Count) is an integer variable that stores the number of command-line
arguments passed by the user including the name of the program.
• argv (ARGument Vector) is an array of character pointers listing all the arguments.
• If argc is greater than zero, the array elements from argv[0] to argv[argc-1] will contain
pointers to strings.
Command line argument in C
$ ./a.out
int main(int argc, char* argv[])
Program Name Is: ./a.out
{printf("Program name is: %s", argv[0]);
No Extra Command Line Argument
if (argc == 1) Passed Other Than Program Name
printf("\nNo Extra Command Line Argument Passed");
if (argc >= 2) { $ ./a.out First Second Third
printf("\nNumber Of Arguments Passed: %d", argc);
Program Name Is: ./a.out
printf("\n----Following Are CLI Arguments Passed----"); Number Of Arguments Passed: 4
----Following Are CLI Arguments
for (int i = 0; i < argc; i++)
Passed----
printf("\nargv[%d]: %s", i, argv[i]); argv[0]: ./a.out
argv[1]: First
}return 0;} argv[2]: Second
argv[3]: Third
Function
with Two
arguments
Function
with no
return value
Function
with return
value
Functions with
Arrays
Function
with 1-D
array
Passing
Values
between
Functions
Passing
Values
between
Functions
Functions
with 2D
arrays
Functions
with 2D
arrays Cont..
Functions
with 2D
arrays Cont..
Macros and Inline functions
• Macros and Inline Functions:
• Use function if the sequence of steps is long
• If small, use macros or inline function, to eliminate the need for retyping and time
overhead.
• Need #define compiler directive
• Find the area of a triangle (given: base and height)

• Define it once and use it anywhere in the program


printf("\nArea = %f\n", area(4.0, 6.0));
Macros and Inline functions Cont..
• Macros: Defined using #define, used for text substitution
• Syntax: #define SQUARE(x) ((x)*(x))
printf("%d", SQUARE(5)); // Expands to ((5)*(5))
• Advantage: Quick text substitution, fast.
• Disadvantage: No type checking
• Inline Functions: Defined using the inline keyword, used to optimize function
calls by the compiler.
• Syntax: inline int square(int x) { return x * x; }
printf("%d", square(5)); // May be optimized by the compiler
• Advantages: Type safety, debuggable, no side effects.
• Disadvantages: The compiler might ignore the inline suggestion
• Both aim to reduce function call overhead but differ in implementation.
Key difference between Macros & Inline function
Macros -
Examples
Functions –
A Few
Examples
Check An
Armstrong
Number
Function -
Armstrong
Number
// Function to print Fibonacci series
void printFibonacci(int n) {
Fibonacci Series
int first = 0, second = 1, next; The Fibonacci sequence: 0, 1, 1, 2, 3, 5, 8, 13, 21,
printf("Fibonacci Series for %d terms:\n", n); …
for (int i = 0; i < n; i++)
// Main function
{
int main() {
if (i <= 1) {next = i; }
else {
int terms;
next = first + second; // User input for number of terms
first = second; printf("Enter the number of terms in the
Fibonacci series: ");
second = next;}
scanf("%d", &terms);
printf("%d ", next);
} // Print the Fibonacci series
printf("\n"); } } printFibonacci(terms);
return 0;}
Fibonacci Series
– upto k-terms
• write a function that:
compute and print the first k
numbers in the Fibonacci Series
and return the sum of the first k
numbers of the Fibonacci series
Practice Questions
1. Write a function that takes a positive integer as input and displays all the
positive factors of that number
2. Write a function to find and count the sum of only even digits in an integer
3. Write a function to count the number of Vowels, Consonants and symbols and
print the same
4. Write a function to reverse the characters in an array of size k

5. Write a function to check whether a number can be expressed as the sum of two
prime numbers
You may use a separate method to check primality
Upcoming Slides

• Recursion

You might also like