[go: up one dir, main page]

0% found this document useful (0 votes)
6 views81 pages

CP - Unit-3

Uploaded by

Shyam Kothapalli
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
6 views81 pages

CP - Unit-3

Uploaded by

Shyam Kothapalli
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 81

UNIT-3

UNIT – III
Functions-
 Introduction to Structured Programming
 Functions- basics, user defined functions
 Inter function communication (call by value, call by
reference)
 Standard functions
 Storage classes-auto, register, static, extern, scope rules
 Arrays to functions
 Recursive functions
 Example C programs.
Functions: Structured Programming
 The planning for large programs consists of first understanding the problem as a
whole, second breaking it into simpler, understandable parts.
 We call each of these parts of a program a module and the process of subdividing a
problem into manageable parts top-down design.
 Top-down design is usually done using a visual representation of the modules known
as a structure chart.
Functions
 Program segment that carries out some specific, well-defined task
Example
 A function to add two numbers
 A function to find the largest of n numbers
 A function will carry out its intended task whenever it is called or invoked.
 Can be called multiple times.
 Every C program has at least one function, which is main().
 Advantages of functions:
1. Write your code as collections of small functions to make your program modular
2. Structured programming
3. Code easier to debug
4. Easier modification
5. Reusable in other programs
C functions aspects Syntax

Return_type function_name (arguments list)


function definition {
Body of function;
}
function call function_name (arguments list);

function declaration return_type function_name (argument list);


There are two types of functions in C.

1. Standard Library Functions: Inbuilt functions in C


2. User-defined Functions: Created by users
Standard Library Functions

 C Standard library functions or simply C Library functions are inbuilt functions in C


programming.
 The prototype and data definitions of these functions are present in their respective
header files.
 To use these functions we need to include the header file in our program.
For example,
 If you want to use the printf() function, the header file <stdio.h> should be included.
Advantages:
 The functions are optimized for performance
 It saves considerable development time
 The functions are portable
User-Defined Functions
 If the functionality of a function is defined by the user those functions are called
user-defined functions.
 To use a user-defined function, we first have to understand the different parts of its
syntax.
 The user-defined function in C can be divided into three parts:
 Function Prototype
 Function Definition
 Function Call
Examining printMessage

#include <stdio.h>

void printMessage ( void ) ; function prototype

int main ( void )


{
printMessage ( ) ; function call
return 0 ;
}

void printMessage ( void ) function header


{
printf (“A message for you:\n\n”) ; function
printf (“Have a nice day!\n”) ; body
}

function definition
Declaring User-defined functions

Syntax

Example
Definition of User-defined functions
Syntax

Example
Calling User-defined functions

Syntax

Example
Working of Functions
inter function communication
(call by value
call by reference)

* Will be discussed during pointer


Parameters & Return Value
 Parameters are the data values which are passed from calling
function to called function.
 Return value is the data value which passed from called
function to calling function.
 For a function we can have any number of parameters
 For a function we can have only one return value
 In a function the total number of parameters and the order of
the parameters must be same in all function prototype,
function calling and function definition
Parameters & Return Value
To return a value from called function to calling function
we use ‘return’ statement
Parameter types

In C programming language there are two types of


parameters
 These are the parameters used at the time of function
calling.

 Whenever we pass actual parameters copy of its value is


sent to the called function but not entire variable.
 These are the parameters used at called function as receivers
of the actual parameters.

 The order of the actual parameters and their datatypes


should exactly match with the order and datatypes of the
formal parameters
Function types
Based on the parameters and return value, functions are
classified into FOUR types
Without Parameters and without Return value

In this type, there is no data transfer between calling and


called functions

Simple control transfer from calling function to called


function, executes called function body and comes back to
the calling function.

Everything is performed within the called function like


reading data, processing data and displaying result.

This type of functions are used to print some message,


line….
Example Program:
void main()
{
void add();
printf(“We are in main….\n”);
add();
printf(“We are again in main….\n”);
}
void add()
{
int a,b,c;
printf(Enter any two numbers: );
scanf(“%d%d”, &a, &b);
c = a + b;
printf(“Result = %d”, c);
}
void main( )
{
void add( ); No input
printf(“We are in main….\n”);
add( );
printf(“We are again in main….\n”); Control
}

void add( )
Control {
int a,b,c;
printf(Enter any two numbers: );
scanf(“%d%d”, &a, &b);
No return value c = a + b;
printf(“Result = %d”, c);
}
With Parameters and without Return value

In this type, there is data transfer from calling to called


function, but not from called to calling function.

Simple control transfer from calling function to called


function along with some data (parameters), executes called
function body and comes back to the calling function
without any data.

This type of functions are depend on the calling function.


Generated result is utilized by called function and nothing
will be sent back to the calling function.
Example Program:
void main()
{
void add( int, int );
printf(“We are in main….\n”);
add( 10, 20);
printf(“We are again in main….\n”);
}
void add(int a, int b)
{
int c;
c = a + b;
printf(“Result = %d”, c);
}
void main( )
{
void add( int, int ); 10 & 20 as input
printf(“We are in main….\n”);
add( 10, 20 );
printf(“We are again in main….\n”); Control
}

void add( int a, int b)


Control {
int c;
c = a + b;
No return value printf(“Result = %d”, c);
}
Without Parameters and with Return value

In this type, there is no data transfer from calling to called


function, but from called to calling function one data is sent.

Simple control transfer from calling function to called


function, executes called function body and a data value is
sent back to the calling function from called function.

This type of functions are called function is independent. It


reads data, process data and result is sent back to the calling
function.
Example Program:
void main()
{
int c;
int add( );
printf(“We are in main….\n”);
c = add( );
printf(“Result = %d\n”, c);
}
int add( )
{
int a, b;
printf(“Enter any two numbers:”);
scanf(“%d%d”, &a, &b);
return (a + b);
}
void main( )
{
int c;
int add( ); No input
printf(“We are in main….\n”);
c = add( );
printf(“Result = %d\n”, c); Control
}

void add( )
{
Control int a,b;
printf(Enter any two numbers: );
30 as return value scanf(“%d%d”, &a, &b);
return (a + b);
}

input values for a & b are 10 & 20 respectively


With Parameters and with Return value

In this type, there is data transfer from calling to called


function, and from called to calling function one data is sent
back.

Control transfer from calling function to called function


along with data, executes called function body and a data
value is sent back to the calling function from called
function.

In this type of functions are called & calling functions both


dependent on each other.
Example Program:

void main()
{
int c;
int add( int, int );
printf(“We are in main….\n”);
c = add( 10, 20 );
printf(“Result = %d\n”, c);
}
int add( int a, int b)
{
return (a + b);
}
void main( )
{
int c;
int add( int, int );
printf(“We are in main….\n”); 10 & 20 as input
c = add( 10, 20 );
printf(“Result = %d\n”, c);
} Control

Control
void add( int a, int b)
{
30 as return value return (a + b);
}
Storage classes
- Auto
- Register
- Static
- Extern
Why Storage Classes?
• Where the variable would be stored?
– Memory or CPU Registers
• What will be the initial value of the variable?
– i.e., default value (Starting value)
• What is the scope of the variable?
– For which function the value of the variable would be
available
• What is the life time of a variable?
– How long would be variable exists
 Storage classes are used to define things like storage location (whether RAM or
REGISTER), scope, lifetime and the default value of a variable.

 There are FOUR storage classes.


1. auto storage class
2. extern storage class
3. static storage class
4. register storage class
auto storage class
•This class enables the user to declare variables without having to
specify their type at run time.
•It also provides a way for c-programmers to declare variables of a
specific type, such as int, double, and char.
•It allows the computer's compiler to automatically assign storage
space from a given pool that is available.
•By facilitating quicker memory access & logical data organization
and boosting program clarity and effectiveness,
•Automatic Storage Class increases code efficiency.
Why Storage Classes?
• Where the variable would be stored?
– Memory or CPU Registers
• What will be the initial value of the variable?
– i.e., default value (Starting value)
• What is the scope of the variable?
– For which function the value of the variable would be
available
• What is the life time of a variable?
– How long would be variable exists
Types Storage Classes
• There are FOUR types of storage classes
– Automatic Storage class (auto)
– Register Storage class (register)
– Static Storage class (static)
– External Storage class (extern)
Automatic Storage Class

Storage Memory

Default value Garbage value


Local to the block in which the
Scope variable is defined

Till the control remains within the


Life time block in which variable is defined
Example 1
#include<stdio.h>
int main(){
int i;
auto char c;
float f;
printf("%d %c %f",i,c,f);
return 0;
}

Output: Garbage Garbage Garbage


Example 2
#include<stdio.h>
int main(){
int a=10;
{
int a=20;
printf("%d",a);
}
printf(" %d",a);
return 0;
}

Output: 20 10
Example 3
#include<stdio.h>
int main(){
{
int a=20;
printf("%d",a);
}
printf(" %d",a); //a is not visible here
return 0;
}

Output: Compilation error


Example 4
#include<stdio.h>
int main(){
int i;
for(i=0;i<4;i++){
int a=20;
printf("%d",a);
a++;
}
return 0;
}

Output: 20 20 20 20
Register Storage Class
Storage Register

Default value Garbage value


Local to the block in which the
Scope variable is defined

Till the control remains within the


Life time block in which variable is defined
Example 1
#include<stdio.h>
int main(){
register int a=10;
int *p;
p=&a;
printf("%u",p);
}

Output: Compilation error


Example 2
#include<stdio.h>
int main(){
register int a,b;
scanf("%d%d",&a,&b);
printf("%d %d",a,b);
}

Output: Compilation error


Static Storage Class
Storage Memory

Default value Zero


Local to the block in which the
Scope variable is defined
The value of the persists between
Life time different function calls (i.e.,
Initialization is done only once)
Example 1
#include<stdio.h>
int a;
int main(){
printf("%d",a);
return 0;
}

Output: 0
Example 2
#include<stdio.h>
static int a;
int main(){
printf("%d",a);
return 0;
}

Output: 0
Example 3
#include <stdio.h>
static char c;
static int i;
static float f;
int main(){
printf("%d %d %f",c,i,f);
return 0;
}

Output: 0 0 0.000000
Example 4
#include <stdio.h>
static int i=10;
int main(){
i=25; //Assignment statement
printf("%d",i);
return 0;
}

Output: 25
Example 5
#include<stdio.h>
int main(){
{
static int a=5;
printf("%d",a);
}
//printf("%d",a); variable a is not visible here.
return 0;
}

Output: 5
External Storage Class
Storage Memory

Default value Zero


Global
Scope (i.e., Throughout the program )

As long as the program’s execution


Life time does not comes to end
Example 1
#include <stdio.h>
int i; //By default it is extern variable
int main(){
printf("%d",i);
return 0;
}

Output: 0
Example 2
#include <stdio.h>
extern int i; //extern variable
int main(){
printf("%d",i);
return 0;
}

Output: Compilation error, undefined symbol i.


Example 3
#include <stdio.h>
void sum(int,int) //By default it is extern.
int main(){
int a=5,b=10;
sum(a,b);
return 0;
}
void sum(int a,int b){
printf("%d”",a+b);
}

Output: 15
Example 4
#include <stdio.h>
extern int i=10; //extern variable
int main(){
printf("%d",i);
return 0;
}

Output: 10
Example 5
#include <stdio.h>
int main(){
extern int i=10; //Try to initialize extern variable
locally.
printf("%d",i);
return 0;
}

Output: Compilation error: Cannot initialize extern variable.


Recursive functions
 A function that calls itself is known as a
recursive function, and, this technique is known
as recursion.
RECURSION ITERATIONS
Recursive function – is a function that is Iterative Instructions –are loop based
partially defined by itself repetitions of a process
Recursion Uses selection structure Iteration uses repetition structure

Infinite recursion occurs if the recursion An infinite loop occurs with iteration
step does not reduce the problem in a
manner that converges on some if the loop-condition test never
condition.(base case) becomes false
Recursion terminates when a base case Iteration terminates when the
is recognized loop-condition fails
Recursion is usually slower then iteration Iteration does not use stack so it's
due to overhead of maintaining stack
faster than recursion
Recursion uses more memory than Iteration consume less memory
iteration
Infinite recursion can crash the system infinite looping uses CPU cycles
repeatedly
Recursion makes code smaller Iteration makes code longer
Example Program:
int factorial( int );
void main( )
{
int fact, n;
printf(“Enter any positive integer: ”);
scanf(“%d”, &n);
fact = factorial( n );
printf(“Factorial of %d is %d”, n, fact);
}
int factorial( int n )
{
int temp;
if( n == o)
return 1;
else
temp = n * factorial( n-1 );
return temp;
}
int factorial( int );
void main( )
{
int fact, n;
printf(“Enter any positive integer: ”);
scanf(“%d”, &n);
fact = factorial( n );
printf(“Factorial of %d is %d”, n, fact);
}

int factorial( int n )


{
int temp;
if( n == o)
return 1;
else
temp = n * factorial( n-1 );
return temp;
}
Arrays to functions
In C programming, you can pass an entire array to functions.

Pass Individual Array Elements


#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;
}
Example 2: Pass Arrays to Functions
// 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);
return 0;
}

float calculateSum(float num[]) {


float sum = 0.0;

for (int i = 0; i < 6; ++i) {


sum += num[i];
}

return sum;
}

You might also like