0% found this document useful (0 votes)
4 views

M3 P1.pptx

P1
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
4 views

M3 P1.pptx

P1
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 66

Principles of Programming using

C
22POP13
Module-3
• Functions: Introduction using functions, Function
definition, function declaration, function call, return
statement, passing parameters to functions, scope of
variables, storage classes, recursive functions.
• Arrays: Declaration of arrays, accessing the
elements of an array, storing values in arrays,
Operations on arrays, Passing arrays to functions,
two dimensional arrays, operations on
two-dimensional arrays, two dimensional arrays to
functions, multidimensional arrays, applications of
arrays.
Functions
• Function is a group of statements that perform a
particular task.
• C functions can be of 2 categories:
1)Built in functions.
• It is built in function or library function which is
provided by the C compiler. User is not required to
write it.
• E.g. printf(), scanf()
2)User defined functions It is written by the user.
• C programs can be written in 2 ways:
• Without using user defined functions or
Unstructured programming
• Using user defined functions or Structured
programming or modular programming.
• In unstructured programs entire logic is written
inside one function which is main () function.

• Disadvantages of Unstructured Programming


• Difficult to read and understand.
• Difficult to debug(identify errors).
• Difficult to test the program.
• Difficult to modify the program
• Advantages of user defined functions:
• Programming becomes easier.
• Large and complex tasks can be broken down
into smaller simple tasks using functions.
• Easier debugging: Finding and removing errors
is easier.
• Readability of the program is increased.
Example of unstructured C program to add two
numbers without using user defined functions:

#include<stdio.h>
void main()
{
int a=10,b=20, sum;
sum=a+b;
printf("Sum is %d\n",sum);
}
Output:
Sum is 30
• Example of structured C program
#include<stdio.h>
int add(int a, int b); //function declaration
void main()
{
int a=10,b=20,sum;
sum=add(a,b); //function call
printf("Sum is %d\n",sum);
}
int add(int a, int b) //function definition
{
int sum;
sum=a+b;
return sum; Output:
Sum is 30
}
ELEMENTS OF USER DEFINED FUNCTIONS:
• Function definition
• Function call
• Function declaration
Function definition
• Actual code for the function to perform the
specific task. It contains two parts:
• Function header, consists of return type,
function name, formal parameter list.
• Function body.
return_type function_name(parameter list)
{
local variable declaration;
executable statement1;
executable statement2;


return statement;
}
int add(int a, int b)
{
int sum;
sum=a+b;
return sum;
}
----------------------------------------------------------------
void add(int a, int b)
{
printf(“ sum is %d”,a+b);
}
FUNCTION DEFINITION and FUNCTION
CALL
void main()
{
int a=10,b=20, sum;
sum=add(a,b); //function call
printf(“sum is %d”,sum);
}
int add(int a, int b) //function definition
{
int sum;
sum= a+b;
return sum;
}
/* Program to find product of given two integers */

#include<stdio.h> Function
int mul(int a, int b); // int mul(int, int); Declaration(FUNCTION
void main() PROTOTYPE)

{
int a, b, c;
printf(“Enter two integers\n”);
scanf(“%d%d”,&a,&b);
c=mul(a,b);
printf(“The Product is = %d”,c); Function Call
}
int mul(int a, int b)
{
return(a*b);
}
• Function declaration or function prototype
return_type function_name (parameter list);

int add(int a, int b); /*Function prototype or


Function declaration */
void display(void);
#include<stdio.h>
int add(int a, int b); //function declaration/ function prototype
void main()
{
int a=10,b=20,sum;
sum=add(a,b); //function call
printf("Sum is %d\n",sum);
}
int add(int a, int b) //function definition
{
int sum;
sum=a+b; Output:
Sum is 30
return sum;
}
Write a program to find cube of a number using
function.
#include<stdio.h>
int cube(int num)
int cube(int num); {
void main() int r;
{ r=num*num*num;
int num, result; return r;
printf("Enter number\n"); }
scanf("%d",&num);
result=cube(num); Output:
Enter number
printf("Cube is %d\n", result); 2
} Cube is 8
Write a program using function to check if number is
prime or not. Function should return 1 if the number is
prime, 0 if not prime number.(Jan 2015).

#include<stdio.h> for(i=2; i<=num/2;i++)


int isprime(int num) {
{ if(num%i==0)
int i; {
if(num==0||num==1) return 0;
{ }
return 0; }
} return 1;
}
void main()
{
int num;
printf("Enter a number\n");
scanf("%d",&num);
if(isprime(num))
{
printf("%d is prime\n",num);
}
else
{
printf("%d is not prime\n",num);
}
}
• Write a C program to calculate factorial of a
number using function.
CATEGORIES OF USER DEFINED
FUNCTIONS
BASE ON PARAMETERS AND
RETURN VALUE
There are four categories of user defined function based on parameters and
return value. They are

1. Function with no arguments and no return value


2. Function with arguments and no return value
3. Function with no arguments and return value

4. Function with arguments and return value


1. Function with no arguments and no return value
(Void function without parameters / No communication)
#include<stdio.h>
void add();
void main()
{
add( );
}
void add()
{
int a, b, c;
printf(“Enter two integers\n”);
scanf(“%d%d”,&a,&b);
c=a+b;
printf(“Sum is =%d”,c);
}
2. Function with arguments and no return value
(Void function with parameters/Downward communication)
#include<stdio.h>
void add(int a, int b);
void main()
{
int a,b;
printf(“Enter two integers\n”);
scanf(“%d%d”,&a,&b);
add(a,b);
}
void add(int a, int b)
{
int c;
c=a+b;
printf(“Sum is =%d”,c);
}
3. Function with no arguments and with return value
(Non-void function without parameters/Upward communication)
#include<stdio.h>
int add();
void main()
{
int c;
c=add();
printf(“Sum is =%d”,c);
}
int add()
{
int a,b,c;
printf(“Enter two integers\n”);
scanf(“%d%d”,&a,&b);
c=a+b;
return(c);
4. Function with arguments and with return value
(Non-void function with parameters/Up-down communication)
#include<stdio.h>
int add(int a, int b);
void main()
{
int a, b, c;
printf(“Enter two integers\n”);
scanf(“%d%d”,&a,&b);
c=add(a, b);
printf(“Sum is =%d”,c);
}
int add(int a, int b)
{
int c;
c=a+b;
return(c);
• Parameter Passing Mechanisms or Types of
Parameters Passing
#include<stdio.h>
int add(int a, int b); //function declaration
void main()
{
int a=10,b=20,sum;
sum=add(a,b); //function call
printf("Sum is %d\n",sum);
}
int add(int a, int b) //function definition
{
int sum;
sum=a+b;
return sum;
}
Two types of parameters passing mechanisms
are:
• Pass by value or call by value
• Pass by reference or pass by pointer
Pass by Value or call by value
• In this method value of variables is passed to
the function during function call.
• Here, values of actual parameters are copied
to formal parameters.
• Change in formal parameters will not affect
actual parameters.
#include <stdio.h>
void exchange(int p, int q)
{

int temp;
temp=p;
p=q;
q=temp; Output:
} Values before exchanging are 10 and 20
Values after exchanging are 10 and 20
void main()
{
int a=10,b=20;
printf("Values before exchanging are %d and
%d\n",a,b);
exchange(a,b);
printf("Values after exchanging are %d and %d\n",a,b);
}
Pass by reference or pass by pointer
• In this method address of the variable is passed to the
function during function call.
• If any change is done to formal parameters, then
actual parameters are changed.
• Actual and formal parameters are created in same
memory location.
• Pointers are required.
#include <stdio.h>
void exchange(int *p, int *q)
{
Output:
int temp; Values before exchanging are 10 and 20
temp=*p; Values after exchanging are 20 and 10
*p=*q;
*q=temp;
}
void main()
{
int a=10,b=20;
printf("Values before exchanging are %d and %d\n",a,b);
exchange(&a,&b);
printf("Values after exchanging are %d and %d\n",a,b);
}
POINTER
Pointer is a variable which holds address of another variable.

Pointer Variables

p a
2000 5
3000 2000

Address
Scope of variables

• In C, all constants and variables have a defined


scope, which means the accessibility and
visibility of the variables at different points in
the program.
• A variable or a constant in C has four types of
scope: block, function, program and a file.
Block Scope
• A statement block is a group statements
enclosed within opening and closing curly
braces ({}).
• A block may contain more blocks within it, i.e.,
nested blocks.
• A variable declared within a Block has a Block
Scope. This variable is accessible anywhere
within the block and its inner blocks. Hence,
the scope of such a variable ends where the
block ends.
#include <stdio.h>
void main()
{
int x = 10;
int i=0;
printf ("The value of x outside the loop is: %d\n", x);
While(i<3)
{
int x=i;
printf ("The value of xinside the loop is: %d\n", x);
i++;
}
printf ("The value of x outside the loop is: %d\n", x);
return 0;
}
Function Scope
• A Function scope begins at the opening of the
function and ends with the closing of it.
• Function scope is applicable to goto labels
only.
• A label declared is used as a target to go to the
statement and both goto and label statement
must be in the same function.
#include <stdio.h>
void main()
{
{
goto label_exec;

label_exec: printf("hello world\n");


}

goto label_exec;

}
Program Scope

• Global variables declared outside the function


bodies have a program scope.
• They can be accessed from any point in the
program after its declaration.
#include <stdio.h>
int x = 10; /* global variable */
void print () ;
void main ()
{
printf (" \n The value of x in main () = %d",x );
int x=2;
printf (" \n The value of local variable x in main () = %d",x );

print();
}
void print()
{
printf (" \n The value of x in function %d", x);
}
File Scope
• When a global variable is accessible until the end
of the file, the variable is said to have file scope.
• To allow a variable to have file scope, declare that
variable with the static keyword before specifying
its data type, as shown:
static int x = 10;
• A global static variable can be used anywhere
from the file in which it is declared but it is not
accessible by any other files.
file2.c file1.c
#include<stdio.h> void fun()
#include "file1.c" {
int a=5; -------------
void main() a=a+3;
{ -------------
printf(“%d\t”,a); }
fun();
printf(“%d\t”,a);
}
file2.c file1.c
#include<stdio.h> void fun()
#include "file1.c" {
static int a=5; -------------
void main() a=a+3;
{ -------------
printf(“%d\t”,a); }
fun();
printf(“%d\t”,a);
}
Storage class
• Storage class specifiers define the scope
(visibility) and lifetime of variables declared
within a C program.
• The scope of the variable indicates the part of
the C program in which the variable name is
visible or accessible.
• Lifetime of variables indicates how long the
storage allocation will continue to exist for
that variable.
• C supports the following storage classes :
• Auto
• Register
• External
• Static
auto Storage Class(Automatic variables)

• Syntax:
auto datatype variable;
• These variables are declared inside a function
and used only inside that function.
• They are created when function is called and
destroyed automatically when the function is
exited. Hence name automatic.
• By default automatic variables are initialized
to garbage (Junk) value.
#include<stdio.h>
void f2()
{ void main()
auto int a=10; {
printf("%d\t",a); auto int a=1000;
} f1();
void f1() printf("%d",a);
{ }
auto int a=100;
f2(); OUTPUT
printf("%d\t",a); 10 100 1000
}
register Storage Class (register variables)
Syntax:
register datatype variable;
• When a variable is declared using register storage
class, it is stored in a CPU register instead of RAM.
• These are accessed faster than memory.
• Frequently used variables (looping variables) will
be kept in register.
• These variables do not have address to access and
hence they cannot be operated using & operator.
register Storage Class
#include <stdio.h>
void main ()
{
int n;
register int i, sum;
printf (" enter the value for n");
scanf("%d",&n);
for(i=0;i<n;i++)
{
sum=sum+i;
}
}
extern Storage Class(External variables)

Syntax: extern datatype variable;


• They are also known as global variable.
• The extern declaration are used to
void fun()
specify that the variable is declared
elsewhere in the program. {
• The extern declaration does not allocate extern int a;
storage space for variables. a=a+3;
• Extern variables are always initialized }
globally (Only once).
file2.c file1.c
#include<stdio.h> //extern int a;
#include "file1.c" void fun()
int a=5; {
void main() extern int a;
{ a=a+3;
printf(“%d\t”,a); }
fun();
printf(“%d\t”,a);
f();
}

Output: 5 8
#include<stdio.h>
int x;
void f()
{
extern int x;
x=x+5;
printf(“%d\t”,x);
} Output:
void main() 5 10
{
extern int x;
x=x+5;
printf(“%d\t”,x);
f();
}
#include<stdio.h>
int x;
void f()
{
int x;
x=x+5;
printf(“%d\t”,x);
} Output:
void main() xxxxx xxxxx
{
int x;
x=x+5;
printf(“%d\t”,x);
f();
}
static storage class(Static variables)

static datatype variable = initial value;


static int x=10;

• Static variable is initialized only once.


• Static variables have the lifetime over the
entire program.
• The static variable inside a function retains its
value during various calls.
#include<stdio.h>
void increment()
{
static int a=0;
a=a+1;
printf(“a=%d\n”,a); Output:
} a=1
void main() a=2
a=3
{
increment();
increment();
increment();
}
#include<stdio.h>
void increment()
{
int a=0;// auto int a=0;
a=a+1;
Output:
printf(“a=%d\n”,a); a=1
} a=1
void main() a=1

{
increment();
increment();
increment();
}
• Static storage class can be specified for extern
variables. For example:
static extern int x;
• When we declare a variable as extern static
variable, then that variable is accessible from
all the functions in this source file.
Qualifier Storage Initial Scope Lifetime
value
Auto CPU Garbage Inside End of block
memory function
Register CPU Garbage Inside End of block
registers function
Extern CPU 0 Throughout Till the end
memory of the
program
Static CPU 0 Inside End of
memory function program
Recursion
• Recursion is the process of defining a problem
(or the solution to a problem) in terms of (a
simpler version of) itself.
• For example, we can define the operation
"find your way home" as:
• If you are at home, stop moving.
• Take one step toward home.
• "find your way home".
Recursive functions
• Recursive function( Recursion) is defined as a
function that calls itself until terminating
condition.
• Recursive solution has two major cases:
• Base case, in which the problem is solved directly
which does not require a cal to itself.
• Recursive case, in which the problem is divided
into sub-parts. The function calls itself with
sub-parts of the problem. Then result is obtained
by combining the solutions of sub-parts.
Write a C program to calculate factorial of a
number using recursion.
• Base case, is when n=1, the factorial is 1
• Recursive case is factorial(n)= n* factorial(n-1)
Base case, is when n=1, the factorial is 1
Recursive case is factorial(n)= n* factorial(n-1)

#include<stdio.h> void main()


int factorial(int n) {
{ int n,fact;
printf("Enter a number\n");
if(n==1) scanf("%d", &n);
return 1 ; fact=factorial(n);
printf("Factorial is %d",fact);
else
}
return( n*factorial(n-1));
}
Write a program to print Fibonacci
series using recursion.
#include<stdio.h>
int fib(int n)
{
if ( n == 0)
return 0;
else if ( n == 1 )
return 1;
else
return fib(n-1)+fib(n-2);
}
void main()
{
int i,n,res;

printf("Enter a number\n");
scanf("%d",&n);
printf("Fibonacci series is "); Output:
for(i=0;i<n;i++) Enter a number
{ 3
res=fib(i); Fibonacci series is 0 1 1
printf("%d\t",res);
}
return 0;
}
• Write a program to calculate GCD using
recursive functions.

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy